ssh.c 376 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582
  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 "pageant.h" /* for AGENT_MAX_MSGLEN */
  12. #include "tree234.h"
  13. #include "storage.h"
  14. #include "marshal.h"
  15. #include "ssh.h"
  16. #include "sshcr.h"
  17. #include "sshbpp.h"
  18. #include "sshchan.h"
  19. #ifndef NO_GSSAPI
  20. #include "sshgssc.h"
  21. #include "sshgss.h"
  22. #define MIN_CTXT_LIFETIME 5 /* Avoid rekey with short lifetime (seconds) */
  23. #define GSS_KEX_CAPABLE (1<<0) /* Can do GSS KEX */
  24. #define GSS_CRED_UPDATED (1<<1) /* Cred updated since previous delegation */
  25. #define GSS_CTXT_EXPIRES (1<<2) /* Context expires before next timer */
  26. #define GSS_CTXT_MAYFAIL (1<<3) /* Context may expire during handshake */
  27. #endif
  28. #ifdef MPEXT
  29. #define queue_idempotent_callback(IC) queue_idempotent_callback(get_callback_set(&ssh->plugvt), IC)
  30. #endif
  31. static const char *const ssh2_disconnect_reasons[] = {
  32. NULL,
  33. "host not allowed to connect",
  34. "protocol error",
  35. "key exchange failed",
  36. "host authentication failed",
  37. "MAC error",
  38. "compression error",
  39. "service not available",
  40. "protocol version not supported",
  41. "host key not verifiable",
  42. "connection lost",
  43. "by application",
  44. "too many connections",
  45. "auth cancelled by user",
  46. "no more auth methods available",
  47. "illegal user name",
  48. };
  49. /*
  50. * Various remote-bug flags.
  51. */
  52. #define BUG_CHOKES_ON_SSH1_IGNORE 1
  53. #define BUG_SSH2_HMAC 2
  54. #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
  55. #define BUG_CHOKES_ON_RSA 8
  56. #define BUG_SSH2_RSA_PADDING 16
  57. #define BUG_SSH2_DERIVEKEY 32
  58. #define BUG_SSH2_REKEY 64
  59. #define BUG_SSH2_PK_SESSIONID 128
  60. #define BUG_SSH2_MAXPKT 256
  61. #define BUG_CHOKES_ON_SSH2_IGNORE 512
  62. #define BUG_CHOKES_ON_WINADJ 1024
  63. #define BUG_SENDS_LATE_REQUEST_REPLY 2048
  64. #define BUG_SSH2_OLDGEX 4096
  65. #define DH_MIN_SIZE 1024
  66. #define DH_MAX_SIZE 8192
  67. /*
  68. * Codes for terminal modes.
  69. * Most of these are the same in SSH-1 and SSH-2.
  70. * This list is derived from RFC 4254 and
  71. * SSH-1 RFC-1.2.31.
  72. */
  73. static const struct ssh_ttymode {
  74. const char* const mode;
  75. int opcode;
  76. enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
  77. } ssh_ttymodes[] = {
  78. /* "V" prefix discarded for special characters relative to SSH specs */
  79. { "INTR", 1, TTY_OP_CHAR },
  80. { "QUIT", 2, TTY_OP_CHAR },
  81. { "ERASE", 3, TTY_OP_CHAR },
  82. { "KILL", 4, TTY_OP_CHAR },
  83. { "EOF", 5, TTY_OP_CHAR },
  84. { "EOL", 6, TTY_OP_CHAR },
  85. { "EOL2", 7, TTY_OP_CHAR },
  86. { "START", 8, TTY_OP_CHAR },
  87. { "STOP", 9, TTY_OP_CHAR },
  88. { "SUSP", 10, TTY_OP_CHAR },
  89. { "DSUSP", 11, TTY_OP_CHAR },
  90. { "REPRINT", 12, TTY_OP_CHAR },
  91. { "WERASE", 13, TTY_OP_CHAR },
  92. { "LNEXT", 14, TTY_OP_CHAR },
  93. { "FLUSH", 15, TTY_OP_CHAR },
  94. { "SWTCH", 16, TTY_OP_CHAR },
  95. { "STATUS", 17, TTY_OP_CHAR },
  96. { "DISCARD", 18, TTY_OP_CHAR },
  97. { "IGNPAR", 30, TTY_OP_BOOL },
  98. { "PARMRK", 31, TTY_OP_BOOL },
  99. { "INPCK", 32, TTY_OP_BOOL },
  100. { "ISTRIP", 33, TTY_OP_BOOL },
  101. { "INLCR", 34, TTY_OP_BOOL },
  102. { "IGNCR", 35, TTY_OP_BOOL },
  103. { "ICRNL", 36, TTY_OP_BOOL },
  104. { "IUCLC", 37, TTY_OP_BOOL },
  105. { "IXON", 38, TTY_OP_BOOL },
  106. { "IXANY", 39, TTY_OP_BOOL },
  107. { "IXOFF", 40, TTY_OP_BOOL },
  108. { "IMAXBEL", 41, TTY_OP_BOOL },
  109. { "IUTF8", 42, TTY_OP_BOOL },
  110. { "ISIG", 50, TTY_OP_BOOL },
  111. { "ICANON", 51, TTY_OP_BOOL },
  112. { "XCASE", 52, TTY_OP_BOOL },
  113. { "ECHO", 53, TTY_OP_BOOL },
  114. { "ECHOE", 54, TTY_OP_BOOL },
  115. { "ECHOK", 55, TTY_OP_BOOL },
  116. { "ECHONL", 56, TTY_OP_BOOL },
  117. { "NOFLSH", 57, TTY_OP_BOOL },
  118. { "TOSTOP", 58, TTY_OP_BOOL },
  119. { "IEXTEN", 59, TTY_OP_BOOL },
  120. { "ECHOCTL", 60, TTY_OP_BOOL },
  121. { "ECHOKE", 61, TTY_OP_BOOL },
  122. { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
  123. { "OPOST", 70, TTY_OP_BOOL },
  124. { "OLCUC", 71, TTY_OP_BOOL },
  125. { "ONLCR", 72, TTY_OP_BOOL },
  126. { "OCRNL", 73, TTY_OP_BOOL },
  127. { "ONOCR", 74, TTY_OP_BOOL },
  128. { "ONLRET", 75, TTY_OP_BOOL },
  129. { "CS7", 90, TTY_OP_BOOL },
  130. { "CS8", 91, TTY_OP_BOOL },
  131. { "PARENB", 92, TTY_OP_BOOL },
  132. { "PARODD", 93, TTY_OP_BOOL }
  133. };
  134. /* Miscellaneous other tty-related constants. */
  135. #define SSH_TTY_OP_END 0
  136. /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
  137. #define SSH1_TTY_OP_ISPEED 192
  138. #define SSH1_TTY_OP_OSPEED 193
  139. #define SSH2_TTY_OP_ISPEED 128
  140. #define SSH2_TTY_OP_OSPEED 129
  141. /* Helper functions for parsing tty-related config. */
  142. static unsigned int ssh_tty_parse_specchar(char *s)
  143. {
  144. unsigned int ret;
  145. if (*s) {
  146. char *next = NULL;
  147. ret = ctrlparse(s, &next);
  148. if (!next) ret = s[0];
  149. } else {
  150. ret = 255; /* special value meaning "don't set" */
  151. }
  152. return ret;
  153. }
  154. static unsigned int ssh_tty_parse_boolean(char *s)
  155. {
  156. if (stricmp(s, "yes") == 0 ||
  157. stricmp(s, "on") == 0 ||
  158. stricmp(s, "true") == 0 ||
  159. stricmp(s, "+") == 0)
  160. return 1; /* true */
  161. else if (stricmp(s, "no") == 0 ||
  162. stricmp(s, "off") == 0 ||
  163. stricmp(s, "false") == 0 ||
  164. stricmp(s, "-") == 0)
  165. return 0; /* false */
  166. else
  167. return (atoi(s) != 0);
  168. }
  169. /* Safely convert rekey_time to unsigned long minutes */
  170. static unsigned long rekey_mins(int rekey_time, unsigned long def)
  171. {
  172. if (rekey_time < 0 || rekey_time > MAX_TICK_MINS)
  173. rekey_time = def;
  174. return (unsigned long)rekey_time;
  175. }
  176. #define translate(x) if (type == x) return #x
  177. #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
  178. #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
  179. const char *ssh1_pkt_type(int type)
  180. {
  181. translate(SSH1_MSG_DISCONNECT);
  182. translate(SSH1_SMSG_PUBLIC_KEY);
  183. translate(SSH1_CMSG_SESSION_KEY);
  184. translate(SSH1_CMSG_USER);
  185. translate(SSH1_CMSG_AUTH_RSA);
  186. translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
  187. translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
  188. translate(SSH1_CMSG_AUTH_PASSWORD);
  189. translate(SSH1_CMSG_REQUEST_PTY);
  190. translate(SSH1_CMSG_WINDOW_SIZE);
  191. translate(SSH1_CMSG_EXEC_SHELL);
  192. translate(SSH1_CMSG_EXEC_CMD);
  193. translate(SSH1_SMSG_SUCCESS);
  194. translate(SSH1_SMSG_FAILURE);
  195. translate(SSH1_CMSG_STDIN_DATA);
  196. translate(SSH1_SMSG_STDOUT_DATA);
  197. translate(SSH1_SMSG_STDERR_DATA);
  198. translate(SSH1_CMSG_EOF);
  199. translate(SSH1_SMSG_EXIT_STATUS);
  200. translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
  201. translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
  202. translate(SSH1_MSG_CHANNEL_DATA);
  203. translate(SSH1_MSG_CHANNEL_CLOSE);
  204. translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
  205. translate(SSH1_SMSG_X11_OPEN);
  206. translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
  207. translate(SSH1_MSG_PORT_OPEN);
  208. translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
  209. translate(SSH1_SMSG_AGENT_OPEN);
  210. translate(SSH1_MSG_IGNORE);
  211. translate(SSH1_CMSG_EXIT_CONFIRMATION);
  212. translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
  213. translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
  214. translate(SSH1_MSG_DEBUG);
  215. translate(SSH1_CMSG_REQUEST_COMPRESSION);
  216. translate(SSH1_CMSG_AUTH_TIS);
  217. translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
  218. translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
  219. translate(SSH1_CMSG_AUTH_CCARD);
  220. translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
  221. translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
  222. return "unknown";
  223. }
  224. const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
  225. {
  226. translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
  227. translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
  228. translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
  229. translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
  230. translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
  231. translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
  232. translate(SSH2_MSG_DISCONNECT);
  233. translate(SSH2_MSG_IGNORE);
  234. translate(SSH2_MSG_UNIMPLEMENTED);
  235. translate(SSH2_MSG_DEBUG);
  236. translate(SSH2_MSG_SERVICE_REQUEST);
  237. translate(SSH2_MSG_SERVICE_ACCEPT);
  238. translate(SSH2_MSG_KEXINIT);
  239. translate(SSH2_MSG_NEWKEYS);
  240. translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
  241. translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
  242. translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
  243. translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
  244. translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
  245. translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
  246. translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
  247. translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
  248. translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
  249. translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
  250. translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
  251. translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
  252. translatek(SSH2_MSG_KEXGSS_INIT, SSH2_PKTCTX_GSSKEX);
  253. translatek(SSH2_MSG_KEXGSS_CONTINUE, SSH2_PKTCTX_GSSKEX);
  254. translatek(SSH2_MSG_KEXGSS_COMPLETE, SSH2_PKTCTX_GSSKEX);
  255. translatek(SSH2_MSG_KEXGSS_HOSTKEY, SSH2_PKTCTX_GSSKEX);
  256. translatek(SSH2_MSG_KEXGSS_ERROR, SSH2_PKTCTX_GSSKEX);
  257. translatek(SSH2_MSG_KEXGSS_GROUPREQ, SSH2_PKTCTX_GSSKEX);
  258. translatek(SSH2_MSG_KEXGSS_GROUP, SSH2_PKTCTX_GSSKEX);
  259. translate(SSH2_MSG_USERAUTH_REQUEST);
  260. translate(SSH2_MSG_USERAUTH_FAILURE);
  261. translate(SSH2_MSG_USERAUTH_SUCCESS);
  262. translate(SSH2_MSG_USERAUTH_BANNER);
  263. translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
  264. translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
  265. translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
  266. translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
  267. translate(SSH2_MSG_GLOBAL_REQUEST);
  268. translate(SSH2_MSG_REQUEST_SUCCESS);
  269. translate(SSH2_MSG_REQUEST_FAILURE);
  270. translate(SSH2_MSG_CHANNEL_OPEN);
  271. translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
  272. translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
  273. translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  274. translate(SSH2_MSG_CHANNEL_DATA);
  275. translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
  276. translate(SSH2_MSG_CHANNEL_EOF);
  277. translate(SSH2_MSG_CHANNEL_CLOSE);
  278. translate(SSH2_MSG_CHANNEL_REQUEST);
  279. translate(SSH2_MSG_CHANNEL_SUCCESS);
  280. translate(SSH2_MSG_CHANNEL_FAILURE);
  281. return "unknown";
  282. }
  283. #undef translate
  284. #undef translatec
  285. /* Enumeration values for fields in SSH-1 packets */
  286. enum {
  287. PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
  288. };
  289. static void ssh_pkt_ensure(struct PktOut *, int length);
  290. static void ssh_pkt_adddata(struct PktOut *, const void *data, int len);
  291. static void ssh2_pkt_send(Ssh, struct PktOut *);
  292. static void do_ssh1_login(void *vctx);
  293. static void do_ssh2_userauth(void *vctx);
  294. static void ssh2_connection_setup(Ssh ssh);
  295. static void do_ssh2_connection(void *vctx);
  296. static void ssh_channel_init(struct ssh_channel *c);
  297. static struct ssh_channel *ssh_channel_msg(Ssh ssh, PktIn *pktin);
  298. static void ssh_channel_got_eof(struct ssh_channel *c);
  299. static void ssh2_channel_check_close(struct ssh_channel *c);
  300. static void ssh_channel_close_local(struct ssh_channel *c, char const *reason);
  301. static void ssh_channel_destroy(struct ssh_channel *c);
  302. static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize);
  303. static void ssh2_msg_something_unimplemented(Ssh ssh, PktIn *pktin);
  304. static void ssh2_general_packet_processing(Ssh ssh, PktIn *pktin);
  305. static void ssh1_login_input(Ssh ssh);
  306. static void ssh2_userauth_input(Ssh ssh);
  307. static void ssh2_connection_input(Ssh ssh);
  308. struct ssh_signkey_with_user_pref_id {
  309. const ssh_keyalg *alg;
  310. int id;
  311. };
  312. const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
  313. { &ssh_ecdsa_ed25519, HK_ED25519 },
  314. { &ssh_ecdsa_nistp256, HK_ECDSA },
  315. { &ssh_ecdsa_nistp384, HK_ECDSA },
  316. { &ssh_ecdsa_nistp521, HK_ECDSA },
  317. /* Changed order to match WinSCP default preference list for SshHostKeyList() */
  318. { &ssh_rsa, HK_RSA },
  319. { &ssh_dss, HK_DSA },
  320. };
  321. const static struct ssh_mac *const macs[] = {
  322. &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
  323. };
  324. const static struct ssh_mac *const buggymacs[] = {
  325. &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
  326. };
  327. static void *ssh_comp_none_init(void)
  328. {
  329. return NULL;
  330. }
  331. static void ssh_comp_none_cleanup(void *handle)
  332. {
  333. }
  334. static void ssh_comp_none_block(void *handle, unsigned char *block, int len,
  335. unsigned char **outblock, int *outlen,
  336. int minlen)
  337. {
  338. }
  339. static int ssh_decomp_none_block(void *handle, unsigned char *block, int len,
  340. unsigned char **outblock, int *outlen)
  341. {
  342. return 0;
  343. }
  344. const static struct ssh_compress ssh_comp_none = {
  345. "none", NULL,
  346. ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
  347. ssh_comp_none_init, ssh_comp_none_cleanup, ssh_decomp_none_block,
  348. NULL
  349. };
  350. extern const struct ssh_compress ssh_zlib;
  351. const static struct ssh_compress *const compressions[] = {
  352. &ssh_zlib, &ssh_comp_none
  353. };
  354. typedef void (*handler_fn_t)(Ssh ssh, PktIn *pktin);
  355. typedef void (*chandler_fn_t)(Ssh ssh, PktIn *pktin, void *ctx);
  356. typedef void (*cchandler_fn_t)(struct ssh_channel *, PktIn *, void *);
  357. /*
  358. * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
  359. * handlers.
  360. */
  361. struct outstanding_channel_request {
  362. cchandler_fn_t handler;
  363. void *ctx;
  364. struct outstanding_channel_request *next;
  365. };
  366. /*
  367. * 2-3-4 tree storing channels.
  368. */
  369. struct ssh_channel {
  370. Ssh ssh; /* pointer back to main context */
  371. unsigned remoteid, localid;
  372. int type;
  373. /* True if we opened this channel but server hasn't confirmed. */
  374. int halfopen;
  375. /*
  376. * In SSH-1, this value contains four bits:
  377. *
  378. * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
  379. * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
  380. * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
  381. * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
  382. *
  383. * A channel is completely finished with when all four bits are set.
  384. *
  385. * In SSH-2, the four bits mean:
  386. *
  387. * 1 We have sent SSH2_MSG_CHANNEL_EOF.
  388. * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
  389. * 4 We have received SSH2_MSG_CHANNEL_EOF.
  390. * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
  391. *
  392. * A channel is completely finished with when we have both sent
  393. * and received CLOSE.
  394. *
  395. * The symbolic constants below use the SSH-2 terminology, which
  396. * is a bit confusing in SSH-1, but we have to use _something_.
  397. */
  398. #define CLOSES_SENT_EOF 1
  399. #define CLOSES_SENT_CLOSE 2
  400. #define CLOSES_RCVD_EOF 4
  401. #define CLOSES_RCVD_CLOSE 8
  402. int closes;
  403. /*
  404. * This flag indicates that an EOF is pending on the outgoing side
  405. * of the channel: that is, wherever we're getting the data for
  406. * this channel has sent us some data followed by EOF. We can't
  407. * actually send the EOF until we've finished sending the data, so
  408. * we set this flag instead to remind us to do so once our buffer
  409. * is clear.
  410. */
  411. int pending_eof;
  412. /*
  413. * True if this channel is causing the underlying connection to be
  414. * throttled.
  415. */
  416. int throttling_conn;
  417. /*
  418. * True if we currently have backed-up data on the direction of
  419. * this channel pointing out of the SSH connection, and therefore
  420. * would prefer the 'Channel' implementation not to read further
  421. * local input if possible.
  422. */
  423. int throttled_by_backlog;
  424. union {
  425. struct ssh2_data_channel {
  426. bufchain outbuffer;
  427. unsigned remwindow, remmaxpkt;
  428. /* locwindow is signed so we can cope with excess data. */
  429. int locwindow, locmaxwin;
  430. /*
  431. * remlocwin is the amount of local window that we think
  432. * the remote end had available to it after it sent the
  433. * last data packet or window adjust ack.
  434. */
  435. int remlocwin;
  436. /*
  437. * These store the list of channel requests that haven't
  438. * been acked.
  439. */
  440. struct outstanding_channel_request *chanreq_head, *chanreq_tail;
  441. enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
  442. } v2;
  443. } v;
  444. ssh_sharing_connstate *sharectx; /* sharing context, if this is a
  445. * downstream channel */
  446. Channel *chan; /* handle the client side of this channel, if not */
  447. };
  448. /*
  449. * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
  450. * use this structure in different ways, reflecting SSH-2's
  451. * altogether saner approach to port forwarding.
  452. *
  453. * In SSH-1, you arrange a remote forwarding by sending the server
  454. * the remote port number, and the local destination host:port.
  455. * When a connection comes in, the server sends you back that
  456. * host:port pair, and you connect to it. This is a ready-made
  457. * security hole if you're not on the ball: a malicious server
  458. * could send you back _any_ host:port pair, so if you trustingly
  459. * connect to the address it gives you then you've just opened the
  460. * entire inside of your corporate network just by connecting
  461. * through it to a dodgy SSH server. Hence, we must store a list of
  462. * host:port pairs we _are_ trying to forward to, and reject a
  463. * connection request from the server if it's not in the list.
  464. *
  465. * In SSH-2, each side of the connection minds its own business and
  466. * doesn't send unnecessary information to the other. You arrange a
  467. * remote forwarding by sending the server just the remote port
  468. * number. When a connection comes in, the server tells you which
  469. * of its ports was connected to; and _you_ have to remember what
  470. * local host:port pair went with that port number.
  471. *
  472. * Hence, in SSH-1 this structure is indexed by destination
  473. * host:port pair, whereas in SSH-2 it is indexed by source port.
  474. */
  475. struct ssh_portfwd; /* forward declaration */
  476. struct ssh_rportfwd {
  477. unsigned sport, dport;
  478. char *shost, *dhost;
  479. char *sportdesc;
  480. ssh_sharing_connstate *share_ctx;
  481. struct ssh_portfwd *pfrec;
  482. };
  483. static void free_rportfwd(struct ssh_rportfwd *pf)
  484. {
  485. if (pf) {
  486. sfree(pf->sportdesc);
  487. sfree(pf->shost);
  488. sfree(pf->dhost);
  489. sfree(pf);
  490. }
  491. }
  492. /*
  493. * Separately to the rportfwd tree (which is for looking up port
  494. * open requests from the server), a tree of _these_ structures is
  495. * used to keep track of all the currently open port forwardings,
  496. * so that we can reconfigure in mid-session if the user requests
  497. * it.
  498. */
  499. struct ssh_portfwd {
  500. enum { DESTROY, KEEP, CREATE } status;
  501. int type;
  502. unsigned sport, dport;
  503. char *saddr, *daddr;
  504. char *sserv, *dserv;
  505. struct ssh_rportfwd *remote;
  506. int addressfamily;
  507. struct PortListener *local;
  508. };
  509. #define free_portfwd(pf) ( \
  510. ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
  511. sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
  512. static void ssh1_protocol_setup(Ssh ssh);
  513. static void ssh2_protocol_setup(Ssh ssh);
  514. static void ssh2_bare_connection_protocol_setup(Ssh ssh);
  515. static void ssh_size(Backend *be, int width, int height);
  516. static void ssh_special(Backend *be, Telnet_Special);
  517. static int ssh2_try_send(struct ssh_channel *c);
  518. static int ssh_send_channel_data(struct ssh_channel *c,
  519. const char *buf, int len);
  520. static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
  521. static void ssh2_set_window(struct ssh_channel *c, int newwin);
  522. static int ssh_sendbuffer(Backend *be);
  523. static int ssh_do_close(Ssh ssh, int notify_exit);
  524. static void ssh2_timer(void *ctx, unsigned long now);
  525. static int ssh2_timer_update(Ssh ssh, unsigned long rekey_time);
  526. #ifndef NO_GSSAPI
  527. static void ssh2_gss_update(Ssh ssh, int definitely_rekeying);
  528. static PktOut *ssh2_gss_authpacket(Ssh ssh, Ssh_gss_ctx gss_ctx,
  529. const char *authtype);
  530. #endif
  531. static void ssh2_msg_unexpected(Ssh ssh, PktIn *pktin);
  532. void pq_init(struct PacketQueue *pq)
  533. {
  534. pq->end.next = pq->end.prev = &pq->end;
  535. }
  536. void pq_push(struct PacketQueue *pq, PktIn *pkt)
  537. {
  538. PacketQueueNode *node = &pkt->qnode;
  539. assert(!node->next);
  540. assert(!node->prev);
  541. node->next = &pq->end;
  542. node->prev = pq->end.prev;
  543. node->next->prev = node;
  544. node->prev->next = node;
  545. }
  546. void pq_push_front(struct PacketQueue *pq, PktIn *pkt)
  547. {
  548. PacketQueueNode *node = &pkt->qnode;
  549. assert(!node->next);
  550. assert(!node->prev);
  551. node->prev = &pq->end;
  552. node->next = pq->end.next;
  553. node->next->prev = node;
  554. node->prev->next = node;
  555. }
  556. PktIn *pq_peek(struct PacketQueue *pq)
  557. {
  558. if (pq->end.next == &pq->end)
  559. return NULL;
  560. return FROMFIELD(pq->end.next, PktIn, qnode);
  561. }
  562. PktIn *pq_pop(struct PacketQueue *pq)
  563. {
  564. PacketQueueNode *node = pq->end.next;
  565. if (node == &pq->end)
  566. return NULL;
  567. node->next->prev = node->prev;
  568. node->prev->next = node->next;
  569. node->prev = node->next = NULL;
  570. return FROMFIELD(node, PktIn, qnode);
  571. }
  572. void pq_clear(struct PacketQueue *pq)
  573. {
  574. PktIn *pkt;
  575. while ((pkt = pq_pop(pq)) != NULL)
  576. ssh_unref_packet(pkt);
  577. }
  578. int pq_empty_on_to_front_of(struct PacketQueue *src, struct PacketQueue *dest)
  579. {
  580. struct PacketQueueNode *srcfirst, *srclast;
  581. if (src->end.next == &src->end)
  582. return FALSE;
  583. srcfirst = src->end.next;
  584. srclast = src->end.prev;
  585. srcfirst->prev = &dest->end;
  586. srclast->next = dest->end.next;
  587. srcfirst->prev->next = srcfirst;
  588. srclast->next->prev = srclast;
  589. src->end.next = src->end.prev = &src->end;
  590. return TRUE;
  591. }
  592. struct queued_handler;
  593. struct queued_handler {
  594. int msg1, msg2;
  595. chandler_fn_t handler;
  596. void *ctx;
  597. struct queued_handler *next;
  598. };
  599. /*
  600. * Enumeration of high-level classes of reason why we might need to do
  601. * a repeat key exchange. The full detailed reason in human-readable
  602. * form for the Event Log is kept in ssh->rekey_reason, but
  603. * ssh->rekey_class is a variable with this enum type which is used to
  604. * discriminate between classes of reason that the code needs to treat
  605. * differently.
  606. *
  607. * RK_NONE == 0 is the value indicating that no rekey is currently
  608. * needed at all. RK_INITIAL indicates that we haven't even done the
  609. * _first_ key exchange yet. RK_NORMAL is the usual case.
  610. * RK_GSS_UPDATE indicates that we're rekeying because we've just got
  611. * new GSSAPI credentials (hence there's no point in doing a
  612. * preliminary check for new GSS creds, because we already know the
  613. * answer); RK_POST_USERAUTH indicates that _if_ we're going to need a
  614. * post-userauth immediate rekey for any reason, this is the moment to
  615. * do it.
  616. *
  617. * So RK_POST_USERAUTH only tells the transport layer to _consider_
  618. * rekeying, not to definitely do it. Also, that one enum value is
  619. * special in that do_ssh2_transport fills in the reason text after it
  620. * decides whether it needs a rekey at all. In the other cases,
  621. * rekey_reason is set up at the same time as rekey_class.
  622. */
  623. enum RekeyClass {
  624. RK_NONE = 0,
  625. RK_INITIAL,
  626. RK_NORMAL,
  627. RK_POST_USERAUTH,
  628. RK_GSS_UPDATE
  629. };
  630. struct ssh_tag {
  631. char *v_c, *v_s;
  632. void *exhash;
  633. BinarySink *exhash_bs;
  634. Socket s;
  635. const Plug_vtable *plugvt;
  636. Backend backend;
  637. Ldisc *ldisc;
  638. LogContext *logctx;
  639. unsigned char session_key[32];
  640. int v1_remote_protoflags;
  641. int v1_local_protoflags;
  642. int agentfwd_enabled;
  643. int X11_fwd_enabled;
  644. int remote_bugs;
  645. const struct ssh_kex *kex;
  646. const ssh_keyalg *hostkey_alg;
  647. char *hostkey_str; /* string representation, for easy checking in rekeys */
  648. unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
  649. int v2_session_id_len;
  650. int v2_cbc_ignore_workaround;
  651. int v2_out_cipherblksize;
  652. void *kex_ctx;
  653. int bare_connection;
  654. int attempting_connshare;
  655. ssh_sharing_state *connshare;
  656. char *savedhost;
  657. int savedport;
  658. int send_ok;
  659. int echoing, editing;
  660. int session_started;
  661. Frontend *frontend;
  662. int ospeed, ispeed; /* temporaries */
  663. int term_width, term_height;
  664. tree234 *channels; /* indexed by local id */
  665. struct ssh_channel *mainchan; /* primary session channel */
  666. int ncmode; /* is primary channel direct-tcpip? */
  667. int exitcode;
  668. int close_expected;
  669. int clean_exit;
  670. int disconnect_message_seen;
  671. tree234 *rportfwds, *portfwds;
  672. enum {
  673. SSH_STATE_PREPACKET,
  674. SSH_STATE_BEFORE_SIZE,
  675. SSH_STATE_INTERMED,
  676. SSH_STATE_SESSION,
  677. SSH_STATE_CLOSED
  678. } state;
  679. int size_needed, eof_needed;
  680. int sent_console_eof;
  681. int got_pty; /* affects EOF behaviour on main channel */
  682. PktOut **queue;
  683. int queuelen, queuesize;
  684. int queueing;
  685. /*
  686. * Gross hack: pscp will try to start SFTP but fall back to
  687. * scp1 if that fails. This variable is the means by which
  688. * scp.c can reach into the SSH code and find out which one it
  689. * got.
  690. */
  691. int fallback_cmd;
  692. bufchain banner; /* accumulates banners during do_ssh2_userauth */
  693. struct X11Display *x11disp;
  694. struct X11FakeAuth *x11auth;
  695. tree234 *x11authtree;
  696. int version;
  697. int conn_throttle_count;
  698. int overall_bufsize;
  699. int throttled_all;
  700. int v1_stdout_throttling;
  701. int do_ssh1_connection_crstate;
  702. void *do_ssh_init_state;
  703. void *do_ssh1_login_state;
  704. void *do_ssh2_transport_state;
  705. void *do_ssh2_userauth_state;
  706. void *do_ssh2_connection_state;
  707. void *do_ssh_connection_init_state;
  708. bufchain incoming_data;
  709. struct IdempotentCallback incoming_data_consumer;
  710. int incoming_data_seen_eof;
  711. char *incoming_data_eof_message;
  712. struct PacketQueue pq_full;
  713. struct IdempotentCallback pq_full_consumer;
  714. struct PacketQueue pq_ssh1_login;
  715. struct IdempotentCallback ssh1_login_icb;
  716. struct PacketQueue pq_ssh1_connection;
  717. struct IdempotentCallback ssh1_connection_icb;
  718. struct PacketQueue pq_ssh2_transport;
  719. struct IdempotentCallback ssh2_transport_icb;
  720. struct PacketQueue pq_ssh2_userauth;
  721. struct IdempotentCallback ssh2_userauth_icb;
  722. struct PacketQueue pq_ssh2_connection;
  723. struct IdempotentCallback ssh2_connection_icb;
  724. bufchain user_input;
  725. struct IdempotentCallback user_input_consumer;
  726. bufchain outgoing_data;
  727. struct IdempotentCallback outgoing_data_sender;
  728. const char *rekey_reason;
  729. enum RekeyClass rekey_class;
  730. PacketLogSettings pls;
  731. BinaryPacketProtocol *bpp;
  732. void (*general_packet_processing)(Ssh ssh, PktIn *pkt);
  733. void (*current_incoming_data_fn) (Ssh ssh);
  734. void (*current_user_input_fn) (Ssh ssh);
  735. /*
  736. * We maintain our own copy of a Conf structure here. That way,
  737. * when we're passed a new one for reconfiguration, we can check
  738. * the differences and potentially reconfigure port forwardings
  739. * etc in mid-session.
  740. */
  741. Conf *conf;
  742. /*
  743. * Dynamically allocated username string created during SSH
  744. * login. Stored in here rather than in the coroutine state so
  745. * that it'll be reliably freed if we shut down the SSH session
  746. * at some unexpected moment.
  747. */
  748. char *username;
  749. /*
  750. * Used to transfer data back from async callbacks.
  751. */
  752. void *agent_response;
  753. int agent_response_len;
  754. int user_response;
  755. /*
  756. * The SSH connection can be set as `frozen', meaning we are
  757. * not currently accepting incoming data from the network.
  758. */
  759. int frozen;
  760. /*
  761. * Dispatch table for packet types that we may have to deal
  762. * with at any time.
  763. */
  764. handler_fn_t packet_dispatch[SSH_MAX_MSG];
  765. /*
  766. * Queues of one-off handler functions for success/failure
  767. * indications from a request.
  768. */
  769. struct queued_handler *qhead, *qtail;
  770. handler_fn_t q_saved_handler1, q_saved_handler2;
  771. /*
  772. * This module deals with sending keepalives.
  773. */
  774. Pinger pinger;
  775. /*
  776. * Track incoming and outgoing data sizes and time, for
  777. * size-based rekeys.
  778. */
  779. unsigned long incoming_data_size, outgoing_data_size;
  780. unsigned long max_data_size;
  781. int kex_in_progress;
  782. unsigned long next_rekey, last_rekey;
  783. const char *deferred_rekey_reason;
  784. /*
  785. * Fully qualified host name, which we need if doing GSSAPI.
  786. */
  787. char *fullhostname;
  788. #ifndef NO_GSSAPI
  789. /*
  790. * GSSAPI libraries for this session. We need them at key exchange
  791. * and userauth time.
  792. *
  793. * And the gss_ctx we setup at initial key exchange will be used
  794. * during gssapi-keyex userauth time as well.
  795. */
  796. struct ssh_gss_liblist *gsslibs;
  797. struct ssh_gss_library *gsslib;
  798. int gss_status;
  799. time_t gss_cred_expiry; /* Re-delegate if newer */
  800. unsigned long gss_ctxt_lifetime; /* Re-delegate when short */
  801. Ssh_gss_name gss_srv_name; /* Cached for KEXGSS */
  802. Ssh_gss_ctx gss_ctx; /* Saved for gssapi-keyex */
  803. tree234 *transient_hostkey_cache;
  804. #endif
  805. int gss_kex_used; /* outside ifdef; always FALSE if NO_GSSAPI */
  806. /*
  807. * The last list returned from get_specials.
  808. */
  809. struct telnet_special *specials;
  810. /*
  811. * List of host key algorithms for which we _don't_ have a stored
  812. * host key. These are indices into the main hostkey_algs[] array
  813. */
  814. int uncert_hostkeys[lenof(hostkey_algs)];
  815. int n_uncert_hostkeys;
  816. /*
  817. * Flag indicating that the current rekey is intended to finish
  818. * with a newly cross-certified host key.
  819. */
  820. int cross_certifying;
  821. /*
  822. * Any asynchronous query to our SSH agent that we might have in
  823. * flight from the main authentication loop. (Queries from
  824. * agent-forwarding channels live in their channel structure.)
  825. */
  826. agent_pending_query *auth_agent_query;
  827. int need_random_unref;
  828. };
  829. static const char *ssh_pkt_type(Ssh ssh, int type)
  830. {
  831. if (ssh->version == 1)
  832. return ssh1_pkt_type(type);
  833. else
  834. return ssh2_pkt_type(ssh->pls.kctx, ssh->pls.actx, type);
  835. }
  836. Frontend *ssh_get_frontend(Ssh ssh)
  837. {
  838. return ssh->frontend;
  839. }
  840. #define logevent(s) logevent(ssh->frontend, s)
  841. /* logevent, only printf-formatted. */
  842. static void logeventf(Ssh ssh, const char *fmt, ...)
  843. {
  844. va_list ap;
  845. char *buf;
  846. va_start(ap, fmt);
  847. buf = dupvprintf(fmt, ap);
  848. va_end(ap);
  849. logevent(buf);
  850. sfree(buf);
  851. }
  852. static void bomb_out(Ssh ssh, char *text)
  853. {
  854. ssh_do_close(ssh, FALSE);
  855. logevent(text);
  856. connection_fatal(ssh->frontend, "%s", text);
  857. sfree(text);
  858. }
  859. #define bombout(msg) bomb_out(ssh, dupprintf msg)
  860. /* Helper function for common bits of parsing ttymodes. */
  861. static void parse_ttymodes(
  862. BinarySink *bs, Ssh ssh,
  863. void (*do_mode)(BinarySink *, const struct ssh_ttymode *, char *))
  864. {
  865. int i;
  866. const struct ssh_ttymode *mode;
  867. char *val;
  868. for (i = 0; i < lenof(ssh_ttymodes); i++) {
  869. mode = ssh_ttymodes + i;
  870. /* Every mode known to the current version of the code should be
  871. * mentioned; this was ensured when settings were loaded. */
  872. val = conf_get_str_str(ssh->conf, CONF_ttymodes, mode->mode);
  873. /*
  874. * val[0] can be
  875. * - 'V', indicating that an explicit value follows it;
  876. * - 'A', indicating that we should pass the value through from
  877. * the local environment via get_ttymode; or
  878. * - 'N', indicating that we should explicitly not send this
  879. * mode.
  880. */
  881. if (val[0] == 'A') {
  882. val = get_ttymode(ssh->frontend, mode->mode);
  883. if (val) {
  884. do_mode(bs, mode, val);
  885. sfree(val);
  886. }
  887. } else if (val[0] == 'V') {
  888. do_mode(bs, mode, val + 1); /* skip the 'V' */
  889. } /* else 'N', or something from the future we don't understand */
  890. }
  891. }
  892. static int ssh_channelcmp(void *av, void *bv)
  893. {
  894. struct ssh_channel *a = (struct ssh_channel *) av;
  895. struct ssh_channel *b = (struct ssh_channel *) bv;
  896. if (a->localid < b->localid)
  897. return -1;
  898. if (a->localid > b->localid)
  899. return +1;
  900. return 0;
  901. }
  902. static int ssh_channelfind(void *av, void *bv)
  903. {
  904. unsigned *a = (unsigned *) av;
  905. struct ssh_channel *b = (struct ssh_channel *) bv;
  906. if (*a < b->localid)
  907. return -1;
  908. if (*a > b->localid)
  909. return +1;
  910. return 0;
  911. }
  912. static int ssh_rportcmp_ssh1(void *av, void *bv)
  913. {
  914. struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
  915. struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
  916. int i;
  917. if ( (i = strcmp(a->dhost, b->dhost)) != 0)
  918. return i < 0 ? -1 : +1;
  919. if (a->dport > b->dport)
  920. return +1;
  921. if (a->dport < b->dport)
  922. return -1;
  923. return 0;
  924. }
  925. static int ssh_rportcmp_ssh2(void *av, void *bv)
  926. {
  927. struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
  928. struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
  929. int i;
  930. if ( (i = strcmp(a->shost, b->shost)) != 0)
  931. return i < 0 ? -1 : +1;
  932. if (a->sport > b->sport)
  933. return +1;
  934. if (a->sport < b->sport)
  935. return -1;
  936. return 0;
  937. }
  938. /*
  939. * Special form of strcmp which can cope with NULL inputs. NULL is
  940. * defined to sort before even the empty string.
  941. */
  942. static int nullstrcmp(const char *a, const char *b)
  943. {
  944. if (a == NULL && b == NULL)
  945. return 0;
  946. if (a == NULL)
  947. return -1;
  948. if (b == NULL)
  949. return +1;
  950. return strcmp(a, b);
  951. }
  952. static int ssh_portcmp(void *av, void *bv)
  953. {
  954. struct ssh_portfwd *a = (struct ssh_portfwd *) av;
  955. struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
  956. int i;
  957. if (a->type > b->type)
  958. return +1;
  959. if (a->type < b->type)
  960. return -1;
  961. if (a->addressfamily > b->addressfamily)
  962. return +1;
  963. if (a->addressfamily < b->addressfamily)
  964. return -1;
  965. if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
  966. return i < 0 ? -1 : +1;
  967. if (a->sport > b->sport)
  968. return +1;
  969. if (a->sport < b->sport)
  970. return -1;
  971. if (a->type != 'D') {
  972. if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
  973. return i < 0 ? -1 : +1;
  974. if (a->dport > b->dport)
  975. return +1;
  976. if (a->dport < b->dport)
  977. return -1;
  978. }
  979. return 0;
  980. }
  981. static int alloc_channel_id(Ssh ssh)
  982. {
  983. const unsigned CHANNEL_NUMBER_OFFSET = 256;
  984. unsigned low, high, mid;
  985. int tsize;
  986. struct ssh_channel *c;
  987. /*
  988. * First-fit allocation of channel numbers: always pick the
  989. * lowest unused one. To do this, binary-search using the
  990. * counted B-tree to find the largest channel ID which is in a
  991. * contiguous sequence from the beginning. (Precisely
  992. * everything in that sequence must have ID equal to its tree
  993. * index plus CHANNEL_NUMBER_OFFSET.)
  994. */
  995. tsize = count234(ssh->channels);
  996. low = -1;
  997. high = tsize;
  998. while (high - low > 1) {
  999. mid = (high + low) / 2;
  1000. c = index234(ssh->channels, mid);
  1001. if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
  1002. low = mid; /* this one is fine */
  1003. else
  1004. high = mid; /* this one is past it */
  1005. }
  1006. /*
  1007. * Now low points to either -1, or the tree index of the
  1008. * largest ID in the initial sequence.
  1009. */
  1010. {
  1011. unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
  1012. assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
  1013. }
  1014. return low + 1 + CHANNEL_NUMBER_OFFSET;
  1015. }
  1016. static void c_write_stderr(int trusted, const void *vbuf, int len)
  1017. {
  1018. const char *buf = (const char *)vbuf;
  1019. int i;
  1020. for (i = 0; i < len; i++)
  1021. if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
  1022. fputc(buf[i], stderr);
  1023. }
  1024. static void c_write(Ssh ssh, const void *buf, int len)
  1025. {
  1026. if (flags & FLAG_STDERR)
  1027. c_write_stderr(1, buf, len);
  1028. else
  1029. #ifdef MPEXT
  1030. from_backend(ssh->frontend, -1, buf, len);
  1031. #else
  1032. from_backend(ssh->frontend, 1, buf, len);
  1033. #endif
  1034. }
  1035. static void c_write_untrusted(Ssh ssh, const void *buf, int len)
  1036. {
  1037. if (flags & FLAG_STDERR)
  1038. c_write_stderr(0, buf, len);
  1039. else
  1040. from_backend_untrusted(ssh->frontend, buf, len);
  1041. }
  1042. static void c_write_str(Ssh ssh, const char *buf)
  1043. {
  1044. c_write(ssh, buf, strlen(buf));
  1045. }
  1046. void ssh_unref_packet(PktIn *pkt)
  1047. {
  1048. if (--pkt->refcount <= 0)
  1049. sfree(pkt);
  1050. }
  1051. void ssh_free_pktout(PktOut *pkt)
  1052. {
  1053. sfree(pkt->data);
  1054. sfree(pkt);
  1055. }
  1056. static void ssh_pkt_BinarySink_write(BinarySink *bs,
  1057. const void *data, size_t len);
  1058. PktOut *ssh_new_packet(void)
  1059. {
  1060. PktOut *pkt = snew(PktOut);
  1061. BinarySink_INIT(pkt, ssh_pkt_BinarySink_write);
  1062. pkt->data = NULL;
  1063. pkt->length = 0;
  1064. pkt->maxlen = 0;
  1065. pkt->downstream_id = 0;
  1066. pkt->additional_log_text = NULL;
  1067. return pkt;
  1068. }
  1069. static int s_write(Ssh ssh, const void *data, int len)
  1070. {
  1071. if (len && ssh->logctx)
  1072. log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
  1073. 0, NULL, NULL, 0, NULL);
  1074. if (!ssh->s)
  1075. return 0;
  1076. return sk_write(ssh->s, data, len);
  1077. }
  1078. static void ssh_pkt_write(Ssh ssh, PktOut *pkt)
  1079. {
  1080. if (ssh->version == 2 && ssh->v2_cbc_ignore_workaround &&
  1081. bufchain_size(&ssh->outgoing_data) != 0) {
  1082. /*
  1083. * When using a CBC-mode cipher in SSH-2, it's necessary to
  1084. * ensure that an attacker can't provide data to be encrypted
  1085. * using an IV that they know. We ensure this by prefixing
  1086. * each packet that might contain user data with an
  1087. * SSH_MSG_IGNORE.
  1088. */
  1089. PktOut *ipkt = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_IGNORE);
  1090. put_stringz(ipkt, "");
  1091. ssh_bpp_format_packet(ssh->bpp, ipkt);
  1092. }
  1093. ssh_bpp_format_packet(ssh->bpp, pkt);
  1094. queue_idempotent_callback(&ssh->outgoing_data_sender);
  1095. }
  1096. static int ssh_versioncmp(const char *a, const char *b)
  1097. {
  1098. char *ae, *be;
  1099. unsigned long av, bv;
  1100. av = strtoul(a, &ae, 10);
  1101. bv = strtoul(b, &be, 10);
  1102. if (av != bv)
  1103. return (av < bv ? -1 : +1);
  1104. if (*ae == '.')
  1105. ae++;
  1106. if (*be == '.')
  1107. be++;
  1108. av = strtoul(ae, &ae, 10);
  1109. bv = strtoul(be, &be, 10);
  1110. if (av != bv)
  1111. return (av < bv ? -1 : +1);
  1112. return 0;
  1113. }
  1114. /*
  1115. * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
  1116. */
  1117. static void ssh_pkt_ensure(PktOut *pkt, int length)
  1118. {
  1119. if (pkt->maxlen < length) {
  1120. pkt->maxlen = length + 256;
  1121. pkt->data = sresize(pkt->data, pkt->maxlen, unsigned char);
  1122. }
  1123. }
  1124. static void ssh_pkt_adddata(PktOut *pkt, const void *data, int len)
  1125. {
  1126. pkt->length += len;
  1127. ssh_pkt_ensure(pkt, pkt->length);
  1128. memcpy(pkt->data + pkt->length - len, data, len);
  1129. }
  1130. static void ssh_pkt_BinarySink_write(BinarySink *bs,
  1131. const void *data, size_t len)
  1132. {
  1133. PktOut *pkt = BinarySink_DOWNCAST(bs, PktOut);
  1134. ssh_pkt_adddata(pkt, data, len);
  1135. }
  1136. /*
  1137. * Queue an SSH-2 packet.
  1138. */
  1139. static void ssh2_pkt_queue(Ssh ssh, PktOut *pkt)
  1140. {
  1141. assert(ssh->queueing);
  1142. if (ssh->queuelen >= ssh->queuesize) {
  1143. ssh->queuesize = ssh->queuelen + 32;
  1144. ssh->queue = sresize(ssh->queue, ssh->queuesize, PktOut *);
  1145. }
  1146. ssh->queue[ssh->queuelen++] = pkt;
  1147. }
  1148. /*
  1149. * Either queue or send a packet, depending on whether queueing is
  1150. * set.
  1151. */
  1152. static void ssh2_pkt_send(Ssh ssh, PktOut *pkt)
  1153. {
  1154. if (ssh->queueing) {
  1155. ssh2_pkt_queue(ssh, pkt);
  1156. } else {
  1157. ssh_pkt_write(ssh, pkt);
  1158. }
  1159. }
  1160. static void ssh_send_outgoing_data(void *ctx)
  1161. {
  1162. Ssh ssh = (Ssh)ctx;
  1163. while (bufchain_size(&ssh->outgoing_data) > 0) {
  1164. void *data;
  1165. int len, backlog;
  1166. bufchain_prefix(&ssh->outgoing_data, &data, &len);
  1167. backlog = s_write(ssh, data, len);
  1168. bufchain_consume(&ssh->outgoing_data, len);
  1169. ssh->outgoing_data_size += len;
  1170. if (ssh->version == 2 && !ssh->kex_in_progress &&
  1171. !ssh->bare_connection && ssh->max_data_size != 0 &&
  1172. ssh->outgoing_data_size > ssh->max_data_size) {
  1173. ssh->rekey_reason = "too much data sent";
  1174. ssh->rekey_class = RK_NORMAL;
  1175. queue_idempotent_callback(&ssh->ssh2_transport_icb);
  1176. }
  1177. if (backlog > SSH_MAX_BACKLOG) {
  1178. ssh_throttle_all(ssh, 1, backlog);
  1179. return;
  1180. }
  1181. }
  1182. }
  1183. /*
  1184. * Send all queued SSH-2 packets.
  1185. */
  1186. static void ssh2_pkt_queuesend(Ssh ssh)
  1187. {
  1188. int i;
  1189. assert(!ssh->queueing);
  1190. for (i = 0; i < ssh->queuelen; i++)
  1191. ssh_pkt_write(ssh, ssh->queue[i]);
  1192. ssh->queuelen = 0;
  1193. }
  1194. #if 0
  1195. void bndebug(char *string, Bignum b)
  1196. {
  1197. unsigned char *p;
  1198. int i, len;
  1199. p = ssh2_mpint_fmt(b, &len);
  1200. debug(("%s", string));
  1201. for (i = 0; i < len; i++)
  1202. debug((" %02x", p[i]));
  1203. debug(("\n"));
  1204. sfree(p);
  1205. }
  1206. #endif
  1207. /*
  1208. * Helper function to add an SSH-2 signature blob to a packet. Expects
  1209. * to be shown the public key blob as well as the signature blob.
  1210. * Normally just appends the sig blob unmodified as a string, except
  1211. * that it optionally breaks it open and fiddle with it to work around
  1212. * BUG_SSH2_RSA_PADDING.
  1213. */
  1214. static void ssh2_add_sigblob(Ssh ssh, PktOut *pkt,
  1215. const void *pkblob, int pkblob_len,
  1216. const void *sigblob, int sigblob_len)
  1217. {
  1218. BinarySource pk[1], sig[1];
  1219. BinarySource_BARE_INIT(pk, pkblob, pkblob_len);
  1220. BinarySource_BARE_INIT(sig, sigblob, sigblob_len);
  1221. /* dmemdump(pkblob, pkblob_len); */
  1222. /* dmemdump(sigblob, sigblob_len); */
  1223. /*
  1224. * See if this is in fact an ssh-rsa signature and a buggy
  1225. * server; otherwise we can just do this the easy way.
  1226. */
  1227. if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
  1228. ptrlen_eq_string(get_string(pk), "ssh-rsa") &&
  1229. ptrlen_eq_string(get_string(sig), "ssh-rsa")) {
  1230. ptrlen mod_mp, sig_mp;
  1231. size_t sig_prefix_len;
  1232. /*
  1233. * Find the modulus and signature integers.
  1234. */
  1235. get_string(pk); /* skip over exponent */
  1236. mod_mp = get_string(pk); /* remember modulus */
  1237. sig_prefix_len = sig->pos;
  1238. sig_mp = get_string(sig);
  1239. if (get_err(pk) || get_err(sig))
  1240. goto give_up;
  1241. /*
  1242. * Find the byte length of the modulus, not counting leading
  1243. * zeroes.
  1244. */
  1245. while (mod_mp.len > 0 && *(const char *)mod_mp.ptr == 0) {
  1246. mod_mp.len--;
  1247. mod_mp.ptr = (const char *)mod_mp.ptr + 1;
  1248. }
  1249. /* debug(("modulus length is %d\n", len)); */
  1250. /* debug(("signature length is %d\n", siglen)); */
  1251. if (mod_mp.len != sig_mp.len) {
  1252. strbuf *substr = strbuf_new();
  1253. put_data(substr, sigblob, sig_prefix_len);
  1254. put_uint32(substr, mod_mp.len);
  1255. put_padding(substr, mod_mp.len - sig_mp.len, 0);
  1256. put_data(substr, sig_mp.ptr, sig_mp.len);
  1257. put_stringsb(pkt, substr);
  1258. return;
  1259. }
  1260. /* Otherwise fall through and do it the easy way. We also come
  1261. * here as a fallback if we discover above that the key blob
  1262. * is misformatted in some way. */
  1263. give_up:;
  1264. }
  1265. put_string(pkt, sigblob, sigblob_len);
  1266. }
  1267. /*
  1268. * Examine the remote side's version string and compare it against
  1269. * a list of known buggy implementations.
  1270. */
  1271. static void ssh_detect_bugs(Ssh ssh, char *vstring)
  1272. {
  1273. char *imp; /* pointer to implementation part */
  1274. imp = vstring;
  1275. imp += strcspn(imp, "-");
  1276. if (*imp) imp++;
  1277. imp += strcspn(imp, "-");
  1278. if (*imp) imp++;
  1279. ssh->remote_bugs = 0;
  1280. /*
  1281. * General notes on server version strings:
  1282. * - Not all servers reporting "Cisco-1.25" have all the bugs listed
  1283. * here -- in particular, we've heard of one that's perfectly happy
  1284. * with SSH1_MSG_IGNOREs -- but this string never seems to change,
  1285. * so we can't distinguish them.
  1286. */
  1287. if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
  1288. (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
  1289. (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
  1290. !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
  1291. !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
  1292. !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
  1293. /*
  1294. * These versions don't support SSH1_MSG_IGNORE, so we have
  1295. * to use a different defence against password length
  1296. * sniffing.
  1297. */
  1298. ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
  1299. logevent("We believe remote version has SSH-1 ignore bug");
  1300. }
  1301. if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
  1302. (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
  1303. (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
  1304. /*
  1305. * These versions need a plain password sent; they can't
  1306. * handle having a null and a random length of data after
  1307. * the password.
  1308. */
  1309. ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
  1310. logevent("We believe remote version needs a plain SSH-1 password");
  1311. }
  1312. if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
  1313. (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
  1314. (!strcmp(imp, "Cisco-1.25")))) {
  1315. /*
  1316. * These versions apparently have no clue whatever about
  1317. * RSA authentication and will panic and die if they see
  1318. * an AUTH_RSA message.
  1319. */
  1320. ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
  1321. logevent("We believe remote version can't handle SSH-1 RSA authentication");
  1322. }
  1323. if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
  1324. (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
  1325. !wc_match("* VShell", imp) &&
  1326. (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
  1327. wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
  1328. wc_match("2.1 *", imp)))) {
  1329. /*
  1330. * These versions have the HMAC bug.
  1331. */
  1332. ssh->remote_bugs |= BUG_SSH2_HMAC;
  1333. logevent("We believe remote version has SSH-2 HMAC bug");
  1334. }
  1335. if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
  1336. (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
  1337. !wc_match("* VShell", imp) &&
  1338. (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
  1339. /*
  1340. * These versions have the key-derivation bug (failing to
  1341. * include the literal shared secret in the hashes that
  1342. * generate the keys).
  1343. */
  1344. ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
  1345. logevent("We believe remote version has SSH-2 key-derivation bug");
  1346. }
  1347. if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
  1348. (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
  1349. (wc_match("OpenSSH_2.[5-9]*", imp) ||
  1350. wc_match("OpenSSH_3.[0-2]*", imp) ||
  1351. wc_match("mod_sftp/0.[0-8]*", imp) ||
  1352. wc_match("mod_sftp/0.9.[0-8]", imp)))) {
  1353. /*
  1354. * These versions have the SSH-2 RSA padding bug.
  1355. */
  1356. ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
  1357. logevent("We believe remote version has SSH-2 RSA padding bug");
  1358. }
  1359. if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
  1360. (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
  1361. wc_match("OpenSSH_2.[0-2]*", imp))) {
  1362. /*
  1363. * These versions have the SSH-2 session-ID bug in
  1364. * public-key authentication.
  1365. */
  1366. ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
  1367. logevent("We believe remote version has SSH-2 public-key-session-ID bug");
  1368. }
  1369. if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
  1370. (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
  1371. (wc_match("DigiSSH_2.0", imp) ||
  1372. wc_match("OpenSSH_2.[0-4]*", imp) ||
  1373. wc_match("OpenSSH_2.5.[0-3]*", imp) ||
  1374. wc_match("Sun_SSH_1.0", imp) ||
  1375. wc_match("Sun_SSH_1.0.1", imp) ||
  1376. /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
  1377. wc_match("WeOnlyDo-*", imp)))) {
  1378. /*
  1379. * These versions have the SSH-2 rekey bug.
  1380. */
  1381. ssh->remote_bugs |= BUG_SSH2_REKEY;
  1382. logevent("We believe remote version has SSH-2 rekey bug");
  1383. }
  1384. if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
  1385. (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
  1386. (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
  1387. wc_match("1.36 sshlib: GlobalScape", imp)))) {
  1388. /*
  1389. * This version ignores our makpkt and needs to be throttled.
  1390. */
  1391. ssh->remote_bugs |= BUG_SSH2_MAXPKT;
  1392. logevent("We believe remote version ignores SSH-2 maximum packet size");
  1393. }
  1394. if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
  1395. /*
  1396. * Servers that don't support SSH2_MSG_IGNORE. Currently,
  1397. * none detected automatically.
  1398. */
  1399. ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
  1400. logevent("We believe remote version has SSH-2 ignore bug");
  1401. }
  1402. if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
  1403. (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
  1404. (wc_match("OpenSSH_2.[235]*", imp)))) {
  1405. /*
  1406. * These versions only support the original (pre-RFC4419)
  1407. * SSH-2 GEX request, and disconnect with a protocol error if
  1408. * we use the newer version.
  1409. */
  1410. ssh->remote_bugs |= BUG_SSH2_OLDGEX;
  1411. logevent("We believe remote version has outdated SSH-2 GEX");
  1412. }
  1413. if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
  1414. /*
  1415. * Servers that don't support our winadj request for one
  1416. * reason or another. Currently, none detected automatically.
  1417. */
  1418. ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
  1419. logevent("We believe remote version has winadj bug");
  1420. }
  1421. if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
  1422. (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
  1423. (wc_match("OpenSSH_[2-5].*", imp) ||
  1424. wc_match("OpenSSH_6.[0-6]*", imp) ||
  1425. wc_match("dropbear_0.[2-4][0-9]*", imp) ||
  1426. wc_match("dropbear_0.5[01]*", imp)))) {
  1427. /*
  1428. * These versions have the SSH-2 channel request bug.
  1429. * OpenSSH 6.7 and above do not:
  1430. * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
  1431. * dropbear_0.52 and above do not:
  1432. * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
  1433. */
  1434. ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
  1435. logevent("We believe remote version has SSH-2 channel request bug");
  1436. }
  1437. }
  1438. /*
  1439. * The `software version' part of an SSH version string is required
  1440. * to contain no spaces or minus signs.
  1441. */
  1442. static void ssh_fix_verstring(char *str)
  1443. {
  1444. /* Eat "<protoversion>-". */
  1445. while (*str && *str != '-') str++;
  1446. assert(*str == '-'); str++;
  1447. /* Convert minus signs and spaces in the remaining string into
  1448. * underscores. */
  1449. while (*str) {
  1450. if (*str == '-' || *str == ' ')
  1451. *str = '_';
  1452. str++;
  1453. }
  1454. }
  1455. /*
  1456. * Send an appropriate SSH version string.
  1457. */
  1458. static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
  1459. {
  1460. char *verstring;
  1461. if (ssh->version == 2) {
  1462. /*
  1463. * Construct a v2 version string.
  1464. */
  1465. verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
  1466. } else {
  1467. /*
  1468. * Construct a v1 version string.
  1469. */
  1470. assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
  1471. verstring = dupprintf("SSH-%s-%s\012",
  1472. (ssh_versioncmp(svers, "1.5") <= 0 ?
  1473. svers : "1.5"),
  1474. sshver);
  1475. }
  1476. ssh_fix_verstring(verstring + strlen(protoname));
  1477. #ifdef FUZZING
  1478. /* FUZZING make PuTTY insecure, so make live use difficult. */
  1479. verstring[0] = 'I';
  1480. #endif
  1481. if (ssh->version == 2) {
  1482. size_t len;
  1483. /*
  1484. * Record our version string.
  1485. */
  1486. len = strcspn(verstring, "\015\012");
  1487. ssh->v_c = snewn(len + 1, char);
  1488. memcpy(ssh->v_c, verstring, len);
  1489. ssh->v_c[len] = 0;
  1490. }
  1491. logeventf(ssh, "We claim version: %.*s",
  1492. strcspn(verstring, "\015\012"), verstring);
  1493. bufchain_add(&ssh->outgoing_data, verstring, strlen(verstring));
  1494. queue_idempotent_callback(&ssh->outgoing_data_sender);
  1495. sfree(verstring);
  1496. }
  1497. static void ssh_feed_to_bpp(Ssh ssh)
  1498. {
  1499. PacketQueueNode *prev_tail = ssh->pq_full.end.prev;
  1500. assert(ssh->bpp);
  1501. ssh_bpp_handle_input(ssh->bpp);
  1502. if (ssh->bpp->error) {
  1503. bomb_out(ssh, ssh->bpp->error); /* also frees the error string */
  1504. return;
  1505. }
  1506. if (ssh->bpp->seen_disconnect) {
  1507. /*
  1508. * If we've seen a DISCONNECT message, we should unset the
  1509. * close_expected flag, because now we _do_ expect the server
  1510. * to close the network connection afterwards. That way, the
  1511. * more informative connection_fatal message for the
  1512. * disconnect itself won't fight with 'Server unexpectedly
  1513. * closed network connection'.
  1514. */
  1515. ssh->clean_exit = FALSE;
  1516. ssh->close_expected = TRUE;
  1517. ssh->disconnect_message_seen = TRUE;
  1518. }
  1519. if (ssh->pq_full.end.prev != prev_tail)
  1520. queue_idempotent_callback(&ssh->pq_full_consumer);
  1521. }
  1522. static void do_ssh_init(Ssh ssh)
  1523. {
  1524. static const char protoname[] = "SSH-";
  1525. struct do_ssh_init_state {
  1526. int crLine;
  1527. int vslen;
  1528. char *vstring;
  1529. char *version;
  1530. int vstrsize;
  1531. int i;
  1532. int proto1, proto2;
  1533. };
  1534. crState(do_ssh_init_state);
  1535. crBeginState;
  1536. /*
  1537. * Search for a line beginning with the protocol name prefix in
  1538. * the input.
  1539. */
  1540. s->i = 0;
  1541. while (1) {
  1542. char prefix[sizeof(protoname)-1];
  1543. /*
  1544. * Every time round this loop, we're at the start of a new
  1545. * line, so look for the prefix.
  1546. */
  1547. crMaybeWaitUntilV(
  1548. bufchain_size(&ssh->incoming_data) >= sizeof(prefix));
  1549. bufchain_fetch(&ssh->incoming_data, prefix, sizeof(prefix));
  1550. if (!memcmp(prefix, protoname, sizeof(prefix))) {
  1551. bufchain_consume(&ssh->incoming_data, sizeof(prefix));
  1552. break;
  1553. }
  1554. /*
  1555. * If we didn't find it, consume data until we see a newline.
  1556. */
  1557. while (1) {
  1558. int len;
  1559. void *data;
  1560. char *nl;
  1561. crMaybeWaitUntilV(bufchain_size(&ssh->incoming_data) > 0);
  1562. bufchain_prefix(&ssh->incoming_data, &data, &len);
  1563. if ((nl = memchr(data, '\012', len)) != NULL) {
  1564. bufchain_consume(&ssh->incoming_data, nl - (char *)data + 1);
  1565. break;
  1566. } else {
  1567. bufchain_consume(&ssh->incoming_data, len);
  1568. }
  1569. }
  1570. }
  1571. ssh->session_started = TRUE;
  1572. ssh->agentfwd_enabled = FALSE;
  1573. /*
  1574. * Now read the rest of the greeting line.
  1575. */
  1576. s->vstrsize = sizeof(protoname) + 16;
  1577. s->vstring = snewn(s->vstrsize, char);
  1578. strcpy(s->vstring, protoname);
  1579. s->vslen = strlen(protoname);
  1580. s->i = 0;
  1581. do {
  1582. int len;
  1583. void *data;
  1584. char *nl;
  1585. crMaybeWaitUntilV(bufchain_size(&ssh->incoming_data) > 0);
  1586. bufchain_prefix(&ssh->incoming_data, &data, &len);
  1587. if ((nl = memchr(data, '\012', len)) != NULL) {
  1588. len = nl - (char *)data + 1;
  1589. }
  1590. if (s->vslen + len >= s->vstrsize - 1) {
  1591. s->vstrsize = (s->vslen + len) * 5 / 4 + 32;
  1592. s->vstring = sresize(s->vstring, s->vstrsize, char);
  1593. }
  1594. memcpy(s->vstring + s->vslen, data, len);
  1595. s->vslen += len;
  1596. bufchain_consume(&ssh->incoming_data, len);
  1597. } while (s->vstring[s->vslen-1] != '\012');
  1598. s->vstring[s->vslen] = 0;
  1599. s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
  1600. logeventf(ssh, "Server version: %s", s->vstring);
  1601. ssh_detect_bugs(ssh, s->vstring);
  1602. /*
  1603. * Decide which SSH protocol version to support.
  1604. */
  1605. s->version = dupprintf(
  1606. "%.*s", (int)strcspn(s->vstring + strlen(protoname), "-"),
  1607. s->vstring + strlen(protoname));
  1608. /* Anything strictly below "2.0" means protocol 1 is supported. */
  1609. s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
  1610. /* Anything greater or equal to "1.99" means protocol 2 is supported. */
  1611. s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
  1612. if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
  1613. if (!s->proto1) {
  1614. bombout(("SSH protocol version 1 required by our configuration "
  1615. "but not provided by server"));
  1616. crStopV;
  1617. }
  1618. } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
  1619. if (!s->proto2) {
  1620. bombout(("SSH protocol version 2 required by our configuration "
  1621. "but server only provides (old, insecure) SSH-1"));
  1622. crStopV;
  1623. }
  1624. } else {
  1625. /* No longer support values 1 or 2 for CONF_sshprot */
  1626. assert(!"Unexpected value for CONF_sshprot");
  1627. }
  1628. if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
  1629. ssh->version = 2;
  1630. else
  1631. ssh->version = 1;
  1632. logeventf(ssh, "Using SSH protocol version %d", ssh->version);
  1633. /* Send the version string, if we haven't already */
  1634. if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
  1635. ssh_send_verstring(ssh, protoname, s->version);
  1636. sfree(s->version);
  1637. if (ssh->version == 2) {
  1638. size_t len;
  1639. /*
  1640. * Record their version string.
  1641. */
  1642. len = strcspn(s->vstring, "\015\012");
  1643. ssh->v_s = snewn(len + 1, char);
  1644. memcpy(ssh->v_s, s->vstring, len);
  1645. ssh->v_s[len] = 0;
  1646. /*
  1647. * Initialise SSH-2 protocol.
  1648. */
  1649. ssh2_protocol_setup(ssh);
  1650. ssh->general_packet_processing = ssh2_general_packet_processing;
  1651. ssh->current_user_input_fn = NULL;
  1652. } else {
  1653. /*
  1654. * Initialise SSH-1 protocol.
  1655. */
  1656. ssh1_protocol_setup(ssh);
  1657. ssh->current_user_input_fn = ssh1_login_input;
  1658. }
  1659. ssh->bpp->out_raw = &ssh->outgoing_data;
  1660. ssh->bpp->in_raw = &ssh->incoming_data;
  1661. ssh->bpp->in_pq = &ssh->pq_full;
  1662. ssh->bpp->pls = &ssh->pls;
  1663. ssh->bpp->logctx = ssh->logctx;
  1664. ssh->current_incoming_data_fn = ssh_feed_to_bpp;
  1665. queue_idempotent_callback(&ssh->incoming_data_consumer);
  1666. queue_idempotent_callback(&ssh->user_input_consumer);
  1667. if (ssh->version == 2)
  1668. queue_idempotent_callback(&ssh->ssh2_transport_icb);
  1669. update_specials_menu(ssh->frontend);
  1670. ssh->state = SSH_STATE_BEFORE_SIZE;
  1671. ssh->pinger = pinger_new(ssh->conf, &ssh->backend);
  1672. sfree(s->vstring);
  1673. crFinishV;
  1674. }
  1675. static void do_ssh_connection_init(Ssh ssh)
  1676. {
  1677. /*
  1678. * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
  1679. * the ssh-connection part, extracted and given a trivial binary
  1680. * packet protocol, so we replace 'SSH-' at the start with a new
  1681. * name. In proper SSH style (though of course this part of the
  1682. * proper SSH protocol _isn't_ subject to this kind of
  1683. * DNS-domain-based extension), we define the new name in our
  1684. * extension space.
  1685. */
  1686. static const char protoname[] =
  1687. "[email protected]";
  1688. struct do_ssh_connection_init_state {
  1689. int crLine;
  1690. int vslen;
  1691. char *vstring;
  1692. char *version;
  1693. int vstrsize;
  1694. int i;
  1695. };
  1696. crState(do_ssh_connection_init_state);
  1697. crBeginState;
  1698. /*
  1699. * Search for a line beginning with the protocol name prefix in
  1700. * the input.
  1701. */
  1702. s->i = 0;
  1703. while (1) {
  1704. char prefix[sizeof(protoname)-1];
  1705. /*
  1706. * Every time round this loop, we're at the start of a new
  1707. * line, so look for the prefix.
  1708. */
  1709. crMaybeWaitUntilV(
  1710. bufchain_size(&ssh->incoming_data) >= sizeof(prefix));
  1711. bufchain_fetch(&ssh->incoming_data, prefix, sizeof(prefix));
  1712. if (!memcmp(prefix, protoname, sizeof(prefix))) {
  1713. bufchain_consume(&ssh->incoming_data, sizeof(prefix));
  1714. break;
  1715. }
  1716. /*
  1717. * If we didn't find it, consume data until we see a newline.
  1718. */
  1719. while (1) {
  1720. int len;
  1721. void *data;
  1722. char *nl;
  1723. crMaybeWaitUntilV(bufchain_size(&ssh->incoming_data) > 0);
  1724. bufchain_prefix(&ssh->incoming_data, &data, &len);
  1725. if ((nl = memchr(data, '\012', len)) != NULL) {
  1726. bufchain_consume(&ssh->incoming_data, nl - (char *)data + 1);
  1727. break;
  1728. } else {
  1729. bufchain_consume(&ssh->incoming_data, len);
  1730. }
  1731. }
  1732. }
  1733. /*
  1734. * Now read the rest of the greeting line.
  1735. */
  1736. s->vstrsize = sizeof(protoname) + 16;
  1737. s->vstring = snewn(s->vstrsize, char);
  1738. strcpy(s->vstring, protoname);
  1739. s->vslen = strlen(protoname);
  1740. s->i = 0;
  1741. do {
  1742. int len;
  1743. void *data;
  1744. char *nl;
  1745. crMaybeWaitUntilV(bufchain_size(&ssh->incoming_data) > 0);
  1746. bufchain_prefix(&ssh->incoming_data, &data, &len);
  1747. if ((nl = memchr(data, '\012', len)) != NULL) {
  1748. len = nl - (char *)data + 1;
  1749. }
  1750. if (s->vslen + len >= s->vstrsize - 1) {
  1751. s->vstrsize = (s->vslen + len) * 5 / 4 + 32;
  1752. s->vstring = sresize(s->vstring, s->vstrsize, char);
  1753. }
  1754. memcpy(s->vstring + s->vslen, data, len);
  1755. s->vslen += len;
  1756. bufchain_consume(&ssh->incoming_data, len);
  1757. } while (s->vstring[s->vslen-1] != '\012');
  1758. s->vstring[s->vslen] = 0;
  1759. s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
  1760. ssh->agentfwd_enabled = FALSE;
  1761. logeventf(ssh, "Server version: %s", s->vstring);
  1762. ssh_detect_bugs(ssh, s->vstring);
  1763. /*
  1764. * Decide which SSH protocol version to support. This is easy in
  1765. * bare ssh-connection mode: only 2.0 is legal.
  1766. */
  1767. s->version = dupprintf(
  1768. "%.*s", (int)strcspn(s->vstring + strlen(protoname), "-"),
  1769. s->vstring + strlen(protoname));
  1770. if (ssh_versioncmp(s->version, "2.0") < 0) {
  1771. bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
  1772. crStopV;
  1773. }
  1774. if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
  1775. bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
  1776. crStopV;
  1777. }
  1778. ssh->version = 2;
  1779. logeventf(ssh, "Using bare ssh-connection protocol");
  1780. /* Send the version string, if we haven't already */
  1781. ssh_send_verstring(ssh, protoname, s->version);
  1782. sfree(s->version);
  1783. /*
  1784. * Initialise bare connection protocol.
  1785. */
  1786. ssh2_bare_connection_protocol_setup(ssh);
  1787. ssh->bpp->out_raw = &ssh->outgoing_data;
  1788. ssh->bpp->in_raw = &ssh->incoming_data;
  1789. ssh->bpp->in_pq = &ssh->pq_full;
  1790. ssh->bpp->pls = &ssh->pls;
  1791. ssh->bpp->logctx = ssh->logctx;
  1792. ssh->current_incoming_data_fn = ssh_feed_to_bpp;
  1793. queue_idempotent_callback(&ssh->incoming_data_consumer);
  1794. ssh->current_user_input_fn = ssh2_connection_input;
  1795. queue_idempotent_callback(&ssh->user_input_consumer);
  1796. update_specials_menu(ssh->frontend);
  1797. ssh->state = SSH_STATE_BEFORE_SIZE;
  1798. ssh->pinger = pinger_new(ssh->conf, &ssh->backend);
  1799. /*
  1800. * Get connection protocol under way.
  1801. */
  1802. do_ssh2_connection(ssh);
  1803. sfree(s->vstring);
  1804. crFinishV;
  1805. }
  1806. static void ssh_set_frozen(Ssh ssh, int frozen)
  1807. {
  1808. if (ssh->s)
  1809. sk_set_frozen(ssh->s, frozen);
  1810. ssh->frozen = frozen;
  1811. }
  1812. static void ssh_process_incoming_data(void *ctx)
  1813. {
  1814. Ssh ssh = (Ssh)ctx;
  1815. if (ssh->state == SSH_STATE_CLOSED)
  1816. return;
  1817. if (!ssh->frozen)
  1818. ssh->current_incoming_data_fn(ssh);
  1819. if (ssh->state == SSH_STATE_CLOSED) /* yes, check _again_ */
  1820. return;
  1821. if (ssh->incoming_data_seen_eof) {
  1822. int need_notify = ssh_do_close(ssh, FALSE);
  1823. const char *error_msg = ssh->incoming_data_eof_message;
  1824. if (!error_msg) {
  1825. if (!ssh->close_expected)
  1826. error_msg = "Server unexpectedly closed network connection";
  1827. else
  1828. error_msg = "Server closed network connection";
  1829. }
  1830. if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
  1831. ssh->exitcode = 0;
  1832. if (need_notify)
  1833. notify_remote_exit(ssh->frontend);
  1834. if (error_msg)
  1835. logevent(error_msg);
  1836. if ((!ssh->close_expected || !ssh->clean_exit) &&
  1837. !ssh->disconnect_message_seen)
  1838. connection_fatal(ssh->frontend, "%s", error_msg);
  1839. }
  1840. }
  1841. static void ssh_process_pq_full(void *ctx)
  1842. {
  1843. Ssh ssh = (Ssh)ctx;
  1844. PktIn *pktin;
  1845. while ((pktin = pq_pop(&ssh->pq_full)) != NULL) {
  1846. if (ssh->general_packet_processing)
  1847. ssh->general_packet_processing(ssh, pktin);
  1848. ssh->packet_dispatch[pktin->type](ssh, pktin);
  1849. ssh_unref_packet(pktin);
  1850. }
  1851. }
  1852. static void ssh_process_user_input(void *ctx)
  1853. {
  1854. Ssh ssh = (Ssh)ctx;
  1855. if (ssh->current_user_input_fn)
  1856. ssh->current_user_input_fn(ssh);
  1857. }
  1858. void chan_remotely_opened_confirmation(Channel *chan)
  1859. {
  1860. assert(0 && "this channel type should never receive OPEN_CONFIRMATION");
  1861. }
  1862. void chan_remotely_opened_failure(Channel *chan, const char *errtext)
  1863. {
  1864. assert(0 && "this channel type should never receive OPEN_FAILURE");
  1865. }
  1866. int chan_no_eager_close(Channel *chan, int sent_local_eof, int rcvd_remote_eof)
  1867. {
  1868. return FALSE; /* default: never proactively ask for a close */
  1869. }
  1870. /*
  1871. * Trivial channel vtable for handling 'zombie channels' - those whose
  1872. * local source of data has already been shut down or otherwise
  1873. * stopped existing - so that we don't have to give them a null
  1874. * 'Channel *' and special-case that all over the place.
  1875. */
  1876. static void zombiechan_free(Channel *chan);
  1877. static int zombiechan_send(Channel *chan, int is_stderr, const void *, int);
  1878. static void zombiechan_set_input_wanted(Channel *chan, int wanted);
  1879. static void zombiechan_do_nothing(Channel *chan);
  1880. static void zombiechan_open_failure(Channel *chan, const char *);
  1881. static int zombiechan_want_close(Channel *chan, int sent_eof, int rcvd_eof);
  1882. static char *zombiechan_log_close_msg(Channel *chan) { return NULL; }
  1883. static const struct ChannelVtable zombiechan_channelvt = {
  1884. zombiechan_free,
  1885. zombiechan_do_nothing, /* open_confirmation */
  1886. zombiechan_open_failure,
  1887. zombiechan_send,
  1888. zombiechan_do_nothing, /* send_eof */
  1889. zombiechan_set_input_wanted,
  1890. zombiechan_log_close_msg,
  1891. zombiechan_want_close,
  1892. };
  1893. Channel *zombiechan_new(void)
  1894. {
  1895. Channel *chan = snew(Channel);
  1896. chan->vt = &zombiechan_channelvt;
  1897. chan->initial_fixed_window_size = 0;
  1898. return chan;
  1899. }
  1900. static void zombiechan_free(Channel *chan)
  1901. {
  1902. assert(chan->vt == &zombiechan_channelvt);
  1903. sfree(chan);
  1904. }
  1905. static void zombiechan_do_nothing(Channel *chan)
  1906. {
  1907. assert(chan->vt == &zombiechan_channelvt);
  1908. }
  1909. static void zombiechan_open_failure(Channel *chan, const char *errtext)
  1910. {
  1911. assert(chan->vt == &zombiechan_channelvt);
  1912. }
  1913. static int zombiechan_send(Channel *chan, int is_stderr,
  1914. const void *data, int length)
  1915. {
  1916. assert(chan->vt == &zombiechan_channelvt);
  1917. return 0;
  1918. }
  1919. static void zombiechan_set_input_wanted(Channel *chan, int enable)
  1920. {
  1921. assert(chan->vt == &zombiechan_channelvt);
  1922. }
  1923. static int zombiechan_want_close(Channel *chan, int sent_eof, int rcvd_eof)
  1924. {
  1925. return TRUE;
  1926. }
  1927. static int ssh_do_close(Ssh ssh, int notify_exit)
  1928. {
  1929. int ret = 0;
  1930. struct ssh_channel *c;
  1931. ssh->state = SSH_STATE_CLOSED;
  1932. expire_timer_context(ssh);
  1933. if (ssh->s) {
  1934. sk_close(ssh->s);
  1935. ssh->s = NULL;
  1936. if (notify_exit)
  1937. notify_remote_exit(ssh->frontend);
  1938. else
  1939. ret = 1;
  1940. }
  1941. /*
  1942. * Now we must shut down any port- and X-forwarded channels going
  1943. * through this connection.
  1944. */
  1945. if (ssh->channels) {
  1946. while (NULL != (c = index234(ssh->channels, 0))) {
  1947. ssh_channel_close_local(c, NULL);
  1948. del234(ssh->channels, c); /* moving next one to index 0 */
  1949. if (ssh->version == 2)
  1950. bufchain_clear(&c->v.v2.outbuffer);
  1951. sfree(c);
  1952. }
  1953. }
  1954. /*
  1955. * Go through port-forwardings, and close any associated
  1956. * listening sockets.
  1957. */
  1958. if (ssh->portfwds) {
  1959. struct ssh_portfwd *pf;
  1960. while (NULL != (pf = index234(ssh->portfwds, 0))) {
  1961. /* Dispose of any listening socket. */
  1962. if (pf->local)
  1963. pfl_terminate(pf->local);
  1964. del234(ssh->portfwds, pf); /* moving next one to index 0 */
  1965. free_portfwd(pf);
  1966. }
  1967. freetree234(ssh->portfwds);
  1968. ssh->portfwds = NULL;
  1969. }
  1970. /*
  1971. * Also stop attempting to connection-share.
  1972. */
  1973. if (ssh->connshare) {
  1974. sharestate_free(ssh->connshare);
  1975. ssh->connshare = NULL;
  1976. }
  1977. return ret;
  1978. }
  1979. static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
  1980. const char *error_msg, int error_code)
  1981. {
  1982. Ssh ssh = FROMFIELD(plug, struct ssh_tag, plugvt);
  1983. /*
  1984. * While we're attempting connection sharing, don't loudly log
  1985. * everything that happens. Real TCP connections need to be logged
  1986. * when we _start_ trying to connect, because it might be ages
  1987. * before they respond if something goes wrong; but connection
  1988. * sharing is local and quick to respond, and it's sufficient to
  1989. * simply wait and see whether it worked afterwards.
  1990. */
  1991. if (!ssh->attempting_connshare)
  1992. backend_socket_log(ssh->frontend, type, addr, port,
  1993. error_msg, error_code, ssh->conf,
  1994. ssh->session_started);
  1995. }
  1996. void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
  1997. const char *ds_err, const char *us_err)
  1998. {
  1999. if (event == SHARE_NONE) {
  2000. /* In this case, 'logtext' is an error message indicating a
  2001. * reason why connection sharing couldn't be set up _at all_.
  2002. * Failing that, ds_err and us_err indicate why we couldn't be
  2003. * a downstream and an upstream respectively. */
  2004. if (logtext) {
  2005. logeventf(ssh, "Could not set up connection sharing: %s", logtext);
  2006. } else {
  2007. if (ds_err)
  2008. logeventf(ssh, "Could not set up connection sharing"
  2009. " as downstream: %s", ds_err);
  2010. if (us_err)
  2011. logeventf(ssh, "Could not set up connection sharing"
  2012. " as upstream: %s", us_err);
  2013. }
  2014. } else if (event == SHARE_DOWNSTREAM) {
  2015. /* In this case, 'logtext' is a local endpoint address */
  2016. logeventf(ssh, "Using existing shared connection at %s", logtext);
  2017. /* Also we should mention this in the console window to avoid
  2018. * confusing users as to why this window doesn't behave the
  2019. * usual way. */
  2020. if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
  2021. c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
  2022. }
  2023. } else if (event == SHARE_UPSTREAM) {
  2024. /* In this case, 'logtext' is a local endpoint address too */
  2025. logeventf(ssh, "Sharing this connection at %s", logtext);
  2026. }
  2027. }
  2028. static void ssh_closing(Plug plug, const char *error_msg, int error_code,
  2029. int calling_back)
  2030. {
  2031. Ssh ssh = FROMFIELD(plug, struct ssh_tag, plugvt);
  2032. ssh->incoming_data_seen_eof = TRUE;
  2033. ssh->incoming_data_eof_message = dupstr(error_msg);
  2034. queue_idempotent_callback(&ssh->incoming_data_consumer);
  2035. }
  2036. static void ssh_receive(Plug plug, int urgent, char *data, int len)
  2037. {
  2038. Ssh ssh = FROMFIELD(plug, struct ssh_tag, plugvt);
  2039. /* Log raw data, if we're in that mode. */
  2040. if (ssh->logctx)
  2041. log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, len,
  2042. 0, NULL, NULL, 0, NULL);
  2043. bufchain_add(&ssh->incoming_data, data, len);
  2044. queue_idempotent_callback(&ssh->incoming_data_consumer);
  2045. if (ssh->state == SSH_STATE_CLOSED) {
  2046. ssh_do_close(ssh, TRUE);
  2047. }
  2048. }
  2049. static void ssh_sent(Plug plug, int bufsize)
  2050. {
  2051. Ssh ssh = FROMFIELD(plug, struct ssh_tag, plugvt);
  2052. /*
  2053. * If the send backlog on the SSH socket itself clears, we should
  2054. * unthrottle the whole world if it was throttled, and also resume
  2055. * sending our bufchain of queued wire data.
  2056. */
  2057. if (bufsize < SSH_MAX_BACKLOG) {
  2058. ssh_throttle_all(ssh, 0, bufsize);
  2059. queue_idempotent_callback(&ssh->outgoing_data_sender);
  2060. }
  2061. }
  2062. static void ssh_hostport_setup(const char *host, int port, Conf *conf,
  2063. char **savedhost, int *savedport,
  2064. char **loghost_ret)
  2065. {
  2066. char *loghost = conf_get_str(conf, CONF_loghost);
  2067. if (loghost_ret)
  2068. *loghost_ret = loghost;
  2069. if (*loghost) {
  2070. char *tmphost;
  2071. char *colon;
  2072. tmphost = dupstr(loghost);
  2073. *savedport = 22; /* default ssh port */
  2074. /*
  2075. * A colon suffix on the hostname string also lets us affect
  2076. * savedport. (Unless there are multiple colons, in which case
  2077. * we assume this is an unbracketed IPv6 literal.)
  2078. */
  2079. colon = host_strrchr(tmphost, ':');
  2080. if (colon && colon == host_strchr(tmphost, ':')) {
  2081. *colon++ = '\0';
  2082. if (*colon)
  2083. *savedport = atoi(colon);
  2084. }
  2085. *savedhost = host_strduptrim(tmphost);
  2086. sfree(tmphost);
  2087. } else {
  2088. *savedhost = host_strduptrim(host);
  2089. if (port < 0)
  2090. port = 22; /* default ssh port */
  2091. *savedport = port;
  2092. }
  2093. }
  2094. static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
  2095. {
  2096. char *savedhost;
  2097. int savedport;
  2098. int ret;
  2099. random_ref(); /* platform may need this to determine share socket name */
  2100. ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
  2101. ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
  2102. sfree(savedhost);
  2103. random_unref();
  2104. return ret;
  2105. }
  2106. static const Plug_vtable Ssh_plugvt = {
  2107. ssh_socket_log,
  2108. ssh_closing,
  2109. ssh_receive,
  2110. ssh_sent,
  2111. NULL
  2112. };
  2113. /*
  2114. * Connect to specified host and port.
  2115. * Returns an error message, or NULL on success.
  2116. * Also places the canonical host name into `realhost'. It must be
  2117. * freed by the caller.
  2118. */
  2119. static const char *connect_to_host(Ssh ssh, const char *host, int port,
  2120. char **realhost, int nodelay, int keepalive)
  2121. {
  2122. SockAddr addr;
  2123. const char *err;
  2124. char *loghost;
  2125. int addressfamily, sshprot;
  2126. ssh_hostport_setup(host, port, ssh->conf,
  2127. &ssh->savedhost, &ssh->savedport, &loghost);
  2128. ssh->plugvt = &Ssh_plugvt;
  2129. #ifdef MPEXT
  2130. // make sure the field is initialized, in case lookup below fails
  2131. ssh->fullhostname = NULL;
  2132. #endif
  2133. /*
  2134. * Try connection-sharing, in case that means we don't open a
  2135. * socket after all. ssh_connection_sharing_init will connect to a
  2136. * previously established upstream if it can, and failing that,
  2137. * establish a listening socket for _us_ to be the upstream. In
  2138. * the latter case it will return NULL just as if it had done
  2139. * nothing, because here we only need to care if we're a
  2140. * downstream and need to do our connection setup differently.
  2141. */
  2142. ssh->connshare = NULL;
  2143. ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
  2144. ssh->s = ssh_connection_sharing_init(
  2145. ssh->savedhost, ssh->savedport, ssh->conf, ssh, &ssh->plugvt,
  2146. &ssh->connshare);
  2147. ssh->attempting_connshare = FALSE;
  2148. if (ssh->s != NULL) {
  2149. /*
  2150. * We are a downstream.
  2151. */
  2152. ssh->bare_connection = TRUE;
  2153. ssh->current_incoming_data_fn = do_ssh_connection_init;
  2154. ssh->fullhostname = NULL;
  2155. *realhost = dupstr(host); /* best we can do */
  2156. } else {
  2157. /*
  2158. * We're not a downstream, so open a normal socket.
  2159. */
  2160. ssh->current_incoming_data_fn = do_ssh_init;
  2161. /*
  2162. * Try to find host.
  2163. */
  2164. addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
  2165. addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
  2166. ssh->frontend, "SSH connection");
  2167. if ((err = sk_addr_error(addr)) != NULL) {
  2168. sk_addr_free(addr);
  2169. return err;
  2170. }
  2171. ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
  2172. ssh->s = new_connection(addr, *realhost, port,
  2173. 0, 1, nodelay, keepalive,
  2174. &ssh->plugvt, ssh->conf);
  2175. if ((err = sk_socket_error(ssh->s)) != NULL) {
  2176. ssh->s = NULL;
  2177. notify_remote_exit(ssh->frontend);
  2178. return err;
  2179. }
  2180. }
  2181. /*
  2182. * The SSH version number is always fixed (since we no longer support
  2183. * fallback between versions), so set it now, and if it's SSH-2,
  2184. * send the version string now too.
  2185. */
  2186. sshprot = conf_get_int(ssh->conf, CONF_sshprot);
  2187. assert(sshprot == 0 || sshprot == 3);
  2188. if (sshprot == 0)
  2189. /* SSH-1 only */
  2190. ssh->version = 1;
  2191. if (sshprot == 3 && !ssh->bare_connection) {
  2192. /* SSH-2 only */
  2193. ssh->version = 2;
  2194. ssh_send_verstring(ssh, "SSH-", NULL);
  2195. }
  2196. /*
  2197. * loghost, if configured, overrides realhost.
  2198. */
  2199. if (*loghost) {
  2200. sfree(*realhost);
  2201. *realhost = dupstr(loghost);
  2202. }
  2203. return NULL;
  2204. }
  2205. /*
  2206. * Throttle or unthrottle the SSH connection.
  2207. */
  2208. static void ssh_throttle_conn(Ssh ssh, int adjust)
  2209. {
  2210. int old_count = ssh->conn_throttle_count;
  2211. ssh->conn_throttle_count += adjust;
  2212. assert(ssh->conn_throttle_count >= 0);
  2213. if (ssh->conn_throttle_count && !old_count) {
  2214. ssh_set_frozen(ssh, 1);
  2215. } else if (!ssh->conn_throttle_count && old_count) {
  2216. ssh_set_frozen(ssh, 0);
  2217. }
  2218. }
  2219. static void ssh_channel_check_throttle(struct ssh_channel *c)
  2220. {
  2221. /*
  2222. * We don't want this channel to read further input if this
  2223. * particular channel has a backed-up SSH window, or if the
  2224. * outgoing side of the whole SSH connection is currently
  2225. * throttled, or if this channel already has an outgoing EOF
  2226. * either sent or pending.
  2227. */
  2228. chan_set_input_wanted(c->chan,
  2229. !c->throttled_by_backlog &&
  2230. !c->ssh->throttled_all &&
  2231. !c->pending_eof &&
  2232. !(c->closes & CLOSES_SENT_EOF));
  2233. }
  2234. /*
  2235. * Throttle or unthrottle _all_ local data streams (for when sends
  2236. * on the SSH connection itself back up).
  2237. */
  2238. static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
  2239. {
  2240. int i;
  2241. struct ssh_channel *c;
  2242. if (enable == ssh->throttled_all)
  2243. return;
  2244. ssh->throttled_all = enable;
  2245. ssh->overall_bufsize = bufsize;
  2246. if (!ssh->channels)
  2247. return;
  2248. for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
  2249. ssh_channel_check_throttle(c);
  2250. }
  2251. static void ssh_agent_callback(void *sshv, void *reply, int replylen)
  2252. {
  2253. Ssh ssh = (Ssh) sshv;
  2254. ssh->auth_agent_query = NULL;
  2255. ssh->agent_response = reply;
  2256. ssh->agent_response_len = replylen;
  2257. if (ssh->version == 1)
  2258. do_ssh1_login(ssh);
  2259. else
  2260. do_ssh2_userauth(ssh);
  2261. }
  2262. static void ssh_dialog_callback(void *sshv, int ret)
  2263. {
  2264. Ssh ssh = (Ssh) sshv;
  2265. ssh->user_response = ret;
  2266. if (ssh->version == 1)
  2267. do_ssh1_login(ssh);
  2268. else
  2269. queue_idempotent_callback(&ssh->ssh2_transport_icb);
  2270. /*
  2271. * This may have unfrozen the SSH connection.
  2272. */
  2273. if (!ssh->frozen)
  2274. queue_idempotent_callback(&ssh->incoming_data_consumer);
  2275. }
  2276. /*
  2277. * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
  2278. * non-NULL, otherwise just close the connection. `client_reason' == NULL
  2279. * => log `wire_reason'.
  2280. */
  2281. static void ssh_disconnect(Ssh ssh, const char *client_reason,
  2282. const char *wire_reason,
  2283. int code, int clean_exit)
  2284. {
  2285. char *error;
  2286. if (!client_reason)
  2287. client_reason = wire_reason;
  2288. if (client_reason)
  2289. error = dupprintf("Disconnected: %s", client_reason);
  2290. else
  2291. error = dupstr("Disconnected");
  2292. if (wire_reason) {
  2293. if (ssh->version == 1) {
  2294. PktOut *pktout = ssh_bpp_new_pktout(ssh->bpp, SSH1_MSG_DISCONNECT);
  2295. put_stringz(pktout, wire_reason);
  2296. ssh_pkt_write(ssh, pktout);
  2297. } else if (ssh->version == 2) {
  2298. PktOut *pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_DISCONNECT);
  2299. put_uint32(pktout, code);
  2300. put_stringz(pktout, wire_reason);
  2301. put_stringz(pktout, "en"); /* language tag */
  2302. ssh_pkt_write(ssh, pktout);
  2303. }
  2304. }
  2305. ssh->close_expected = TRUE;
  2306. ssh->clean_exit = clean_exit;
  2307. ssh_closing(&ssh->plugvt, error, 0, 0);
  2308. sfree(error);
  2309. }
  2310. int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint, ssh_key *key)
  2311. {
  2312. if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
  2313. return -1; /* no manual keys configured */
  2314. }
  2315. if (fingerprint) {
  2316. /*
  2317. * The fingerprint string we've been given will have things
  2318. * like 'ssh-rsa 2048' at the front of it. Strip those off and
  2319. * narrow down to just the colon-separated hex block at the
  2320. * end of the string.
  2321. */
  2322. const char *p = strrchr(fingerprint, ' ');
  2323. fingerprint = p ? p+1 : fingerprint;
  2324. /* Quick sanity checks, including making sure it's in lowercase */
  2325. assert(strlen(fingerprint) == 16*3 - 1);
  2326. assert(fingerprint[2] == ':');
  2327. assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
  2328. if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
  2329. fingerprint))
  2330. return 1; /* success */
  2331. }
  2332. if (key) {
  2333. /*
  2334. * Construct the base64-encoded public key blob and see if
  2335. * that's listed.
  2336. */
  2337. strbuf *binblob;
  2338. char *base64blob;
  2339. int atoms, i;
  2340. binblob = strbuf_new();
  2341. ssh_key_public_blob(key, BinarySink_UPCAST(binblob));
  2342. atoms = (binblob->len + 2) / 3;
  2343. base64blob = snewn(atoms * 4 + 1, char);
  2344. for (i = 0; i < atoms; i++)
  2345. base64_encode_atom(binblob->u + 3*i,
  2346. binblob->len - 3*i, base64blob + 4*i);
  2347. base64blob[atoms * 4] = '\0';
  2348. strbuf_free(binblob);
  2349. if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
  2350. base64blob)) {
  2351. sfree(base64blob);
  2352. return 1; /* success */
  2353. }
  2354. sfree(base64blob);
  2355. }
  2356. return 0;
  2357. }
  2358. static void ssh1_coro_wrapper_initial(Ssh ssh, PktIn *pktin);
  2359. static void ssh1_coro_wrapper_session(Ssh ssh, PktIn *pktin);
  2360. static void ssh1_connection_input(Ssh ssh);
  2361. /*
  2362. * Handle the key exchange and user authentication phases.
  2363. */
  2364. static void do_ssh1_login(void *vctx)
  2365. {
  2366. Ssh ssh = (Ssh)vctx;
  2367. PktIn *pktin;
  2368. PktOut *pkt;
  2369. int i, j, ret;
  2370. ptrlen pl;
  2371. struct MD5Context md5c;
  2372. struct do_ssh1_login_state {
  2373. int crLine;
  2374. int len;
  2375. unsigned char *rsabuf;
  2376. unsigned long supported_ciphers_mask, supported_auths_mask;
  2377. int tried_publickey, tried_agent;
  2378. int tis_auth_refused, ccard_auth_refused;
  2379. unsigned char cookie[8];
  2380. unsigned char session_id[16];
  2381. int cipher_type;
  2382. strbuf *publickey_blob;
  2383. char *publickey_comment;
  2384. int privatekey_available, privatekey_encrypted;
  2385. prompts_t *cur_prompt;
  2386. int userpass_ret;
  2387. char c;
  2388. int pwpkt_type;
  2389. unsigned char *agent_response;
  2390. BinarySource asrc[1]; /* response from SSH agent */
  2391. int keyi, nkeys;
  2392. int authed;
  2393. struct RSAKey key;
  2394. Bignum challenge;
  2395. ptrlen comment;
  2396. int dlgret;
  2397. Filename *keyfile;
  2398. struct RSAKey servkey, hostkey;
  2399. };
  2400. crState(do_ssh1_login_state);
  2401. crBeginState;
  2402. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_login)) != NULL);
  2403. if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
  2404. bombout(("Public key packet not received"));
  2405. crStopV;
  2406. }
  2407. logevent("Received public keys");
  2408. pl = get_data(pktin, 8);
  2409. memcpy(s->cookie, pl.ptr, pl.len);
  2410. get_rsa_ssh1_pub(pktin, &s->servkey, RSA_SSH1_EXPONENT_FIRST);
  2411. get_rsa_ssh1_pub(pktin, &s->hostkey, RSA_SSH1_EXPONENT_FIRST);
  2412. s->hostkey.comment = NULL; /* avoid confusing rsa_ssh1_fingerprint */
  2413. /*
  2414. * Log the host key fingerprint.
  2415. */
  2416. if (!get_err(pktin)) {
  2417. char *fingerprint = rsa_ssh1_fingerprint(&s->hostkey);
  2418. logevent("Host key fingerprint is:");
  2419. logeventf(ssh, " %s", fingerprint);
  2420. sfree(fingerprint);
  2421. }
  2422. ssh->v1_remote_protoflags = get_uint32(pktin);
  2423. s->supported_ciphers_mask = get_uint32(pktin);
  2424. s->supported_auths_mask = get_uint32(pktin);
  2425. if (get_err(pktin)) {
  2426. bombout(("Bad SSH-1 public key packet"));
  2427. crStopV;
  2428. }
  2429. if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
  2430. s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
  2431. ssh->v1_local_protoflags =
  2432. ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
  2433. ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
  2434. MD5Init(&md5c);
  2435. {
  2436. int i;
  2437. for (i = (bignum_bitcount(s->hostkey.modulus) + 7) / 8; i-- ;)
  2438. put_byte(&md5c, bignum_byte(s->hostkey.modulus, i));
  2439. for (i = (bignum_bitcount(s->servkey.modulus) + 7) / 8; i-- ;)
  2440. put_byte(&md5c, bignum_byte(s->servkey.modulus, i));
  2441. }
  2442. put_data(&md5c, s->cookie, 8);
  2443. MD5Final(s->session_id, &md5c);
  2444. for (i = 0; i < 32; i++)
  2445. ssh->session_key[i] = random_byte();
  2446. /*
  2447. * Verify that the `bits' and `bytes' parameters match.
  2448. */
  2449. if (s->hostkey.bits > s->hostkey.bytes * 8 ||
  2450. s->servkey.bits > s->servkey.bytes * 8) {
  2451. bombout(("SSH-1 public keys were badly formatted"));
  2452. crStopV;
  2453. }
  2454. s->len = (s->hostkey.bytes > s->servkey.bytes ?
  2455. s->hostkey.bytes : s->servkey.bytes);
  2456. s->rsabuf = snewn(s->len, unsigned char);
  2457. /*
  2458. * Verify the host key.
  2459. */
  2460. {
  2461. /*
  2462. * First format the key into a string.
  2463. */
  2464. int len = rsastr_len(&s->hostkey);
  2465. char *fingerprint;
  2466. char *keystr = snewn(len, char);
  2467. rsastr_fmt(keystr, &s->hostkey);
  2468. fingerprint = rsa_ssh1_fingerprint(&s->hostkey);
  2469. /* First check against manually configured host keys. */
  2470. s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL);
  2471. sfree(fingerprint);
  2472. if (s->dlgret == 0) { /* did not match */
  2473. bombout(("Host key did not appear in manually configured list"));
  2474. sfree(keystr);
  2475. crStopV;
  2476. } else if (s->dlgret < 0) { /* none configured; use standard handling */
  2477. ssh_set_frozen(ssh, 1);
  2478. s->dlgret = verify_ssh_host_key(ssh->frontend,
  2479. ssh->savedhost, ssh->savedport,
  2480. "rsa", keystr, fingerprint,
  2481. ssh_dialog_callback, ssh);
  2482. sfree(keystr);
  2483. #ifdef FUZZING
  2484. s->dlgret = 1;
  2485. #endif
  2486. if (s->dlgret < 0) {
  2487. ssh->user_response = -1;
  2488. crWaitUntilV(ssh->user_response >= 0);
  2489. s->dlgret = ssh->user_response;
  2490. }
  2491. ssh_set_frozen(ssh, 0);
  2492. if (s->dlgret == 0) {
  2493. ssh_disconnect(ssh, "User aborted at host key verification",
  2494. NULL, 0, TRUE);
  2495. crStopV;
  2496. }
  2497. } else {
  2498. sfree(keystr);
  2499. }
  2500. }
  2501. for (i = 0; i < 32; i++) {
  2502. s->rsabuf[i] = ssh->session_key[i];
  2503. if (i < 16)
  2504. s->rsabuf[i] ^= s->session_id[i];
  2505. }
  2506. if (s->hostkey.bytes > s->servkey.bytes) {
  2507. ret = rsa_ssh1_encrypt(s->rsabuf, 32, &s->servkey);
  2508. if (ret)
  2509. ret = rsa_ssh1_encrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
  2510. } else {
  2511. ret = rsa_ssh1_encrypt(s->rsabuf, 32, &s->hostkey);
  2512. if (ret)
  2513. ret = rsa_ssh1_encrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
  2514. }
  2515. if (!ret) {
  2516. bombout(("SSH-1 public key encryptions failed due to bad formatting"));
  2517. crStopV;
  2518. }
  2519. logevent("Encrypted session key");
  2520. {
  2521. int cipher_chosen = 0, warn = 0;
  2522. const char *cipher_string = NULL;
  2523. int i;
  2524. for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
  2525. int next_cipher = conf_get_int_int(ssh->conf,
  2526. CONF_ssh_cipherlist, i);
  2527. if (next_cipher == CIPHER_WARN) {
  2528. /* If/when we choose a cipher, warn about it */
  2529. warn = 1;
  2530. } else if (next_cipher == CIPHER_AES) {
  2531. /* XXX Probably don't need to mention this. */
  2532. logevent("AES not supported in SSH-1, skipping");
  2533. } else {
  2534. switch (next_cipher) {
  2535. case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
  2536. cipher_string = "3DES"; break;
  2537. case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
  2538. cipher_string = "Blowfish"; break;
  2539. case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
  2540. cipher_string = "single-DES"; break;
  2541. }
  2542. if (s->supported_ciphers_mask & (1 << s->cipher_type))
  2543. cipher_chosen = 1;
  2544. }
  2545. }
  2546. if (!cipher_chosen) {
  2547. if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
  2548. bombout(("Server violates SSH-1 protocol by not "
  2549. "supporting 3DES encryption"));
  2550. else
  2551. /* shouldn't happen */
  2552. bombout(("No supported ciphers found"));
  2553. crStopV;
  2554. }
  2555. /* Warn about chosen cipher if necessary. */
  2556. if (warn) {
  2557. ssh_set_frozen(ssh, 1);
  2558. s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
  2559. ssh_dialog_callback, ssh);
  2560. if (s->dlgret < 0) {
  2561. ssh->user_response = -1;
  2562. crWaitUntilV(ssh->user_response >= 0);
  2563. s->dlgret = ssh->user_response;
  2564. }
  2565. ssh_set_frozen(ssh, 0);
  2566. if (s->dlgret == 0) {
  2567. ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
  2568. 0, TRUE);
  2569. crStopV;
  2570. }
  2571. }
  2572. }
  2573. switch (s->cipher_type) {
  2574. case SSH_CIPHER_3DES:
  2575. logevent("Using 3DES encryption");
  2576. break;
  2577. case SSH_CIPHER_DES:
  2578. logevent("Using single-DES encryption");
  2579. break;
  2580. case SSH_CIPHER_BLOWFISH:
  2581. logevent("Using Blowfish encryption");
  2582. break;
  2583. }
  2584. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_SESSION_KEY);
  2585. put_byte(pkt, s->cipher_type);
  2586. put_data(pkt, s->cookie, 8);
  2587. put_uint16(pkt, s->len * 8);
  2588. put_data(pkt, s->rsabuf, s->len);
  2589. put_uint32(pkt, ssh->v1_local_protoflags);
  2590. ssh_pkt_write(ssh, pkt);
  2591. logevent("Trying to enable encryption...");
  2592. sfree(s->rsabuf);
  2593. {
  2594. const struct ssh_cipher *cipher =
  2595. (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
  2596. s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
  2597. &ssh_3des);
  2598. ssh1_bpp_new_cipher(ssh->bpp, cipher, ssh->session_key);
  2599. logeventf(ssh, "Initialised %s encryption", cipher->text_name);
  2600. }
  2601. if (s->servkey.modulus) {
  2602. sfree(s->servkey.modulus);
  2603. s->servkey.modulus = NULL;
  2604. }
  2605. if (s->servkey.exponent) {
  2606. sfree(s->servkey.exponent);
  2607. s->servkey.exponent = NULL;
  2608. }
  2609. if (s->hostkey.modulus) {
  2610. sfree(s->hostkey.modulus);
  2611. s->hostkey.modulus = NULL;
  2612. }
  2613. if (s->hostkey.exponent) {
  2614. sfree(s->hostkey.exponent);
  2615. s->hostkey.exponent = NULL;
  2616. }
  2617. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_login)) != NULL);
  2618. if (pktin->type != SSH1_SMSG_SUCCESS) {
  2619. bombout(("Encryption not successfully enabled"));
  2620. crStopV;
  2621. }
  2622. logevent("Successfully started encryption");
  2623. fflush(stdout); /* FIXME eh? */
  2624. if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
  2625. s->cur_prompt = new_prompts(ssh->frontend);
  2626. s->cur_prompt->to_server = TRUE;
  2627. s->cur_prompt->name = dupstr("SSH login name");
  2628. add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
  2629. s->userpass_ret = get_userpass_input(s->cur_prompt, NULL);
  2630. while (1) {
  2631. while (s->userpass_ret < 0 &&
  2632. bufchain_size(&ssh->user_input) > 0)
  2633. s->userpass_ret = get_userpass_input(
  2634. s->cur_prompt, &ssh->user_input);
  2635. if (s->userpass_ret >= 0)
  2636. break;
  2637. ssh->send_ok = 1;
  2638. crReturnV;
  2639. ssh->send_ok = 0;
  2640. }
  2641. if (!s->userpass_ret) {
  2642. /*
  2643. * Failed to get a username. Terminate.
  2644. */
  2645. free_prompts(s->cur_prompt);
  2646. ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
  2647. crStopV;
  2648. }
  2649. ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
  2650. free_prompts(s->cur_prompt);
  2651. }
  2652. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_USER);
  2653. put_stringz(pkt, ssh->username);
  2654. ssh_pkt_write(ssh, pkt);
  2655. {
  2656. char *userlog = dupprintf(MPEXT_BOM "Sent username \"%s\"", ssh->username);
  2657. logevent(userlog);
  2658. if (flags & FLAG_INTERACTIVE &&
  2659. (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
  2660. c_write_str(ssh, userlog);
  2661. c_write_str(ssh, "\r\n");
  2662. }
  2663. sfree(userlog);
  2664. }
  2665. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_login)) != NULL);
  2666. if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
  2667. /* We must not attempt PK auth. Pretend we've already tried it. */
  2668. s->tried_publickey = s->tried_agent = 1;
  2669. } else {
  2670. s->tried_publickey = s->tried_agent = 0;
  2671. }
  2672. s->tis_auth_refused = s->ccard_auth_refused = 0;
  2673. /*
  2674. * Load the public half of any configured keyfile for later use.
  2675. */
  2676. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  2677. if (!filename_is_null(s->keyfile)) {
  2678. int keytype;
  2679. logeventf(ssh, MPEXT_BOM "Reading key file \"%.150s\"",
  2680. filename_to_str(s->keyfile));
  2681. keytype = key_type(s->keyfile);
  2682. if (keytype == SSH_KEYTYPE_SSH1 ||
  2683. keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
  2684. const char *error;
  2685. s->publickey_blob = strbuf_new();
  2686. if (rsa_ssh1_loadpub(s->keyfile,
  2687. BinarySink_UPCAST(s->publickey_blob),
  2688. &s->publickey_comment, &error)) {
  2689. s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
  2690. if (!s->privatekey_available)
  2691. logeventf(ssh, "Key file contains public key only");
  2692. s->privatekey_encrypted = rsa_ssh1_encrypted(s->keyfile, NULL);
  2693. } else {
  2694. char *msgbuf;
  2695. logeventf(ssh, "Unable to load key (%s)", error);
  2696. msgbuf = dupprintf(MPEXT_BOM "Unable to load key file "
  2697. "\"%.150s\" (%s)\r\n",
  2698. filename_to_str(s->keyfile),
  2699. error);
  2700. c_write_str(ssh, msgbuf);
  2701. sfree(msgbuf);
  2702. strbuf_free(s->publickey_blob);
  2703. s->publickey_blob = NULL;
  2704. }
  2705. } else {
  2706. char *msgbuf;
  2707. logeventf(ssh, "Unable to use this key file (%s)",
  2708. key_type_to_str(keytype));
  2709. msgbuf = dupprintf(MPEXT_BOM "Unable to use key file \"%.150s\""
  2710. " (%s)\r\n",
  2711. filename_to_str(s->keyfile),
  2712. key_type_to_str(keytype));
  2713. c_write_str(ssh, msgbuf);
  2714. sfree(msgbuf);
  2715. s->publickey_blob = NULL;
  2716. }
  2717. } else
  2718. s->publickey_blob = NULL;
  2719. while (pktin->type == SSH1_SMSG_FAILURE) {
  2720. s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
  2721. if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
  2722. /*
  2723. * Attempt RSA authentication using Pageant.
  2724. */
  2725. void *r;
  2726. int rlen;
  2727. strbuf *request;
  2728. s->authed = FALSE;
  2729. s->tried_agent = 1;
  2730. logevent("Pageant is running. Requesting keys.");
  2731. /* Request the keys held by the agent. */
  2732. request = strbuf_new_for_agent_query();
  2733. put_byte(request, SSH1_AGENTC_REQUEST_RSA_IDENTITIES);
  2734. ssh->auth_agent_query = agent_query(
  2735. request, &r, &rlen, ssh_agent_callback, ssh);
  2736. strbuf_free(request);
  2737. if (ssh->auth_agent_query) {
  2738. ssh->agent_response = NULL;
  2739. crWaitUntilV(ssh->agent_response);
  2740. r = ssh->agent_response;
  2741. rlen = ssh->agent_response_len;
  2742. }
  2743. s->agent_response = r;
  2744. BinarySource_BARE_INIT(s->asrc, r, rlen);
  2745. get_uint32(s->asrc); /* skip length field */
  2746. if (get_byte(s->asrc) == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
  2747. s->nkeys = toint(get_uint32(s->asrc));
  2748. if (s->nkeys < 0) {
  2749. logeventf(ssh, "Pageant reported negative key count %d",
  2750. s->nkeys);
  2751. s->nkeys = 0;
  2752. }
  2753. logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
  2754. for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
  2755. size_t start, end;
  2756. start = s->asrc->pos;
  2757. get_rsa_ssh1_pub(s->asrc, &s->key,
  2758. RSA_SSH1_EXPONENT_FIRST);
  2759. end = s->asrc->pos;
  2760. s->comment = get_string(s->asrc);
  2761. if (get_err(s->asrc)) {
  2762. logevent("Pageant key list packet was truncated");
  2763. break;
  2764. }
  2765. if (s->publickey_blob) {
  2766. ptrlen keystr = make_ptrlen(
  2767. (const char *)s->asrc->data + start, end - start);
  2768. if (keystr.len == s->publickey_blob->len &&
  2769. !memcmp(keystr.ptr, s->publickey_blob->s,
  2770. s->publickey_blob->len)) {
  2771. logeventf(ssh, "Pageant key #%d matches "
  2772. "configured key file", s->keyi);
  2773. s->tried_publickey = 1;
  2774. } else
  2775. /* Skip non-configured key */
  2776. continue;
  2777. }
  2778. logeventf(ssh, "Trying Pageant key #%d", s->keyi);
  2779. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_AUTH_RSA);
  2780. put_mp_ssh1(pkt, s->key.modulus);
  2781. ssh_pkt_write(ssh, pkt);
  2782. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_login))
  2783. != NULL);
  2784. if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
  2785. logevent("Key refused");
  2786. continue;
  2787. }
  2788. logevent("Received RSA challenge");
  2789. s->challenge = get_mp_ssh1(pktin);
  2790. if (get_err(pktin)) {
  2791. freebn(s->challenge);
  2792. bombout(("Server's RSA challenge was badly formatted"));
  2793. crStopV;
  2794. }
  2795. {
  2796. strbuf *agentreq;
  2797. char *ret;
  2798. void *vret;
  2799. int retlen;
  2800. agentreq = strbuf_new_for_agent_query();
  2801. put_byte(agentreq, SSH1_AGENTC_RSA_CHALLENGE);
  2802. put_uint32(agentreq, bignum_bitcount(s->key.modulus));
  2803. put_mp_ssh1(agentreq, s->key.exponent);
  2804. put_mp_ssh1(agentreq, s->key.modulus);
  2805. put_mp_ssh1(agentreq, s->challenge);
  2806. put_data(agentreq, s->session_id, 16);
  2807. put_uint32(agentreq, 1); /* response format */
  2808. ssh->auth_agent_query = agent_query(
  2809. agentreq, &vret, &retlen,
  2810. ssh_agent_callback, ssh);
  2811. strbuf_free(agentreq);
  2812. if (ssh->auth_agent_query) {
  2813. ssh->agent_response = NULL;
  2814. crWaitUntilV(ssh->agent_response);
  2815. vret = ssh->agent_response;
  2816. retlen = ssh->agent_response_len;
  2817. }
  2818. ret = vret;
  2819. if (ret) {
  2820. if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
  2821. logevent("Sending Pageant's response");
  2822. pkt = ssh_bpp_new_pktout(ssh->bpp,
  2823. SSH1_CMSG_AUTH_RSA_RESPONSE);
  2824. put_data(pkt, ret + 5, 16);
  2825. ssh_pkt_write(ssh, pkt);
  2826. sfree(ret);
  2827. crMaybeWaitUntilV(
  2828. (pktin = pq_pop(&ssh->pq_ssh1_login))
  2829. != NULL);
  2830. if (pktin->type == SSH1_SMSG_SUCCESS) {
  2831. logevent
  2832. ("Pageant's response accepted");
  2833. if (flags & FLAG_VERBOSE) {
  2834. c_write_str(ssh, "Authenticated using"
  2835. " RSA key \"");
  2836. c_write(ssh, s->comment.ptr,
  2837. s->comment.len);
  2838. c_write_str(ssh, "\" from agent\r\n");
  2839. }
  2840. s->authed = TRUE;
  2841. } else
  2842. logevent
  2843. ("Pageant's response not accepted");
  2844. } else {
  2845. logevent
  2846. ("Pageant failed to answer challenge");
  2847. sfree(ret);
  2848. }
  2849. } else {
  2850. logevent("No reply received from Pageant");
  2851. }
  2852. }
  2853. freebn(s->key.exponent);
  2854. freebn(s->key.modulus);
  2855. freebn(s->challenge);
  2856. if (s->authed)
  2857. break;
  2858. }
  2859. sfree(s->agent_response);
  2860. if (s->publickey_blob && !s->tried_publickey)
  2861. logevent("Configured key file not in Pageant");
  2862. } else {
  2863. logevent("Failed to get reply from Pageant");
  2864. }
  2865. if (s->authed)
  2866. break;
  2867. }
  2868. if (s->publickey_blob && s->privatekey_available &&
  2869. !s->tried_publickey) {
  2870. /*
  2871. * Try public key authentication with the specified
  2872. * key file.
  2873. */
  2874. int got_passphrase; /* need not be kept over crReturn */
  2875. if (flags & FLAG_VERBOSE)
  2876. c_write_str(ssh, "Trying public key authentication.\r\n");
  2877. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  2878. logeventf(ssh, MPEXT_BOM "Trying public key \"%s\"",
  2879. filename_to_str(s->keyfile));
  2880. s->tried_publickey = 1;
  2881. got_passphrase = FALSE;
  2882. while (!got_passphrase) {
  2883. /*
  2884. * Get a passphrase, if necessary.
  2885. */
  2886. char *passphrase = NULL; /* only written after crReturn */
  2887. const char *error;
  2888. if (!s->privatekey_encrypted) {
  2889. if (flags & FLAG_VERBOSE)
  2890. c_write_str(ssh, "No passphrase required.\r\n");
  2891. passphrase = NULL;
  2892. } else {
  2893. s->cur_prompt = new_prompts(ssh->frontend);
  2894. s->cur_prompt->to_server = FALSE;
  2895. s->cur_prompt->name = dupstr("SSH key passphrase");
  2896. add_prompt(s->cur_prompt,
  2897. dupprintf("Passphrase for key \"%.100s\": ",
  2898. s->publickey_comment), FALSE);
  2899. s->userpass_ret = get_userpass_input(s->cur_prompt, NULL);
  2900. while (1) {
  2901. while (s->userpass_ret < 0 &&
  2902. bufchain_size(&ssh->user_input) > 0)
  2903. s->userpass_ret = get_userpass_input(
  2904. s->cur_prompt, &ssh->user_input);
  2905. if (s->userpass_ret >= 0)
  2906. break;
  2907. ssh->send_ok = 1;
  2908. crReturnV;
  2909. ssh->send_ok = 0;
  2910. }
  2911. if (!s->userpass_ret) {
  2912. /* Failed to get a passphrase. Terminate. */
  2913. free_prompts(s->cur_prompt);
  2914. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  2915. 0, TRUE);
  2916. crStopV;
  2917. }
  2918. passphrase = dupstr(s->cur_prompt->prompts[0]->result);
  2919. free_prompts(s->cur_prompt);
  2920. }
  2921. /*
  2922. * Try decrypting key with passphrase.
  2923. */
  2924. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  2925. ret = rsa_ssh1_loadkey(
  2926. s->keyfile, &s->key, passphrase, &error);
  2927. if (passphrase) {
  2928. smemclr(passphrase, strlen(passphrase));
  2929. sfree(passphrase);
  2930. }
  2931. if (ret == 1) {
  2932. /* Correct passphrase. */
  2933. got_passphrase = TRUE;
  2934. } else if (ret == 0) {
  2935. c_write_str(ssh, MPEXT_BOM "Couldn't load private key from ");
  2936. c_write_str(ssh, filename_to_str(s->keyfile));
  2937. c_write_str(ssh, " (");
  2938. c_write_str(ssh, error);
  2939. c_write_str(ssh, ").\r\n");
  2940. got_passphrase = FALSE;
  2941. break; /* go and try something else */
  2942. } else if (ret == -1) {
  2943. c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
  2944. got_passphrase = FALSE;
  2945. /* and try again */
  2946. } else {
  2947. assert(0 && "unexpected return from rsa_ssh1_loadkey()");
  2948. got_passphrase = FALSE; /* placate optimisers */
  2949. }
  2950. }
  2951. if (got_passphrase) {
  2952. /*
  2953. * Send a public key attempt.
  2954. */
  2955. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_AUTH_RSA);
  2956. put_mp_ssh1(pkt, s->key.modulus);
  2957. ssh_pkt_write(ssh, pkt);
  2958. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_login))
  2959. != NULL);
  2960. if (pktin->type == SSH1_SMSG_FAILURE) {
  2961. c_write_str(ssh, "Server refused our public key.\r\n");
  2962. continue; /* go and try something else */
  2963. }
  2964. if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
  2965. bombout(("Bizarre response to offer of public key"));
  2966. crStopV;
  2967. }
  2968. {
  2969. int i;
  2970. unsigned char buffer[32];
  2971. Bignum challenge, response;
  2972. challenge = get_mp_ssh1(pktin);
  2973. if (get_err(pktin)) {
  2974. freebn(challenge);
  2975. bombout(("Server's RSA challenge was badly formatted"));
  2976. crStopV;
  2977. }
  2978. response = rsa_ssh1_decrypt(challenge, &s->key);
  2979. freebn(s->key.private_exponent);/* burn the evidence */
  2980. for (i = 0; i < 32; i++) {
  2981. buffer[i] = bignum_byte(response, 31 - i);
  2982. }
  2983. MD5Init(&md5c);
  2984. put_data(&md5c, buffer, 32);
  2985. put_data(&md5c, s->session_id, 16);
  2986. MD5Final(buffer, &md5c);
  2987. pkt = ssh_bpp_new_pktout(
  2988. ssh->bpp, SSH1_CMSG_AUTH_RSA_RESPONSE);
  2989. put_data(pkt, buffer, 16);
  2990. ssh_pkt_write(ssh, pkt);
  2991. freebn(challenge);
  2992. freebn(response);
  2993. }
  2994. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_login))
  2995. != NULL);
  2996. if (pktin->type == SSH1_SMSG_FAILURE) {
  2997. if (flags & FLAG_VERBOSE)
  2998. c_write_str(ssh, "Failed to authenticate with"
  2999. " our public key.\r\n");
  3000. continue; /* go and try something else */
  3001. } else if (pktin->type != SSH1_SMSG_SUCCESS) {
  3002. bombout(("Bizarre response to RSA authentication response"));
  3003. crStopV;
  3004. }
  3005. break; /* we're through! */
  3006. }
  3007. }
  3008. /*
  3009. * Otherwise, try various forms of password-like authentication.
  3010. */
  3011. s->cur_prompt = new_prompts(ssh->frontend);
  3012. if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
  3013. (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
  3014. !s->tis_auth_refused) {
  3015. s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
  3016. logevent("Requested TIS authentication");
  3017. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_AUTH_TIS);
  3018. ssh_pkt_write(ssh, pkt);
  3019. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_login)) != NULL);
  3020. if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
  3021. logevent("TIS authentication declined");
  3022. if (flags & FLAG_INTERACTIVE)
  3023. c_write_str(ssh, "TIS authentication refused.\r\n");
  3024. s->tis_auth_refused = 1;
  3025. continue;
  3026. } else {
  3027. ptrlen challenge;
  3028. char *instr_suf, *prompt;
  3029. challenge = get_string(pktin);
  3030. if (get_err(pktin)) {
  3031. bombout(("TIS challenge packet was badly formed"));
  3032. crStopV;
  3033. }
  3034. logevent("Received TIS challenge");
  3035. s->cur_prompt->to_server = TRUE;
  3036. s->cur_prompt->name = dupstr("SSH TIS authentication");
  3037. /* Prompt heuristic comes from OpenSSH */
  3038. if (memchr(challenge.ptr, '\n', challenge.len)) {
  3039. instr_suf = dupstr("");
  3040. prompt = mkstr(challenge);
  3041. } else {
  3042. instr_suf = mkstr(challenge);
  3043. prompt = dupstr("Response: ");
  3044. }
  3045. s->cur_prompt->instruction =
  3046. dupprintf("Using TIS authentication.%s%s",
  3047. (*instr_suf) ? "\n" : "",
  3048. instr_suf);
  3049. s->cur_prompt->instr_reqd = TRUE;
  3050. add_prompt(s->cur_prompt, prompt, FALSE);
  3051. sfree(instr_suf);
  3052. }
  3053. }
  3054. if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
  3055. (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
  3056. !s->ccard_auth_refused) {
  3057. s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
  3058. logevent("Requested CryptoCard authentication");
  3059. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_AUTH_CCARD);
  3060. ssh_pkt_write(ssh, pkt);
  3061. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_login)) != NULL);
  3062. if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
  3063. logevent("CryptoCard authentication declined");
  3064. c_write_str(ssh, "CryptoCard authentication refused.\r\n");
  3065. s->ccard_auth_refused = 1;
  3066. continue;
  3067. } else {
  3068. ptrlen challenge;
  3069. char *instr_suf, *prompt;
  3070. challenge = get_string(pktin);
  3071. if (get_err(pktin)) {
  3072. bombout(("CryptoCard challenge packet was badly formed"));
  3073. crStopV;
  3074. }
  3075. logevent("Received CryptoCard challenge");
  3076. s->cur_prompt->to_server = TRUE;
  3077. s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
  3078. s->cur_prompt->name_reqd = FALSE;
  3079. /* Prompt heuristic comes from OpenSSH */
  3080. if (memchr(challenge.ptr, '\n', challenge.len)) {
  3081. instr_suf = dupstr("");
  3082. prompt = mkstr(challenge);
  3083. } else {
  3084. instr_suf = mkstr(challenge);
  3085. prompt = dupstr("Response: ");
  3086. }
  3087. s->cur_prompt->instruction =
  3088. dupprintf("Using CryptoCard authentication.%s%s",
  3089. (*instr_suf) ? "\n" : "",
  3090. instr_suf);
  3091. s->cur_prompt->instr_reqd = TRUE;
  3092. add_prompt(s->cur_prompt, prompt, FALSE);
  3093. sfree(instr_suf);
  3094. }
  3095. }
  3096. if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
  3097. if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
  3098. bombout(("No supported authentication methods available"));
  3099. crStopV;
  3100. }
  3101. s->cur_prompt->to_server = TRUE;
  3102. s->cur_prompt->name = dupstr("SSH password");
  3103. add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
  3104. ssh->username, ssh->savedhost),
  3105. FALSE);
  3106. }
  3107. /*
  3108. * Show password prompt, having first obtained it via a TIS
  3109. * or CryptoCard exchange if we're doing TIS or CryptoCard
  3110. * authentication.
  3111. */
  3112. s->userpass_ret = get_userpass_input(s->cur_prompt, NULL);
  3113. while (1) {
  3114. while (s->userpass_ret < 0 &&
  3115. bufchain_size(&ssh->user_input) > 0)
  3116. s->userpass_ret = get_userpass_input(
  3117. s->cur_prompt, &ssh->user_input);
  3118. if (s->userpass_ret >= 0)
  3119. break;
  3120. ssh->send_ok = 1;
  3121. crReturnV;
  3122. ssh->send_ok = 0;
  3123. }
  3124. if (!s->userpass_ret) {
  3125. /*
  3126. * Failed to get a password (for example
  3127. * because one was supplied on the command line
  3128. * which has already failed to work). Terminate.
  3129. */
  3130. free_prompts(s->cur_prompt);
  3131. ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
  3132. crStopV;
  3133. }
  3134. if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
  3135. /*
  3136. * Defence against traffic analysis: we send a
  3137. * whole bunch of packets containing strings of
  3138. * different lengths. One of these strings is the
  3139. * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
  3140. * The others are all random data in
  3141. * SSH1_MSG_IGNORE packets. This way a passive
  3142. * listener can't tell which is the password, and
  3143. * hence can't deduce the password length.
  3144. *
  3145. * Anybody with a password length greater than 16
  3146. * bytes is going to have enough entropy in their
  3147. * password that a listener won't find it _that_
  3148. * much help to know how long it is. So what we'll
  3149. * do is:
  3150. *
  3151. * - if password length < 16, we send 15 packets
  3152. * containing string lengths 1 through 15
  3153. *
  3154. * - otherwise, we let N be the nearest multiple
  3155. * of 8 below the password length, and send 8
  3156. * packets containing string lengths N through
  3157. * N+7. This won't obscure the order of
  3158. * magnitude of the password length, but it will
  3159. * introduce a bit of extra uncertainty.
  3160. *
  3161. * A few servers can't deal with SSH1_MSG_IGNORE, at
  3162. * least in this context. For these servers, we need
  3163. * an alternative defence. We make use of the fact
  3164. * that the password is interpreted as a C string:
  3165. * so we can append a NUL, then some random data.
  3166. *
  3167. * A few servers can deal with neither SSH1_MSG_IGNORE
  3168. * here _nor_ a padded password string.
  3169. * For these servers we are left with no defences
  3170. * against password length sniffing.
  3171. */
  3172. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
  3173. !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
  3174. /*
  3175. * The server can deal with SSH1_MSG_IGNORE, so
  3176. * we can use the primary defence.
  3177. */
  3178. int bottom, top, pwlen, i;
  3179. pwlen = strlen(s->cur_prompt->prompts[0]->result);
  3180. if (pwlen < 16) {
  3181. bottom = 0; /* zero length passwords are OK! :-) */
  3182. top = 15;
  3183. } else {
  3184. bottom = pwlen & ~7;
  3185. top = bottom + 7;
  3186. }
  3187. assert(pwlen >= bottom && pwlen <= top);
  3188. for (i = bottom; i <= top; i++) {
  3189. if (i == pwlen) {
  3190. pkt = ssh_bpp_new_pktout(ssh->bpp, s->pwpkt_type);
  3191. put_stringz(pkt, s->cur_prompt->prompts[0]->result);
  3192. ssh_pkt_write(ssh, pkt);
  3193. } else {
  3194. strbuf *random_data = strbuf_new();
  3195. for (j = 0; j < i; j++)
  3196. put_byte(random_data, random_byte());
  3197. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_MSG_IGNORE);
  3198. put_stringsb(pkt, random_data);
  3199. ssh_pkt_write(ssh, pkt);
  3200. }
  3201. }
  3202. logevent("Sending password with camouflage packets");
  3203. }
  3204. else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
  3205. /*
  3206. * The server can't deal with SSH1_MSG_IGNORE
  3207. * but can deal with padded passwords, so we
  3208. * can use the secondary defence.
  3209. */
  3210. strbuf *padded_pw = strbuf_new();
  3211. logevent("Sending length-padded password");
  3212. pkt = ssh_bpp_new_pktout(ssh->bpp, s->pwpkt_type);
  3213. put_asciz(padded_pw, s->cur_prompt->prompts[0]->result);
  3214. do {
  3215. put_byte(padded_pw, random_byte());
  3216. } while (padded_pw->len % 64 != 0);
  3217. put_stringsb(pkt, padded_pw);
  3218. ssh_pkt_write(ssh, pkt);
  3219. } else {
  3220. /*
  3221. * The server is believed unable to cope with
  3222. * any of our password camouflage methods.
  3223. */
  3224. logevent("Sending unpadded password");
  3225. pkt = ssh_bpp_new_pktout(ssh->bpp, s->pwpkt_type);
  3226. put_stringz(pkt, s->cur_prompt->prompts[0]->result);
  3227. ssh_pkt_write(ssh, pkt);
  3228. }
  3229. } else {
  3230. pkt = ssh_bpp_new_pktout(ssh->bpp, s->pwpkt_type);
  3231. put_stringz(pkt, s->cur_prompt->prompts[0]->result);
  3232. ssh_pkt_write(ssh, pkt);
  3233. }
  3234. logevent("Sent password");
  3235. free_prompts(s->cur_prompt);
  3236. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_login)) != NULL);
  3237. if (pktin->type == SSH1_SMSG_FAILURE) {
  3238. if (flags & FLAG_VERBOSE)
  3239. c_write_str(ssh, "Access denied\r\n");
  3240. logevent("Authentication refused");
  3241. } else if (pktin->type != SSH1_SMSG_SUCCESS) {
  3242. bombout(("Strange packet received, type %d", pktin->type));
  3243. crStopV;
  3244. }
  3245. }
  3246. /* Clear up */
  3247. if (s->publickey_blob) {
  3248. strbuf_free(s->publickey_blob);
  3249. sfree(s->publickey_comment);
  3250. }
  3251. logevent("Authentication successful");
  3252. /* Set up for the next phase */
  3253. {
  3254. int i;
  3255. for (i = 0; i < SSH_MAX_MSG; i++)
  3256. if (ssh->packet_dispatch[i] == ssh1_coro_wrapper_initial)
  3257. ssh->packet_dispatch[i] = ssh1_coro_wrapper_session;
  3258. ssh->current_user_input_fn = ssh1_connection_input;
  3259. queue_idempotent_callback(&ssh->user_input_consumer);
  3260. }
  3261. crFinishV;
  3262. }
  3263. static void ssh_channel_try_eof(struct ssh_channel *c)
  3264. {
  3265. Ssh ssh = c->ssh;
  3266. PktOut *pktout;
  3267. assert(c->pending_eof); /* precondition for calling us */
  3268. if (c->halfopen)
  3269. return; /* can't close: not even opened yet */
  3270. if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
  3271. return; /* can't send EOF: pending outgoing data */
  3272. c->pending_eof = FALSE; /* we're about to send it */
  3273. if (ssh->version == 1) {
  3274. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH1_MSG_CHANNEL_CLOSE);
  3275. put_uint32(pktout, c->remoteid);
  3276. ssh_pkt_write(ssh, pktout);
  3277. c->closes |= CLOSES_SENT_EOF;
  3278. } else {
  3279. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_CHANNEL_EOF);
  3280. put_uint32(pktout, c->remoteid);
  3281. ssh2_pkt_send(ssh, pktout);
  3282. c->closes |= CLOSES_SENT_EOF;
  3283. ssh2_channel_check_close(c);
  3284. }
  3285. }
  3286. Conf *sshfwd_get_conf(struct ssh_channel *c)
  3287. {
  3288. Ssh ssh = c->ssh;
  3289. return ssh->conf;
  3290. }
  3291. void sshfwd_write_eof(struct ssh_channel *c)
  3292. {
  3293. Ssh ssh = c->ssh;
  3294. if (ssh->state == SSH_STATE_CLOSED)
  3295. return;
  3296. if (c->closes & CLOSES_SENT_EOF)
  3297. return;
  3298. c->pending_eof = TRUE;
  3299. ssh_channel_try_eof(c);
  3300. }
  3301. void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
  3302. {
  3303. Ssh ssh = c->ssh;
  3304. char *reason;
  3305. if (ssh->state == SSH_STATE_CLOSED)
  3306. return;
  3307. reason = dupprintf("due to local error: %s", err);
  3308. ssh_channel_close_local(c, reason);
  3309. sfree(reason);
  3310. c->pending_eof = FALSE; /* this will confuse a zombie channel */
  3311. ssh2_channel_check_close(c);
  3312. }
  3313. int sshfwd_write(struct ssh_channel *c, const void *buf, int len)
  3314. {
  3315. Ssh ssh = c->ssh;
  3316. if (ssh->state == SSH_STATE_CLOSED)
  3317. return 0;
  3318. return ssh_send_channel_data(c, buf, len);
  3319. }
  3320. void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
  3321. {
  3322. Ssh ssh = c->ssh;
  3323. if (ssh->state == SSH_STATE_CLOSED)
  3324. return;
  3325. ssh_channel_unthrottle(c, bufsize);
  3326. }
  3327. static void ssh_queueing_handler(Ssh ssh, PktIn *pktin)
  3328. {
  3329. struct queued_handler *qh = ssh->qhead;
  3330. assert(qh != NULL);
  3331. assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
  3332. if (qh->msg1 > 0) {
  3333. assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
  3334. ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
  3335. }
  3336. if (qh->msg2 > 0) {
  3337. assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
  3338. ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
  3339. }
  3340. if (qh->next) {
  3341. ssh->qhead = qh->next;
  3342. if (ssh->qhead->msg1 > 0) {
  3343. ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
  3344. ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
  3345. }
  3346. if (ssh->qhead->msg2 > 0) {
  3347. ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
  3348. ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
  3349. }
  3350. } else {
  3351. ssh->qhead = ssh->qtail = NULL;
  3352. }
  3353. qh->handler(ssh, pktin, qh->ctx);
  3354. sfree(qh);
  3355. }
  3356. static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
  3357. chandler_fn_t handler, void *ctx)
  3358. {
  3359. struct queued_handler *qh;
  3360. qh = snew(struct queued_handler);
  3361. qh->msg1 = msg1;
  3362. qh->msg2 = msg2;
  3363. qh->handler = handler;
  3364. qh->ctx = ctx;
  3365. qh->next = NULL;
  3366. if (ssh->qtail == NULL) {
  3367. ssh->qhead = qh;
  3368. if (qh->msg1 > 0) {
  3369. ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
  3370. ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
  3371. }
  3372. if (qh->msg2 > 0) {
  3373. ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
  3374. ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
  3375. }
  3376. } else {
  3377. ssh->qtail->next = qh;
  3378. }
  3379. ssh->qtail = qh;
  3380. }
  3381. static void ssh_rportfwd_succfail(Ssh ssh, PktIn *pktin, void *ctx)
  3382. {
  3383. struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
  3384. if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
  3385. SSH2_MSG_REQUEST_SUCCESS)) {
  3386. logeventf(ssh, "Remote port forwarding from %s enabled",
  3387. pf->sportdesc);
  3388. } else {
  3389. logeventf(ssh, "Remote port forwarding from %s refused",
  3390. pf->sportdesc);
  3391. rpf = del234(ssh->rportfwds, pf);
  3392. assert(rpf == pf);
  3393. pf->pfrec->remote = NULL;
  3394. free_rportfwd(pf);
  3395. }
  3396. }
  3397. int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
  3398. ssh_sharing_connstate *share_ctx)
  3399. {
  3400. struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
  3401. pf->dhost = NULL;
  3402. pf->dport = 0;
  3403. pf->share_ctx = share_ctx;
  3404. pf->shost = dupstr(shost);
  3405. pf->sport = sport;
  3406. pf->sportdesc = NULL;
  3407. if (!ssh->rportfwds) {
  3408. assert(ssh->version == 2);
  3409. ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
  3410. }
  3411. if (add234(ssh->rportfwds, pf) != pf) {
  3412. sfree(pf->shost);
  3413. sfree(pf);
  3414. return FALSE;
  3415. }
  3416. return TRUE;
  3417. }
  3418. void ssh_remove_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
  3419. ssh_sharing_connstate *share_ctx)
  3420. {
  3421. struct ssh_rportfwd pf, *realpf;
  3422. assert(ssh->rportfwds);
  3423. pf.shost = dupstr(shost);
  3424. pf.sport = sport;
  3425. realpf = del234(ssh->rportfwds, &pf);
  3426. assert(realpf);
  3427. assert(realpf->share_ctx == share_ctx);
  3428. sfree(realpf->shost);
  3429. sfree(realpf);
  3430. }
  3431. static void ssh_sharing_global_request_response(Ssh ssh, PktIn *pktin,
  3432. void *ctx)
  3433. {
  3434. share_got_pkt_from_server(ctx, pktin->type,
  3435. BinarySource_UPCAST(pktin)->data,
  3436. BinarySource_UPCAST(pktin)->len);
  3437. }
  3438. void ssh_sharing_queue_global_request(Ssh ssh,
  3439. ssh_sharing_connstate *share_ctx)
  3440. {
  3441. ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
  3442. ssh_sharing_global_request_response, share_ctx);
  3443. }
  3444. static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
  3445. {
  3446. struct ssh_portfwd *epf;
  3447. int i;
  3448. char *key, *val;
  3449. if (!ssh->portfwds) {
  3450. ssh->portfwds = newtree234(ssh_portcmp);
  3451. } else {
  3452. /*
  3453. * Go through the existing port forwardings and tag them
  3454. * with status==DESTROY. Any that we want to keep will be
  3455. * re-enabled (status==KEEP) as we go through the
  3456. * configuration and find out which bits are the same as
  3457. * they were before.
  3458. */
  3459. struct ssh_portfwd *epf;
  3460. int i;
  3461. for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
  3462. epf->status = DESTROY;
  3463. }
  3464. for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
  3465. val != NULL;
  3466. val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
  3467. char *kp, *kp2, *vp, *vp2;
  3468. char address_family, type;
  3469. int sport,dport,sserv,dserv;
  3470. char *sports, *dports, *saddr, *host;
  3471. kp = key;
  3472. address_family = 'A';
  3473. type = 'L';
  3474. if (*kp == 'A' || *kp == '4' || *kp == '6')
  3475. address_family = *kp++;
  3476. if (*kp == 'L' || *kp == 'R')
  3477. type = *kp++;
  3478. if ((kp2 = host_strchr(kp, ':')) != NULL) {
  3479. /*
  3480. * There's a colon in the middle of the source port
  3481. * string, which means that the part before it is
  3482. * actually a source address.
  3483. */
  3484. char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
  3485. saddr = host_strduptrim(saddr_tmp);
  3486. sfree(saddr_tmp);
  3487. sports = kp2+1;
  3488. } else {
  3489. saddr = NULL;
  3490. sports = kp;
  3491. }
  3492. sport = atoi(sports);
  3493. sserv = 0;
  3494. if (sport == 0) {
  3495. sserv = 1;
  3496. sport = net_service_lookup(sports);
  3497. if (!sport) {
  3498. logeventf(ssh, "Service lookup failed for source"
  3499. " port \"%s\"", sports);
  3500. }
  3501. }
  3502. if (type == 'L' && !strcmp(val, "D")) {
  3503. /* dynamic forwarding */
  3504. host = NULL;
  3505. dports = NULL;
  3506. dport = -1;
  3507. dserv = 0;
  3508. type = 'D';
  3509. } else {
  3510. /* ordinary forwarding */
  3511. vp = val;
  3512. vp2 = vp + host_strcspn(vp, ":");
  3513. host = dupprintf("%.*s", (int)(vp2 - vp), vp);
  3514. if (*vp2)
  3515. vp2++;
  3516. dports = vp2;
  3517. dport = atoi(dports);
  3518. dserv = 0;
  3519. if (dport == 0) {
  3520. dserv = 1;
  3521. dport = net_service_lookup(dports);
  3522. if (!dport) {
  3523. logeventf(ssh, "Service lookup failed for destination"
  3524. " port \"%s\"", dports);
  3525. }
  3526. }
  3527. }
  3528. if (sport && dport) {
  3529. /* Set up a description of the source port. */
  3530. struct ssh_portfwd *pfrec, *epfrec;
  3531. pfrec = snew(struct ssh_portfwd);
  3532. pfrec->type = type;
  3533. pfrec->saddr = saddr;
  3534. pfrec->sserv = sserv ? dupstr(sports) : NULL;
  3535. pfrec->sport = sport;
  3536. pfrec->daddr = host;
  3537. pfrec->dserv = dserv ? dupstr(dports) : NULL;
  3538. pfrec->dport = dport;
  3539. pfrec->local = NULL;
  3540. pfrec->remote = NULL;
  3541. pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
  3542. address_family == '6' ? ADDRTYPE_IPV6 :
  3543. ADDRTYPE_UNSPEC);
  3544. epfrec = add234(ssh->portfwds, pfrec);
  3545. if (epfrec != pfrec) {
  3546. if (epfrec->status == DESTROY) {
  3547. /*
  3548. * We already have a port forwarding up and running
  3549. * with precisely these parameters. Hence, no need
  3550. * to do anything; simply re-tag the existing one
  3551. * as KEEP.
  3552. */
  3553. epfrec->status = KEEP;
  3554. }
  3555. /*
  3556. * Anything else indicates that there was a duplicate
  3557. * in our input, which we'll silently ignore.
  3558. */
  3559. free_portfwd(pfrec);
  3560. } else {
  3561. pfrec->status = CREATE;
  3562. }
  3563. } else {
  3564. sfree(saddr);
  3565. sfree(host);
  3566. }
  3567. }
  3568. /*
  3569. * Now go through and destroy any port forwardings which were
  3570. * not re-enabled.
  3571. */
  3572. for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
  3573. if (epf->status == DESTROY) {
  3574. char *message;
  3575. message = dupprintf("%s port forwarding from %s%s%d",
  3576. epf->type == 'L' ? "local" :
  3577. epf->type == 'R' ? "remote" : "dynamic",
  3578. epf->saddr ? epf->saddr : "",
  3579. epf->saddr ? ":" : "",
  3580. epf->sport);
  3581. if (epf->type != 'D') {
  3582. char *msg2 = dupprintf("%s to %s:%d", message,
  3583. epf->daddr, epf->dport);
  3584. sfree(message);
  3585. message = msg2;
  3586. }
  3587. logeventf(ssh, "Cancelling %s", message);
  3588. sfree(message);
  3589. /* epf->remote or epf->local may be NULL if setting up a
  3590. * forwarding failed. */
  3591. if (epf->remote) {
  3592. struct ssh_rportfwd *rpf = epf->remote;
  3593. PktOut *pktout;
  3594. /*
  3595. * Cancel the port forwarding at the server
  3596. * end.
  3597. */
  3598. if (ssh->version == 1) {
  3599. /*
  3600. * We cannot cancel listening ports on the
  3601. * server side in SSH-1! There's no message
  3602. * to support it. Instead, we simply remove
  3603. * the rportfwd record from the local end
  3604. * so that any connections the server tries
  3605. * to make on it are rejected.
  3606. */
  3607. } else {
  3608. pktout = ssh_bpp_new_pktout(
  3609. ssh->bpp, SSH2_MSG_GLOBAL_REQUEST);
  3610. put_stringz(pktout, "cancel-tcpip-forward");
  3611. put_bool(pktout, 0);/* _don't_ want reply */
  3612. if (epf->saddr) {
  3613. put_stringz(pktout, epf->saddr);
  3614. } else if (conf_get_int(conf, CONF_rport_acceptall)) {
  3615. /* XXX: rport_acceptall may not represent
  3616. * what was used to open the original connection,
  3617. * since it's reconfigurable. */
  3618. put_stringz(pktout, "");
  3619. } else {
  3620. put_stringz(pktout, "localhost");
  3621. }
  3622. put_uint32(pktout, epf->sport);
  3623. ssh2_pkt_send(ssh, pktout);
  3624. }
  3625. del234(ssh->rportfwds, rpf);
  3626. free_rportfwd(rpf);
  3627. } else if (epf->local) {
  3628. pfl_terminate(epf->local);
  3629. }
  3630. delpos234(ssh->portfwds, i);
  3631. free_portfwd(epf);
  3632. i--; /* so we don't skip one in the list */
  3633. }
  3634. /*
  3635. * And finally, set up any new port forwardings (status==CREATE).
  3636. */
  3637. for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
  3638. if (epf->status == CREATE) {
  3639. char *sportdesc, *dportdesc;
  3640. sportdesc = dupprintf("%s%s%s%s%d%s",
  3641. epf->saddr ? epf->saddr : "",
  3642. epf->saddr ? ":" : "",
  3643. epf->sserv ? epf->sserv : "",
  3644. epf->sserv ? "(" : "",
  3645. epf->sport,
  3646. epf->sserv ? ")" : "");
  3647. if (epf->type == 'D') {
  3648. dportdesc = NULL;
  3649. } else {
  3650. dportdesc = dupprintf("%s:%s%s%d%s",
  3651. epf->daddr,
  3652. epf->dserv ? epf->dserv : "",
  3653. epf->dserv ? "(" : "",
  3654. epf->dport,
  3655. epf->dserv ? ")" : "");
  3656. }
  3657. if (epf->type == 'L') {
  3658. char *err = pfl_listen(epf->daddr, epf->dport,
  3659. epf->saddr, epf->sport,
  3660. ssh, conf, &epf->local,
  3661. epf->addressfamily);
  3662. logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
  3663. epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
  3664. epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
  3665. sportdesc, dportdesc,
  3666. err ? " failed: " : "", err ? err : "");
  3667. if (err)
  3668. sfree(err);
  3669. } else if (epf->type == 'D') {
  3670. char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
  3671. ssh, conf, &epf->local,
  3672. epf->addressfamily);
  3673. logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
  3674. epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
  3675. epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
  3676. sportdesc,
  3677. err ? " failed: " : "", err ? err : "");
  3678. if (err)
  3679. sfree(err);
  3680. } else {
  3681. struct ssh_rportfwd *pf;
  3682. /*
  3683. * Ensure the remote port forwardings tree exists.
  3684. */
  3685. if (!ssh->rportfwds) {
  3686. if (ssh->version == 1)
  3687. ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
  3688. else
  3689. ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
  3690. }
  3691. pf = snew(struct ssh_rportfwd);
  3692. pf->share_ctx = NULL;
  3693. pf->dhost = dupstr(epf->daddr);
  3694. pf->dport = epf->dport;
  3695. if (epf->saddr) {
  3696. pf->shost = dupstr(epf->saddr);
  3697. } else if (conf_get_int(conf, CONF_rport_acceptall)) {
  3698. pf->shost = dupstr("");
  3699. } else {
  3700. pf->shost = dupstr("localhost");
  3701. }
  3702. pf->sport = epf->sport;
  3703. if (add234(ssh->rportfwds, pf) != pf) {
  3704. logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
  3705. epf->daddr, epf->dport);
  3706. sfree(pf);
  3707. } else {
  3708. PktOut *pktout;
  3709. logeventf(ssh, "Requesting remote port %s"
  3710. " forward to %s", sportdesc, dportdesc);
  3711. pf->sportdesc = sportdesc;
  3712. sportdesc = NULL;
  3713. epf->remote = pf;
  3714. pf->pfrec = epf;
  3715. if (ssh->version == 1) {
  3716. pktout = ssh_bpp_new_pktout(
  3717. ssh->bpp, SSH1_CMSG_PORT_FORWARD_REQUEST);
  3718. put_uint32(pktout, epf->sport);
  3719. put_stringz(pktout, epf->daddr);
  3720. put_uint32(pktout, epf->dport);
  3721. ssh_pkt_write(ssh, pktout);
  3722. ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
  3723. SSH1_SMSG_FAILURE,
  3724. ssh_rportfwd_succfail, pf);
  3725. } else {
  3726. pktout = ssh_bpp_new_pktout(
  3727. ssh->bpp, SSH2_MSG_GLOBAL_REQUEST);
  3728. put_stringz(pktout, "tcpip-forward");
  3729. put_bool(pktout, 1);/* want reply */
  3730. put_stringz(pktout, pf->shost);
  3731. put_uint32(pktout, pf->sport);
  3732. ssh2_pkt_send(ssh, pktout);
  3733. ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
  3734. SSH2_MSG_REQUEST_FAILURE,
  3735. ssh_rportfwd_succfail, pf);
  3736. }
  3737. }
  3738. }
  3739. sfree(sportdesc);
  3740. sfree(dportdesc);
  3741. }
  3742. }
  3743. static void ssh1_smsg_stdout_stderr_data(Ssh ssh, PktIn *pktin)
  3744. {
  3745. ptrlen string;
  3746. int bufsize;
  3747. string = get_string(pktin);
  3748. if (get_err(pktin)) {
  3749. bombout(("Incoming terminal data packet was badly formed"));
  3750. return;
  3751. }
  3752. bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
  3753. string.ptr, string.len);
  3754. if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
  3755. ssh->v1_stdout_throttling = 1;
  3756. ssh_throttle_conn(ssh, +1);
  3757. }
  3758. }
  3759. static void ssh1_smsg_x11_open(Ssh ssh, PktIn *pktin)
  3760. {
  3761. /* Remote side is trying to open a channel to talk to our
  3762. * X-Server. Give them back a local channel number. */
  3763. struct ssh_channel *c;
  3764. PktOut *pkt;
  3765. int remoteid = get_uint32(pktin);
  3766. logevent("Received X11 connect request");
  3767. /* Refuse if X11 forwarding is disabled. */
  3768. if (!ssh->X11_fwd_enabled) {
  3769. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_MSG_CHANNEL_OPEN_FAILURE);
  3770. put_uint32(pkt, remoteid);
  3771. ssh_pkt_write(ssh, pkt);
  3772. logevent("Rejected X11 connect request");
  3773. } else {
  3774. c = snew(struct ssh_channel);
  3775. c->ssh = ssh;
  3776. ssh_channel_init(c);
  3777. c->chan = x11_new_channel(ssh->x11authtree, c, NULL, -1, FALSE);
  3778. c->remoteid = remoteid;
  3779. c->halfopen = FALSE;
  3780. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
  3781. put_uint32(pkt, c->remoteid);
  3782. put_uint32(pkt, c->localid);
  3783. ssh_pkt_write(ssh, pkt);
  3784. logevent("Opened X11 forward channel");
  3785. }
  3786. }
  3787. static void ssh1_smsg_agent_open(Ssh ssh, PktIn *pktin)
  3788. {
  3789. /* Remote side is trying to open a channel to talk to our
  3790. * agent. Give them back a local channel number. */
  3791. struct ssh_channel *c;
  3792. PktOut *pkt;
  3793. int remoteid = toint(get_uint32(pktin));
  3794. /* Refuse if agent forwarding is disabled. */
  3795. if (!ssh->agentfwd_enabled) {
  3796. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_MSG_CHANNEL_OPEN_FAILURE);
  3797. put_uint32(pkt, remoteid);
  3798. ssh_pkt_write(ssh, pkt);
  3799. } else {
  3800. c = snew(struct ssh_channel);
  3801. c->ssh = ssh;
  3802. ssh_channel_init(c);
  3803. c->remoteid = remoteid;
  3804. c->halfopen = FALSE;
  3805. c->chan = agentf_new(c);
  3806. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
  3807. put_uint32(pkt, c->remoteid);
  3808. put_uint32(pkt, c->localid);
  3809. ssh_pkt_write(ssh, pkt);
  3810. }
  3811. }
  3812. static void ssh1_msg_port_open(Ssh ssh, PktIn *pktin)
  3813. {
  3814. /* Remote side is trying to open a channel to talk to a
  3815. * forwarded port. Give them back a local channel number. */
  3816. struct ssh_rportfwd pf, *pfp;
  3817. PktOut *pkt;
  3818. int remoteid;
  3819. int port;
  3820. ptrlen host;
  3821. char *err;
  3822. remoteid = toint(get_uint32(pktin));
  3823. host = get_string(pktin);
  3824. port = toint(get_uint32(pktin));
  3825. pf.dhost = mkstr(host);
  3826. pf.dport = port;
  3827. pfp = find234(ssh->rportfwds, &pf, NULL);
  3828. if (pfp == NULL) {
  3829. logeventf(ssh, "Rejected remote port open request for %s:%d",
  3830. pf.dhost, port);
  3831. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_MSG_CHANNEL_OPEN_FAILURE);
  3832. put_uint32(pkt, remoteid);
  3833. ssh_pkt_write(ssh, pkt);
  3834. } else {
  3835. struct ssh_channel *c = snew(struct ssh_channel);
  3836. c->ssh = ssh;
  3837. logeventf(ssh, "Received remote port open request for %s:%d",
  3838. pf.dhost, port);
  3839. err = pfd_connect(&c->chan, pf.dhost, port,
  3840. c, ssh->conf, pfp->pfrec->addressfamily);
  3841. if (err != NULL) {
  3842. logeventf(ssh, "Port open failed: %s", err);
  3843. sfree(err);
  3844. sfree(c);
  3845. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_MSG_CHANNEL_OPEN_FAILURE);
  3846. put_uint32(pkt, remoteid);
  3847. ssh_pkt_write(ssh, pkt);
  3848. } else {
  3849. ssh_channel_init(c);
  3850. c->remoteid = remoteid;
  3851. c->halfopen = FALSE;
  3852. pkt = ssh_bpp_new_pktout(
  3853. ssh->bpp, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
  3854. put_uint32(pkt, c->remoteid);
  3855. put_uint32(pkt, c->localid);
  3856. ssh_pkt_write(ssh, pkt);
  3857. logevent("Forwarded port opened successfully");
  3858. }
  3859. }
  3860. sfree(pf.dhost);
  3861. }
  3862. static void ssh1_msg_channel_open_confirmation(Ssh ssh, PktIn *pktin)
  3863. {
  3864. struct ssh_channel *c;
  3865. c = ssh_channel_msg(ssh, pktin);
  3866. chan_open_confirmation(c->chan);
  3867. c->remoteid = get_uint32(pktin);
  3868. c->halfopen = FALSE;
  3869. c->throttling_conn = 0;
  3870. if (c && c->pending_eof) {
  3871. /*
  3872. * We have a pending close on this channel,
  3873. * which we decided on before the server acked
  3874. * the channel open. So now we know the
  3875. * remoteid, we can close it again.
  3876. */
  3877. ssh_channel_try_eof(c);
  3878. }
  3879. }
  3880. static void ssh1_msg_channel_open_failure(Ssh ssh, PktIn *pktin)
  3881. {
  3882. struct ssh_channel *c;
  3883. c = ssh_channel_msg(ssh, pktin);
  3884. chan_open_failed(c->chan, NULL);
  3885. chan_free(c->chan);
  3886. del234(ssh->channels, c);
  3887. sfree(c);
  3888. }
  3889. static void ssh1_msg_channel_close(Ssh ssh, PktIn *pktin)
  3890. {
  3891. /* Remote side closes a channel. */
  3892. struct ssh_channel *c;
  3893. c = ssh_channel_msg(ssh, pktin);
  3894. if (c) {
  3895. if (pktin->type == SSH1_MSG_CHANNEL_CLOSE) {
  3896. /*
  3897. * Received CHANNEL_CLOSE, which we translate into
  3898. * outgoing EOF.
  3899. */
  3900. ssh_channel_got_eof(c);
  3901. }
  3902. if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
  3903. !(c->closes & CLOSES_RCVD_CLOSE)) {
  3904. if (!(c->closes & CLOSES_SENT_EOF)) {
  3905. bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %u"
  3906. " for which we never sent CHANNEL_CLOSE\n",
  3907. c->localid));
  3908. }
  3909. c->closes |= CLOSES_RCVD_CLOSE;
  3910. }
  3911. if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
  3912. !(c->closes & CLOSES_SENT_CLOSE)) {
  3913. PktOut *pkt = ssh_bpp_new_pktout(
  3914. ssh->bpp, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
  3915. put_uint32(pkt, c->remoteid);
  3916. ssh_pkt_write(ssh, pkt);
  3917. c->closes |= CLOSES_SENT_CLOSE;
  3918. }
  3919. if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
  3920. ssh_channel_destroy(c);
  3921. }
  3922. }
  3923. static int ssh_channel_data(struct ssh_channel *c, int is_stderr,
  3924. const void *data, int length)
  3925. {
  3926. if (c->chan)
  3927. chan_send(c->chan, is_stderr, data, length);
  3928. return 0;
  3929. }
  3930. static void ssh1_msg_channel_data(Ssh ssh, PktIn *pktin)
  3931. {
  3932. /* Data sent down one of our channels. */
  3933. ptrlen data;
  3934. struct ssh_channel *c;
  3935. c = ssh_channel_msg(ssh, pktin);
  3936. data = get_string(pktin);
  3937. if (c) {
  3938. int bufsize = ssh_channel_data(c, FALSE, data.ptr, data.len);
  3939. if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
  3940. c->throttling_conn = 1;
  3941. ssh_throttle_conn(ssh, +1);
  3942. }
  3943. }
  3944. }
  3945. static void ssh1_smsg_exit_status(Ssh ssh, PktIn *pktin)
  3946. {
  3947. PktOut *pkt;
  3948. ssh->exitcode = get_uint32(pktin);
  3949. logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
  3950. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_EXIT_CONFIRMATION);
  3951. ssh_pkt_write(ssh, pkt);
  3952. /*
  3953. * In case `helpful' firewalls or proxies tack
  3954. * extra human-readable text on the end of the
  3955. * session which we might mistake for another
  3956. * encrypted packet, we close the session once
  3957. * we've sent EXIT_CONFIRMATION.
  3958. */
  3959. ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
  3960. }
  3961. /* Helper function to deal with sending tty modes for REQUEST_PTY */
  3962. static void ssh1_send_ttymode(BinarySink *bs,
  3963. const struct ssh_ttymode *mode, char *val)
  3964. {
  3965. put_byte(bs, mode->opcode);
  3966. switch (mode->type) {
  3967. case TTY_OP_CHAR:
  3968. put_byte(bs, ssh_tty_parse_specchar(val));
  3969. break;
  3970. case TTY_OP_BOOL:
  3971. put_byte(bs, ssh_tty_parse_boolean(val));
  3972. break;
  3973. }
  3974. }
  3975. int ssh_agent_forwarding_permitted(Ssh ssh)
  3976. {
  3977. return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
  3978. }
  3979. static void do_ssh1_connection(void *vctx)
  3980. {
  3981. Ssh ssh = (Ssh)vctx;
  3982. PktIn *pktin;
  3983. PktOut *pkt;
  3984. crBegin(ssh->do_ssh1_connection_crstate);
  3985. ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
  3986. ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
  3987. ssh1_smsg_stdout_stderr_data;
  3988. ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
  3989. ssh1_msg_channel_open_confirmation;
  3990. ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
  3991. ssh1_msg_channel_open_failure;
  3992. ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
  3993. ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
  3994. ssh1_msg_channel_close;
  3995. ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
  3996. ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
  3997. if (ssh_agent_forwarding_permitted(ssh)) {
  3998. logevent("Requesting agent forwarding");
  3999. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_AGENT_REQUEST_FORWARDING);
  4000. ssh_pkt_write(ssh, pkt);
  4001. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_connection)) != NULL);
  4002. if (pktin->type != SSH1_SMSG_SUCCESS
  4003. && pktin->type != SSH1_SMSG_FAILURE) {
  4004. bombout(("Protocol confusion"));
  4005. crStopV;
  4006. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  4007. logevent("Agent forwarding refused");
  4008. } else {
  4009. logevent("Agent forwarding enabled");
  4010. ssh->agentfwd_enabled = TRUE;
  4011. ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
  4012. }
  4013. }
  4014. if (conf_get_int(ssh->conf, CONF_x11_forward)) {
  4015. ssh->x11disp =
  4016. x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
  4017. ssh->conf);
  4018. if (!ssh->x11disp) {
  4019. /* FIXME: return an error message from x11_setup_display */
  4020. logevent("X11 forwarding not enabled: unable to"
  4021. " initialise X display");
  4022. } else {
  4023. ssh->x11auth = x11_invent_fake_auth
  4024. (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
  4025. ssh->x11auth->disp = ssh->x11disp;
  4026. logevent("Requesting X11 forwarding");
  4027. pkt = ssh_bpp_new_pktout(
  4028. ssh->bpp, SSH1_CMSG_X11_REQUEST_FORWARDING);
  4029. put_stringz(pkt, ssh->x11auth->protoname);
  4030. put_stringz(pkt, ssh->x11auth->datastring);
  4031. if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER)
  4032. put_uint32(pkt, ssh->x11disp->screennum);
  4033. ssh_pkt_write(ssh, pkt);
  4034. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_connection))
  4035. != NULL);
  4036. if (pktin->type != SSH1_SMSG_SUCCESS
  4037. && pktin->type != SSH1_SMSG_FAILURE) {
  4038. bombout(("Protocol confusion"));
  4039. crStopV;
  4040. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  4041. logevent("X11 forwarding refused");
  4042. } else {
  4043. logevent("X11 forwarding enabled");
  4044. ssh->X11_fwd_enabled = TRUE;
  4045. ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
  4046. }
  4047. }
  4048. }
  4049. ssh_setup_portfwd(ssh, ssh->conf);
  4050. ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
  4051. if (!conf_get_int(ssh->conf, CONF_nopty)) {
  4052. PktOut *pkt;
  4053. /* Unpick the terminal-speed string. */
  4054. /* XXX perhaps we should allow no speeds to be sent. */
  4055. ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
  4056. sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
  4057. /* Send the pty request. */
  4058. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_REQUEST_PTY);
  4059. put_stringz(pkt, conf_get_str(ssh->conf, CONF_termtype));
  4060. put_uint32(pkt, ssh->term_height);
  4061. put_uint32(pkt, ssh->term_width);
  4062. put_uint32(pkt, 0); /* width in pixels */
  4063. put_uint32(pkt, 0); /* height in pixels */
  4064. parse_ttymodes(BinarySink_UPCAST(pkt), ssh, ssh1_send_ttymode);
  4065. put_byte(pkt, SSH1_TTY_OP_ISPEED);
  4066. put_uint32(pkt, ssh->ispeed);
  4067. put_byte(pkt, SSH1_TTY_OP_OSPEED);
  4068. put_uint32(pkt, ssh->ospeed);
  4069. put_byte(pkt, SSH_TTY_OP_END);
  4070. ssh_pkt_write(ssh, pkt);
  4071. ssh->state = SSH_STATE_INTERMED;
  4072. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_connection)) != NULL);
  4073. if (pktin->type != SSH1_SMSG_SUCCESS
  4074. && pktin->type != SSH1_SMSG_FAILURE) {
  4075. bombout(("Protocol confusion"));
  4076. crStopV;
  4077. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  4078. c_write_str(ssh, "Server refused to allocate pty\r\n");
  4079. ssh->editing = ssh->echoing = 1;
  4080. } else {
  4081. logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
  4082. ssh->ospeed, ssh->ispeed);
  4083. ssh->got_pty = TRUE;
  4084. }
  4085. } else {
  4086. ssh->editing = ssh->echoing = 1;
  4087. }
  4088. if (conf_get_int(ssh->conf, CONF_compression)) {
  4089. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_REQUEST_COMPRESSION);
  4090. put_uint32(pkt, 6); /* gzip compression level */
  4091. ssh_pkt_write(ssh, pkt);
  4092. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh1_connection)) != NULL);
  4093. if (pktin->type != SSH1_SMSG_SUCCESS
  4094. && pktin->type != SSH1_SMSG_FAILURE) {
  4095. bombout(("Protocol confusion"));
  4096. crStopV;
  4097. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  4098. c_write_str(ssh, "Server refused to compress\r\n");
  4099. }
  4100. logevent("Started zlib (RFC1950) compression");
  4101. ssh1_bpp_start_compression(ssh->bpp);
  4102. }
  4103. /*
  4104. * Start the shell or command.
  4105. *
  4106. * Special case: if the first-choice command is an SSH-2
  4107. * subsystem (hence not usable here) and the second choice
  4108. * exists, we fall straight back to that.
  4109. */
  4110. {
  4111. char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
  4112. if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
  4113. conf_get_str(ssh->conf, CONF_remote_cmd2)) {
  4114. cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
  4115. ssh->fallback_cmd = TRUE;
  4116. }
  4117. if (*cmd) {
  4118. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_EXEC_CMD);
  4119. put_stringz(pkt, cmd);
  4120. ssh_pkt_write(ssh, pkt);
  4121. } else {
  4122. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_EXEC_SHELL);
  4123. ssh_pkt_write(ssh, pkt);
  4124. }
  4125. logevent("Started session");
  4126. }
  4127. ssh->state = SSH_STATE_SESSION;
  4128. if (ssh->size_needed)
  4129. backend_size(&ssh->backend, ssh->term_width, ssh->term_height);
  4130. if (ssh->eof_needed)
  4131. backend_special(&ssh->backend, TS_EOF);
  4132. if (ssh->ldisc)
  4133. ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
  4134. ssh->send_ok = 1;
  4135. ssh->channels = newtree234(ssh_channelcmp);
  4136. while (1) {
  4137. /*
  4138. * By this point, most incoming packets are already being
  4139. * handled by the dispatch table, and we need only pay
  4140. * attention to the unusual ones.
  4141. */
  4142. while ((pktin = pq_pop(&ssh->pq_ssh1_connection)) != NULL) {
  4143. if (pktin->type == SSH1_SMSG_SUCCESS) {
  4144. /* may be from EXEC_SHELL on some servers */
  4145. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  4146. /* may be from EXEC_SHELL on some servers
  4147. * if no pty is available or in other odd cases. Ignore */
  4148. } else {
  4149. bombout(("Strange packet received: type %d", pktin->type));
  4150. crStopV;
  4151. }
  4152. }
  4153. while (bufchain_size(&ssh->user_input) > 0) {
  4154. void *data;
  4155. int len;
  4156. bufchain_prefix(&ssh->user_input, &data, &len);
  4157. if (len > 512)
  4158. len = 512;
  4159. pkt = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_STDIN_DATA);
  4160. put_string(pkt, data, len);
  4161. ssh_pkt_write(ssh, pkt);
  4162. bufchain_consume(&ssh->user_input, len);
  4163. }
  4164. crReturnV;
  4165. }
  4166. crFinishV;
  4167. }
  4168. /*
  4169. * Handle the top-level SSH-2 protocol.
  4170. */
  4171. static void ssh1_msg_debug(Ssh ssh, PktIn *pktin)
  4172. {
  4173. ptrlen msg = get_string(pktin);
  4174. logeventf(ssh, "Remote debug message: %.*s", PTRLEN_PRINTF(msg));
  4175. }
  4176. static void ssh1_msg_disconnect(Ssh ssh, PktIn *pktin)
  4177. {
  4178. ptrlen msg = get_string(pktin);
  4179. bombout(("Server sent disconnect message:\n\"%.*s\"", PTRLEN_PRINTF(msg)));
  4180. }
  4181. static void ssh_msg_ignore(Ssh ssh, PktIn *pktin)
  4182. {
  4183. /* Do nothing, because we're ignoring it! Duhh. */
  4184. }
  4185. static void ssh1_login_input(Ssh ssh)
  4186. {
  4187. do_ssh1_login(ssh);
  4188. }
  4189. static void ssh1_connection_input(Ssh ssh)
  4190. {
  4191. do_ssh1_connection(ssh);
  4192. }
  4193. static void ssh1_coro_wrapper_initial(Ssh ssh, PktIn *pktin)
  4194. {
  4195. pktin->refcount++; /* avoid packet being freed when we return */
  4196. pq_push(&ssh->pq_ssh1_login, pktin);
  4197. queue_idempotent_callback(&ssh->ssh1_login_icb);
  4198. }
  4199. static void ssh1_coro_wrapper_session(Ssh ssh, PktIn *pktin)
  4200. {
  4201. pktin->refcount++; /* avoid packet being freed when we return */
  4202. pq_push(&ssh->pq_ssh1_connection, pktin);
  4203. queue_idempotent_callback(&ssh->ssh1_connection_icb);
  4204. }
  4205. static void ssh1_protocol_setup(Ssh ssh)
  4206. {
  4207. int i;
  4208. ssh->bpp = ssh1_bpp_new();
  4209. /*
  4210. * Most messages are handled by the main protocol routine.
  4211. */
  4212. for (i = 0; i < SSH_MAX_MSG; i++)
  4213. ssh->packet_dispatch[i] = ssh1_coro_wrapper_initial;
  4214. /*
  4215. * These special message types we install handlers for.
  4216. */
  4217. ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
  4218. ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
  4219. ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
  4220. }
  4221. /*
  4222. * Utility routines for decoding comma-separated strings in KEXINIT.
  4223. */
  4224. static int first_in_commasep_string(char const *needle, char const *haystack,
  4225. int haylen)
  4226. {
  4227. int needlen;
  4228. if (!needle || !haystack) /* protect against null pointers */
  4229. return 0;
  4230. needlen = strlen(needle);
  4231. if (haylen >= needlen && /* haystack is long enough */
  4232. !memcmp(needle, haystack, needlen) && /* initial match */
  4233. (haylen == needlen || haystack[needlen] == ',')
  4234. /* either , or EOS follows */
  4235. )
  4236. return 1;
  4237. return 0;
  4238. }
  4239. static int in_commasep_string(char const *needle, char const *haystack,
  4240. int haylen)
  4241. {
  4242. char *p;
  4243. if (!needle || !haystack) /* protect against null pointers */
  4244. return 0;
  4245. /*
  4246. * Is it at the start of the string?
  4247. */
  4248. if (first_in_commasep_string(needle, haystack, haylen))
  4249. return 1;
  4250. /*
  4251. * If not, search for the next comma and resume after that.
  4252. * If no comma found, terminate.
  4253. */
  4254. p = memchr(haystack, ',', haylen);
  4255. if (!p) return 0;
  4256. /* + 1 to skip over comma */
  4257. return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
  4258. }
  4259. /*
  4260. * Add a value to a strbuf containing a comma-separated list.
  4261. */
  4262. static void add_to_commasep(strbuf *buf, const char *data)
  4263. {
  4264. if (buf->len > 0)
  4265. put_byte(buf, ',');
  4266. put_data(buf, data, strlen(data));
  4267. }
  4268. /*
  4269. * SSH-2 key derivation (RFC 4253 section 7.2).
  4270. */
  4271. static void ssh2_mkkey(Ssh ssh, strbuf *out, Bignum K, unsigned char *H,
  4272. char chr, int keylen)
  4273. {
  4274. const struct ssh_hash *h = ssh->kex->hash;
  4275. int keylen_padded;
  4276. unsigned char *key;
  4277. void *s, *s2;
  4278. BinarySink *bs;
  4279. if (keylen == 0)
  4280. return;
  4281. /*
  4282. * Round the requested amount of key material up to a multiple of
  4283. * the length of the hash we're using to make it. This makes life
  4284. * simpler because then we can just write each hash output block
  4285. * straight into the output buffer without fiddling about
  4286. * truncating the last one. Since it's going into a strbuf, and
  4287. * strbufs are always smemclr()ed on free, there's no need to
  4288. * worry about leaving extra potentially-sensitive data in memory
  4289. * that the caller didn't ask for.
  4290. */
  4291. keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
  4292. out->len = 0;
  4293. key = strbuf_append(out, keylen_padded);
  4294. /* First hlen bytes. */
  4295. s = h->init();
  4296. bs = h->sink(s);
  4297. if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
  4298. put_mp_ssh2(bs, K);
  4299. put_data(bs, H, h->hlen);
  4300. put_byte(bs, chr);
  4301. put_data(bs, ssh->v2_session_id, ssh->v2_session_id_len);
  4302. h->final(s, key);
  4303. /* Subsequent blocks of hlen bytes. */
  4304. if (keylen_padded > h->hlen) {
  4305. int offset;
  4306. s = h->init();
  4307. bs = h->sink(s);
  4308. if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
  4309. put_mp_ssh2(bs, K);
  4310. put_data(bs, H, h->hlen);
  4311. for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
  4312. put_data(bs, key + offset - h->hlen, h->hlen);
  4313. s2 = h->copy(s);
  4314. h->final(s2, key + offset);
  4315. }
  4316. h->free(s);
  4317. }
  4318. }
  4319. /*
  4320. * Structure for constructing KEXINIT algorithm lists.
  4321. */
  4322. #define MAXKEXLIST 16
  4323. struct kexinit_algorithm {
  4324. const char *name;
  4325. union {
  4326. struct {
  4327. const struct ssh_kex *kex;
  4328. int warn;
  4329. } kex;
  4330. struct {
  4331. const ssh_keyalg *hostkey;
  4332. int warn;
  4333. } hk;
  4334. struct {
  4335. const struct ssh2_cipher *cipher;
  4336. int warn;
  4337. } cipher;
  4338. struct {
  4339. const struct ssh_mac *mac;
  4340. int etm;
  4341. } mac;
  4342. const struct ssh_compress *comp;
  4343. } u;
  4344. };
  4345. /*
  4346. * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
  4347. * If the algorithm is already in the list, return a pointer to its
  4348. * entry, otherwise return an entry from the end of the list.
  4349. * This assumes that every time a particular name is passed in, it
  4350. * comes from the same string constant. If this isn't true, this
  4351. * function may need to be rewritten to use strcmp() instead.
  4352. */
  4353. static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
  4354. *list, const char *name)
  4355. {
  4356. int i;
  4357. for (i = 0; i < MAXKEXLIST; i++)
  4358. if (list[i].name == NULL || list[i].name == name) {
  4359. list[i].name = name;
  4360. return &list[i];
  4361. }
  4362. assert(!"No space in KEXINIT list");
  4363. return NULL;
  4364. }
  4365. #ifndef NO_GSSAPI
  4366. /*
  4367. * Data structure managing host keys in sessions based on GSSAPI KEX.
  4368. *
  4369. * In a session we started with a GSSAPI key exchange, the concept of
  4370. * 'host key' has completely different lifetime and security semantics
  4371. * from the usual ones. Per RFC 4462 section 2.1, we assume that any
  4372. * host key delivered to us in the course of a GSSAPI key exchange is
  4373. * _solely_ there to use as a transient fallback within the same
  4374. * session, if at the time of a subsequent rekey the GSS credentials
  4375. * are temporarily invalid and so a non-GSS KEX method has to be used.
  4376. *
  4377. * In particular, in a GSS-based SSH deployment, host keys may not
  4378. * even _be_ persistent identities for the server; it would be
  4379. * legitimate for a server to generate a fresh one routinely if it
  4380. * wanted to, like SSH-1 server keys.
  4381. *
  4382. * So, in this mode, we never touch the persistent host key cache at
  4383. * all, either to check keys against it _or_ to store keys in it.
  4384. * Instead, we maintain an in-memory cache of host keys that have been
  4385. * mentioned in GSS key exchanges within this particular session, and
  4386. * we permit precisely those host keys in non-GSS rekeys.
  4387. */
  4388. struct ssh_transient_hostkey_cache_entry {
  4389. const ssh_keyalg *alg;
  4390. strbuf *pub_blob;
  4391. };
  4392. static int ssh_transient_hostkey_cache_cmp(void *av, void *bv)
  4393. {
  4394. const struct ssh_transient_hostkey_cache_entry
  4395. *a = (const struct ssh_transient_hostkey_cache_entry *)av,
  4396. *b = (const struct ssh_transient_hostkey_cache_entry *)bv;
  4397. return strcmp(a->alg->ssh_id, b->alg->ssh_id);
  4398. }
  4399. static int ssh_transient_hostkey_cache_find(void *av, void *bv)
  4400. {
  4401. const ssh_keyalg *aalg = (const ssh_keyalg *)av;
  4402. const struct ssh_transient_hostkey_cache_entry
  4403. *b = (const struct ssh_transient_hostkey_cache_entry *)bv;
  4404. return strcmp(aalg->ssh_id, b->alg->ssh_id);
  4405. }
  4406. static void ssh_init_transient_hostkey_store(Ssh ssh)
  4407. {
  4408. ssh->transient_hostkey_cache =
  4409. newtree234(ssh_transient_hostkey_cache_cmp);
  4410. }
  4411. static void ssh_cleanup_transient_hostkey_store(Ssh ssh)
  4412. {
  4413. struct ssh_transient_hostkey_cache_entry *ent;
  4414. while ((ent = delpos234(ssh->transient_hostkey_cache, 0)) != NULL) {
  4415. strbuf_free(ent->pub_blob);
  4416. sfree(ent);
  4417. }
  4418. freetree234(ssh->transient_hostkey_cache);
  4419. }
  4420. static void ssh_store_transient_hostkey(Ssh ssh, ssh_key *key)
  4421. {
  4422. struct ssh_transient_hostkey_cache_entry *ent, *retd;
  4423. if ((ent = find234(ssh->transient_hostkey_cache, (void *)ssh_key_alg(key),
  4424. ssh_transient_hostkey_cache_find)) != NULL) {
  4425. strbuf_free(ent->pub_blob);
  4426. sfree(ent);
  4427. }
  4428. ent = snew(struct ssh_transient_hostkey_cache_entry);
  4429. ent->alg = ssh_key_alg(key);
  4430. ent->pub_blob = strbuf_new();
  4431. ssh_key_public_blob(key, BinarySink_UPCAST(ent->pub_blob));
  4432. retd = add234(ssh->transient_hostkey_cache, ent);
  4433. assert(retd == ent);
  4434. }
  4435. static int ssh_verify_transient_hostkey(Ssh ssh, ssh_key *key)
  4436. {
  4437. struct ssh_transient_hostkey_cache_entry *ent;
  4438. int toret = FALSE;
  4439. if ((ent = find234(ssh->transient_hostkey_cache, (void *)ssh_key_alg(key),
  4440. ssh_transient_hostkey_cache_find)) != NULL) {
  4441. strbuf *this_blob = strbuf_new();
  4442. ssh_key_public_blob(key, BinarySink_UPCAST(this_blob));
  4443. if (this_blob->len == ent->pub_blob->len &&
  4444. !memcmp(this_blob->s, ent->pub_blob->s,
  4445. this_blob->len))
  4446. toret = TRUE;
  4447. strbuf_free(this_blob);
  4448. }
  4449. return toret;
  4450. }
  4451. static int ssh_have_transient_hostkey(Ssh ssh, const ssh_keyalg *alg)
  4452. {
  4453. struct ssh_transient_hostkey_cache_entry *ent =
  4454. find234(ssh->transient_hostkey_cache, (void *)alg,
  4455. ssh_transient_hostkey_cache_find);
  4456. return ent != NULL;
  4457. }
  4458. static int ssh_have_any_transient_hostkey(Ssh ssh)
  4459. {
  4460. return count234(ssh->transient_hostkey_cache) > 0;
  4461. }
  4462. #endif /* NO_GSSAPI */
  4463. /*
  4464. * Handle the SSH-2 transport layer.
  4465. */
  4466. static void do_ssh2_transport(void *vctx)
  4467. {
  4468. Ssh ssh = (Ssh)vctx;
  4469. PktIn *pktin;
  4470. enum kexlist {
  4471. KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
  4472. KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
  4473. NKEXLIST
  4474. };
  4475. const char * kexlist_descr[NKEXLIST] = {
  4476. "key exchange algorithm", "host key algorithm",
  4477. "client-to-server cipher", "server-to-client cipher",
  4478. "client-to-server MAC", "server-to-client MAC",
  4479. "client-to-server compression method",
  4480. "server-to-client compression method" };
  4481. struct do_ssh2_transport_state {
  4482. int crLine;
  4483. int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
  4484. Bignum p, g, e, f, K;
  4485. void *our_kexinit;
  4486. int our_kexinitlen;
  4487. int kex_init_value, kex_reply_value;
  4488. const struct ssh_mac *const *maclist;
  4489. int nmacs;
  4490. struct {
  4491. const struct ssh2_cipher *cipher;
  4492. const struct ssh_mac *mac;
  4493. int etm_mode;
  4494. const struct ssh_compress *comp;
  4495. } in, out;
  4496. ptrlen hostkeydata, sigdata;
  4497. char *keystr, *fingerprint;
  4498. ssh_key *hkey; /* actual host key */
  4499. struct RSAKey *rsakey; /* for RSA kex */
  4500. struct ec_key *eckey; /* for ECDH kex */
  4501. unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
  4502. int n_preferred_kex;
  4503. int can_gssapi_keyex;
  4504. int need_gss_transient_hostkey;
  4505. int warned_about_no_gss_transient_hostkey;
  4506. const struct ssh_kexes *preferred_kex[KEX_MAX + 1]; /* +1 for GSSAPI */
  4507. int n_preferred_hk;
  4508. int preferred_hk[HK_MAX];
  4509. int n_preferred_ciphers;
  4510. const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
  4511. const struct ssh_compress *preferred_comp;
  4512. int userauth_succeeded; /* for delayed compression */
  4513. int pending_compression;
  4514. int got_session_id;
  4515. PktOut *pktout;
  4516. int dlgret;
  4517. int guessok;
  4518. int ignorepkt;
  4519. struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
  4520. #ifndef NO_GSSAPI
  4521. Ssh_gss_buf gss_buf;
  4522. Ssh_gss_buf gss_rcvtok, gss_sndtok;
  4523. Ssh_gss_stat gss_stat;
  4524. Ssh_gss_ctx gss_ctx;
  4525. Ssh_gss_buf mic;
  4526. int init_token_sent;
  4527. int complete_rcvd;
  4528. int gss_delegate;
  4529. time_t gss_cred_expiry;
  4530. #endif
  4531. };
  4532. crState(do_ssh2_transport_state);
  4533. assert(!ssh->bare_connection);
  4534. assert(ssh->version == 2);
  4535. crBeginState;
  4536. s->in.cipher = s->out.cipher = NULL;
  4537. s->in.mac = s->out.mac = NULL;
  4538. s->in.comp = s->out.comp = NULL;
  4539. s->got_session_id = FALSE;
  4540. s->userauth_succeeded = FALSE;
  4541. s->pending_compression = FALSE;
  4542. s->need_gss_transient_hostkey = FALSE;
  4543. s->warned_about_no_gss_transient_hostkey = FALSE;
  4544. /*
  4545. * Be prepared to work around the buggy MAC problem.
  4546. */
  4547. if (ssh->remote_bugs & BUG_SSH2_HMAC)
  4548. s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
  4549. else
  4550. s->maclist = macs, s->nmacs = lenof(macs);
  4551. begin_key_exchange:
  4552. #ifndef NO_GSSAPI
  4553. if (s->need_gss_transient_hostkey) {
  4554. /*
  4555. * This flag indicates a special case in which we must not do
  4556. * GSS key exchange even if we could. (See comments below,
  4557. * where the flag was set on the previous key exchange.)
  4558. */
  4559. s->can_gssapi_keyex = FALSE;
  4560. } else if (conf_get_int(ssh->conf, CONF_try_gssapi_kex)) {
  4561. /*
  4562. * We always check if we have GSS creds before we come up with
  4563. * the kex algorithm list, otherwise future rekeys will fail
  4564. * when creds expire. To make this so, this code section must
  4565. * follow the begin_key_exchange label above, otherwise this
  4566. * section would execute just once per-connection.
  4567. *
  4568. * Update GSS state unless the reason we're here is that a
  4569. * timer just checked the GSS state and decided that we should
  4570. * rekey to update delegated credentials. In that case, the
  4571. * state is "fresh".
  4572. */
  4573. if (ssh->rekey_class != RK_GSS_UPDATE)
  4574. ssh2_gss_update(ssh, TRUE);
  4575. /* Do GSSAPI KEX when capable */
  4576. s->can_gssapi_keyex = ssh->gss_status & GSS_KEX_CAPABLE;
  4577. /*
  4578. * But not when failure is likely. [ GSS implementations may
  4579. * attempt (and fail) to use a ticket that is almost expired
  4580. * when retrieved from the ccache that actually expires by the
  4581. * time the server receives it. ]
  4582. *
  4583. * Note: The first time always try KEXGSS if we can, failures
  4584. * will be very rare, and disabling the initial GSS KEX is
  4585. * worse. Some day GSS libraries will ignore cached tickets
  4586. * whose lifetime is critically short, and will instead use
  4587. * fresh ones.
  4588. */
  4589. if (!s->got_session_id && (ssh->gss_status & GSS_CTXT_MAYFAIL) != 0)
  4590. s->can_gssapi_keyex = 0;
  4591. s->gss_delegate = conf_get_int(ssh->conf, CONF_gssapifwd);
  4592. } else {
  4593. s->can_gssapi_keyex = FALSE;
  4594. }
  4595. #endif
  4596. ssh->pls.kctx = SSH2_PKTCTX_NOKEX;
  4597. {
  4598. int i, j, k, warn;
  4599. struct kexinit_algorithm *alg;
  4600. /*
  4601. * Set up the preferred key exchange. (NULL => warn below here)
  4602. */
  4603. s->n_preferred_kex = 0;
  4604. if (s->can_gssapi_keyex)
  4605. s->preferred_kex[s->n_preferred_kex++] = &ssh_gssk5_sha1_kex;
  4606. for (i = 0; i < KEX_MAX; i++) {
  4607. switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
  4608. case KEX_DHGEX:
  4609. s->preferred_kex[s->n_preferred_kex++] =
  4610. &ssh_diffiehellman_gex;
  4611. break;
  4612. case KEX_DHGROUP14:
  4613. s->preferred_kex[s->n_preferred_kex++] =
  4614. &ssh_diffiehellman_group14;
  4615. break;
  4616. case KEX_DHGROUP1:
  4617. s->preferred_kex[s->n_preferred_kex++] =
  4618. &ssh_diffiehellman_group1;
  4619. break;
  4620. case KEX_RSA:
  4621. s->preferred_kex[s->n_preferred_kex++] =
  4622. &ssh_rsa_kex;
  4623. break;
  4624. case KEX_ECDH:
  4625. s->preferred_kex[s->n_preferred_kex++] =
  4626. &ssh_ecdh_kex;
  4627. break;
  4628. case KEX_WARN:
  4629. /* Flag for later. Don't bother if it's the last in
  4630. * the list. */
  4631. if (i < KEX_MAX - 1) {
  4632. s->preferred_kex[s->n_preferred_kex++] = NULL;
  4633. }
  4634. break;
  4635. }
  4636. }
  4637. /*
  4638. * Set up the preferred host key types. These are just the ids
  4639. * in the enum in putty.h, so 'warn below here' is indicated
  4640. * by HK_WARN.
  4641. */
  4642. s->n_preferred_hk = 0;
  4643. for (i = 0; i < HK_MAX; i++) {
  4644. int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
  4645. /* As above, don't bother with HK_WARN if it's last in the
  4646. * list */
  4647. if (id != HK_WARN || i < HK_MAX - 1)
  4648. s->preferred_hk[s->n_preferred_hk++] = id;
  4649. }
  4650. /*
  4651. * Set up the preferred ciphers. (NULL => warn below here)
  4652. */
  4653. s->n_preferred_ciphers = 0;
  4654. for (i = 0; i < CIPHER_MAX; i++) {
  4655. switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
  4656. case CIPHER_BLOWFISH:
  4657. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
  4658. break;
  4659. case CIPHER_DES:
  4660. if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
  4661. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
  4662. }
  4663. break;
  4664. case CIPHER_3DES:
  4665. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
  4666. break;
  4667. case CIPHER_AES:
  4668. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
  4669. break;
  4670. case CIPHER_ARCFOUR:
  4671. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
  4672. break;
  4673. case CIPHER_CHACHA20:
  4674. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
  4675. break;
  4676. case CIPHER_WARN:
  4677. /* Flag for later. Don't bother if it's the last in
  4678. * the list. */
  4679. if (i < CIPHER_MAX - 1) {
  4680. s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
  4681. }
  4682. break;
  4683. }
  4684. }
  4685. /*
  4686. * Set up preferred compression.
  4687. */
  4688. if (conf_get_int(ssh->conf, CONF_compression))
  4689. s->preferred_comp = &ssh_zlib;
  4690. else
  4691. s->preferred_comp = &ssh_comp_none;
  4692. /*
  4693. * Enable queueing of outgoing auth- or connection-layer
  4694. * packets while we are in the middle of a key exchange.
  4695. */
  4696. ssh->queueing = TRUE;
  4697. /*
  4698. * Flag that KEX is in progress.
  4699. */
  4700. ssh->kex_in_progress = TRUE;
  4701. for (i = 0; i < NKEXLIST; i++)
  4702. for (j = 0; j < MAXKEXLIST; j++)
  4703. s->kexlists[i][j].name = NULL;
  4704. /* List key exchange algorithms. */
  4705. warn = FALSE;
  4706. for (i = 0; i < s->n_preferred_kex; i++) {
  4707. const struct ssh_kexes *k = s->preferred_kex[i];
  4708. if (!k) warn = TRUE;
  4709. else for (j = 0; j < k->nkexes; j++) {
  4710. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
  4711. k->list[j]->name);
  4712. alg->u.kex.kex = k->list[j];
  4713. alg->u.kex.warn = warn;
  4714. }
  4715. }
  4716. /* List server host key algorithms. */
  4717. if (!s->got_session_id) {
  4718. /*
  4719. * In the first key exchange, we list all the algorithms
  4720. * we're prepared to cope with, but prefer those algorithms
  4721. * for which we have a host key for this host.
  4722. *
  4723. * If the host key algorithm is below the warning
  4724. * threshold, we warn even if we did already have a key
  4725. * for it, on the basis that if the user has just
  4726. * reconfigured that host key type to be warned about,
  4727. * they surely _do_ want to be alerted that a server
  4728. * they're actually connecting to is using it.
  4729. */
  4730. warn = FALSE;
  4731. for (i = 0; i < s->n_preferred_hk; i++) {
  4732. if (s->preferred_hk[i] == HK_WARN)
  4733. warn = TRUE;
  4734. for (j = 0; j < lenof(hostkey_algs); j++) {
  4735. if (hostkey_algs[j].id != s->preferred_hk[i])
  4736. continue;
  4737. if (have_ssh_host_key(
  4738. #ifdef MPEXT
  4739. ssh->frontend,
  4740. #endif
  4741. ssh->savedhost, ssh->savedport,
  4742. hostkey_algs[j].alg->cache_id)) {
  4743. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  4744. hostkey_algs[j].alg->ssh_id);
  4745. alg->u.hk.hostkey = hostkey_algs[j].alg;
  4746. alg->u.hk.warn = warn;
  4747. }
  4748. }
  4749. }
  4750. warn = FALSE;
  4751. for (i = 0; i < s->n_preferred_hk; i++) {
  4752. if (s->preferred_hk[i] == HK_WARN)
  4753. warn = TRUE;
  4754. for (j = 0; j < lenof(hostkey_algs); j++) {
  4755. if (hostkey_algs[j].id != s->preferred_hk[i])
  4756. continue;
  4757. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  4758. hostkey_algs[j].alg->ssh_id);
  4759. alg->u.hk.hostkey = hostkey_algs[j].alg;
  4760. alg->u.hk.warn = warn;
  4761. }
  4762. }
  4763. #ifndef NO_GSSAPI
  4764. } else if (ssh->gss_kex_used && !s->need_gss_transient_hostkey) {
  4765. /*
  4766. * If we've previously done a GSSAPI KEX, then we list
  4767. * precisely the algorithms for which a previous GSS key
  4768. * exchange has delivered us a host key, because we expect
  4769. * one of exactly those keys to be used in any subsequent
  4770. * non-GSS-based rekey.
  4771. *
  4772. * An exception is if this is the key exchange we
  4773. * triggered for the purposes of populating that cache -
  4774. * in which case the cache will currently be empty, which
  4775. * isn't helpful!
  4776. */
  4777. warn = FALSE;
  4778. for (i = 0; i < s->n_preferred_hk; i++) {
  4779. if (s->preferred_hk[i] == HK_WARN)
  4780. warn = TRUE;
  4781. for (j = 0; j < lenof(hostkey_algs); j++) {
  4782. if (hostkey_algs[j].id != s->preferred_hk[i])
  4783. continue;
  4784. if (ssh_have_transient_hostkey(ssh, hostkey_algs[j].alg)) {
  4785. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  4786. hostkey_algs[j].alg->ssh_id);
  4787. alg->u.hk.hostkey = hostkey_algs[j].alg;
  4788. alg->u.hk.warn = warn;
  4789. }
  4790. }
  4791. }
  4792. #endif
  4793. } else {
  4794. /*
  4795. * In subsequent key exchanges, we list only the kex
  4796. * algorithm that was selected in the first key exchange,
  4797. * so that we keep getting the same host key and hence
  4798. * don't have to interrupt the user's session to ask for
  4799. * reverification.
  4800. */
  4801. assert(ssh->kex);
  4802. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  4803. ssh->hostkey_alg->ssh_id);
  4804. alg->u.hk.hostkey = ssh->hostkey_alg;
  4805. alg->u.hk.warn = FALSE;
  4806. }
  4807. if (s->can_gssapi_keyex) {
  4808. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY], "null");
  4809. alg->u.hk.hostkey = NULL;
  4810. }
  4811. /* List encryption algorithms (client->server then server->client). */
  4812. for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
  4813. warn = FALSE;
  4814. #ifdef FUZZING
  4815. alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
  4816. alg->u.cipher.cipher = NULL;
  4817. alg->u.cipher.warn = warn;
  4818. #endif /* FUZZING */
  4819. for (i = 0; i < s->n_preferred_ciphers; i++) {
  4820. const struct ssh2_ciphers *c = s->preferred_ciphers[i];
  4821. if (!c) warn = TRUE;
  4822. else for (j = 0; j < c->nciphers; j++) {
  4823. alg = ssh2_kexinit_addalg(s->kexlists[k],
  4824. c->list[j]->name);
  4825. alg->u.cipher.cipher = c->list[j];
  4826. alg->u.cipher.warn = warn;
  4827. }
  4828. }
  4829. }
  4830. /* List MAC algorithms (client->server then server->client). */
  4831. for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
  4832. #ifdef FUZZING
  4833. alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
  4834. alg->u.mac.mac = NULL;
  4835. alg->u.mac.etm = FALSE;
  4836. #endif /* FUZZING */
  4837. for (i = 0; i < s->nmacs; i++) {
  4838. alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
  4839. alg->u.mac.mac = s->maclist[i];
  4840. alg->u.mac.etm = FALSE;
  4841. }
  4842. for (i = 0; i < s->nmacs; i++)
  4843. /* For each MAC, there may also be an ETM version,
  4844. * which we list second. */
  4845. if (s->maclist[i]->etm_name) {
  4846. alg = ssh2_kexinit_addalg(s->kexlists[j],
  4847. s->maclist[i]->etm_name);
  4848. alg->u.mac.mac = s->maclist[i];
  4849. alg->u.mac.etm = TRUE;
  4850. }
  4851. }
  4852. /* List client->server compression algorithms,
  4853. * then server->client compression algorithms. (We use the
  4854. * same set twice.) */
  4855. for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
  4856. assert(lenof(compressions) > 1);
  4857. /* Prefer non-delayed versions */
  4858. alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
  4859. alg->u.comp = s->preferred_comp;
  4860. /* We don't even list delayed versions of algorithms until
  4861. * they're allowed to be used, to avoid a race. See the end of
  4862. * this function. */
  4863. if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
  4864. alg = ssh2_kexinit_addalg(s->kexlists[j],
  4865. s->preferred_comp->delayed_name);
  4866. alg->u.comp = s->preferred_comp;
  4867. }
  4868. for (i = 0; i < lenof(compressions); i++) {
  4869. const struct ssh_compress *c = compressions[i];
  4870. alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
  4871. alg->u.comp = c;
  4872. if (s->userauth_succeeded && c->delayed_name) {
  4873. alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
  4874. alg->u.comp = c;
  4875. }
  4876. }
  4877. }
  4878. /*
  4879. * Construct and send our key exchange packet.
  4880. */
  4881. s->pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_KEXINIT);
  4882. for (i = 0; i < 16; i++)
  4883. put_byte(s->pktout, (unsigned char) random_byte());
  4884. for (i = 0; i < NKEXLIST; i++) {
  4885. strbuf *list = strbuf_new();
  4886. for (j = 0; j < MAXKEXLIST; j++) {
  4887. if (s->kexlists[i][j].name == NULL) break;
  4888. add_to_commasep(list, s->kexlists[i][j].name);
  4889. }
  4890. put_stringsb(s->pktout, list);
  4891. }
  4892. /* List client->server languages. Empty list. */
  4893. put_stringz(s->pktout, "");
  4894. /* List server->client languages. Empty list. */
  4895. put_stringz(s->pktout, "");
  4896. /* First KEX packet does _not_ follow, because we're not that brave. */
  4897. put_bool(s->pktout, FALSE);
  4898. /* Reserved. */
  4899. put_uint32(s->pktout, 0);
  4900. }
  4901. s->our_kexinitlen = s->pktout->length - 5;
  4902. s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
  4903. memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
  4904. ssh_pkt_write(ssh, s->pktout);
  4905. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_transport)) != NULL);
  4906. /*
  4907. * Now examine the other side's KEXINIT to see what we're up
  4908. * to.
  4909. */
  4910. {
  4911. ptrlen str;
  4912. int i, j;
  4913. if (pktin->type != SSH2_MSG_KEXINIT) {
  4914. bombout(("expected key exchange packet from server"));
  4915. crStopV;
  4916. }
  4917. ssh->kex = NULL;
  4918. ssh->hostkey_alg = NULL;
  4919. s->in.cipher = s->out.cipher = NULL;
  4920. s->in.mac = s->out.mac = NULL;
  4921. s->in.comp = s->out.comp = NULL;
  4922. s->warn_kex = s->warn_hk = FALSE;
  4923. s->warn_cscipher = s->warn_sccipher = FALSE;
  4924. get_data(pktin, 16); /* skip garbage cookie */
  4925. s->guessok = FALSE;
  4926. for (i = 0; i < NKEXLIST; i++) {
  4927. str = get_string(pktin);
  4928. if (get_err(pktin)) {
  4929. bombout(("KEXINIT packet was incomplete"));
  4930. crStopV;
  4931. }
  4932. /* If we've already selected a cipher which requires a
  4933. * particular MAC, then just select that, and don't even
  4934. * bother looking through the server's KEXINIT string for
  4935. * MACs. */
  4936. if (i == KEXLIST_CSMAC && s->out.cipher &&
  4937. s->out.cipher->required_mac) {
  4938. s->out.mac = s->out.cipher->required_mac;
  4939. s->out.etm_mode = !!(s->out.mac->etm_name);
  4940. goto matched;
  4941. }
  4942. if (i == KEXLIST_SCMAC && s->in.cipher &&
  4943. s->in.cipher->required_mac) {
  4944. s->in.mac = s->in.cipher->required_mac;
  4945. s->in.etm_mode = !!(s->in.mac->etm_name);
  4946. goto matched;
  4947. }
  4948. for (j = 0; j < MAXKEXLIST; j++) {
  4949. struct kexinit_algorithm *alg = &s->kexlists[i][j];
  4950. if (alg->name == NULL) break;
  4951. if (in_commasep_string(alg->name, str.ptr, str.len)) {
  4952. /* We've found a matching algorithm. */
  4953. if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
  4954. /* Check if we might need to ignore first kex pkt */
  4955. if (j != 0 ||
  4956. !first_in_commasep_string(alg->name,
  4957. str.ptr, str.len))
  4958. s->guessok = FALSE;
  4959. }
  4960. if (i == KEXLIST_KEX) {
  4961. ssh->kex = alg->u.kex.kex;
  4962. s->warn_kex = alg->u.kex.warn;
  4963. } else if (i == KEXLIST_HOSTKEY) {
  4964. /*
  4965. * Ignore an unexpected/inappropriate offer of "null",
  4966. * we offer "null" when we're willing to use GSS KEX,
  4967. * but it is only acceptable when GSSKEX is actually
  4968. * selected.
  4969. */
  4970. if (alg->u.hk.hostkey == NULL &&
  4971. ssh->kex->main_type != KEXTYPE_GSS)
  4972. continue;
  4973. ssh->hostkey_alg = alg->u.hk.hostkey;
  4974. s->warn_hk = alg->u.hk.warn;
  4975. } else if (i == KEXLIST_CSCIPHER) {
  4976. s->out.cipher = alg->u.cipher.cipher;
  4977. s->warn_cscipher = alg->u.cipher.warn;
  4978. } else if (i == KEXLIST_SCCIPHER) {
  4979. s->in.cipher = alg->u.cipher.cipher;
  4980. s->warn_sccipher = alg->u.cipher.warn;
  4981. } else if (i == KEXLIST_CSMAC) {
  4982. s->out.mac = alg->u.mac.mac;
  4983. s->out.etm_mode = alg->u.mac.etm;
  4984. } else if (i == KEXLIST_SCMAC) {
  4985. s->in.mac = alg->u.mac.mac;
  4986. s->in.etm_mode = alg->u.mac.etm;
  4987. } else if (i == KEXLIST_CSCOMP) {
  4988. s->out.comp = alg->u.comp;
  4989. } else if (i == KEXLIST_SCCOMP) {
  4990. s->in.comp = alg->u.comp;
  4991. }
  4992. goto matched;
  4993. }
  4994. if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
  4995. in_commasep_string(alg->u.comp->delayed_name,
  4996. str.ptr, str.len) &&
  4997. !s->userauth_succeeded)
  4998. s->pending_compression = TRUE; /* try this later */
  4999. }
  5000. bombout(("Couldn't agree a %s (available: %.*s)",
  5001. kexlist_descr[i], PTRLEN_PRINTF(str)));
  5002. crStopV;
  5003. matched:;
  5004. if (i == KEXLIST_HOSTKEY &&
  5005. !ssh->gss_kex_used &&
  5006. ssh->kex->main_type != KEXTYPE_GSS) {
  5007. int j;
  5008. /*
  5009. * In addition to deciding which host key we're
  5010. * actually going to use, we should make a list of the
  5011. * host keys offered by the server which we _don't_
  5012. * have cached. These will be offered as cross-
  5013. * certification options by ssh_get_specials.
  5014. *
  5015. * We also count the key we're currently using for KEX
  5016. * as one we've already got, because by the time this
  5017. * menu becomes visible, it will be.
  5018. */
  5019. ssh->n_uncert_hostkeys = 0;
  5020. for (j = 0; j < lenof(hostkey_algs); j++) {
  5021. if (hostkey_algs[j].alg != ssh->hostkey_alg &&
  5022. in_commasep_string(hostkey_algs[j].alg->ssh_id,
  5023. str.ptr, str.len) &&
  5024. !have_ssh_host_key(
  5025. #ifdef MPEXT
  5026. ssh->frontend,
  5027. #endif
  5028. ssh->savedhost, ssh->savedport,
  5029. hostkey_algs[j].alg->cache_id)) {
  5030. ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
  5031. }
  5032. }
  5033. }
  5034. }
  5035. if (s->pending_compression) {
  5036. logevent("Server supports delayed compression; "
  5037. "will try this later");
  5038. }
  5039. get_string(pktin); /* client->server language */
  5040. get_string(pktin); /* server->client language */
  5041. s->ignorepkt = get_bool(pktin) && !s->guessok;
  5042. ssh->exhash = ssh->kex->hash->init();
  5043. ssh->exhash_bs = ssh->kex->hash->sink(ssh->exhash);
  5044. put_stringz(ssh->exhash_bs, ssh->v_c);
  5045. put_stringz(ssh->exhash_bs, ssh->v_s);
  5046. put_string(ssh->exhash_bs, s->our_kexinit, s->our_kexinitlen);
  5047. sfree(s->our_kexinit);
  5048. /* Include the type byte in the hash of server's KEXINIT */
  5049. put_string(ssh->exhash_bs,
  5050. (const char *)BinarySource_UPCAST(pktin)->data - 1,
  5051. BinarySource_UPCAST(pktin)->len + 1);
  5052. if (s->warn_kex) {
  5053. ssh_set_frozen(ssh, 1);
  5054. s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
  5055. ssh->kex->name,
  5056. ssh_dialog_callback, ssh);
  5057. if (s->dlgret < 0) {
  5058. ssh->user_response = -1;
  5059. crWaitUntilV(ssh->user_response >= 0);
  5060. s->dlgret = ssh->user_response;
  5061. }
  5062. ssh_set_frozen(ssh, 0);
  5063. if (s->dlgret == 0) {
  5064. ssh_disconnect(ssh, "User aborted at kex warning", NULL,
  5065. 0, TRUE);
  5066. crStopV;
  5067. }
  5068. }
  5069. if (s->warn_hk) {
  5070. int j, k;
  5071. char *betteralgs;
  5072. ssh_set_frozen(ssh, 1);
  5073. /*
  5074. * Change warning box wording depending on why we chose a
  5075. * warning-level host key algorithm. If it's because
  5076. * that's all we have *cached*, use the askhk mechanism,
  5077. * and list the host keys we could usefully cross-certify.
  5078. * Otherwise, use askalg for the standard wording.
  5079. */
  5080. betteralgs = NULL;
  5081. for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
  5082. const struct ssh_signkey_with_user_pref_id *hktype =
  5083. &hostkey_algs[ssh->uncert_hostkeys[j]];
  5084. int better = FALSE;
  5085. for (k = 0; k < HK_MAX; k++) {
  5086. int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
  5087. if (id == HK_WARN) {
  5088. break;
  5089. } else if (id == hktype->id) {
  5090. better = TRUE;
  5091. break;
  5092. }
  5093. }
  5094. if (better) {
  5095. if (betteralgs) {
  5096. char *old_ba = betteralgs;
  5097. betteralgs = dupcat(betteralgs, ",",
  5098. hktype->alg->ssh_id,
  5099. (const char *)NULL);
  5100. sfree(old_ba);
  5101. } else {
  5102. betteralgs = dupstr(hktype->alg->ssh_id);
  5103. }
  5104. }
  5105. }
  5106. if (betteralgs) {
  5107. s->dlgret = askhk(ssh->frontend, ssh->hostkey_alg->ssh_id,
  5108. betteralgs, ssh_dialog_callback, ssh);
  5109. sfree(betteralgs);
  5110. } else {
  5111. s->dlgret = askalg(ssh->frontend, "host key type",
  5112. ssh->hostkey_alg->ssh_id,
  5113. ssh_dialog_callback, ssh);
  5114. }
  5115. if (s->dlgret < 0) {
  5116. ssh->user_response = -1;
  5117. crWaitUntilV(ssh->user_response >= 0);
  5118. s->dlgret = ssh->user_response;
  5119. }
  5120. ssh_set_frozen(ssh, 0);
  5121. if (s->dlgret == 0) {
  5122. ssh_disconnect(ssh, "User aborted at host key warning", NULL,
  5123. 0, TRUE);
  5124. crStopV;
  5125. }
  5126. }
  5127. if (s->warn_cscipher) {
  5128. ssh_set_frozen(ssh, 1);
  5129. s->dlgret = askalg(ssh->frontend,
  5130. "client-to-server cipher",
  5131. s->out.cipher->name,
  5132. ssh_dialog_callback, ssh);
  5133. if (s->dlgret < 0) {
  5134. ssh->user_response = -1;
  5135. crWaitUntilV(ssh->user_response >= 0);
  5136. s->dlgret = ssh->user_response;
  5137. }
  5138. ssh_set_frozen(ssh, 0);
  5139. if (s->dlgret == 0) {
  5140. ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
  5141. 0, TRUE);
  5142. crStopV;
  5143. }
  5144. }
  5145. if (s->warn_sccipher) {
  5146. ssh_set_frozen(ssh, 1);
  5147. s->dlgret = askalg(ssh->frontend,
  5148. "server-to-client cipher",
  5149. s->in.cipher->name,
  5150. ssh_dialog_callback, ssh);
  5151. if (s->dlgret < 0) {
  5152. ssh->user_response = -1;
  5153. crWaitUntilV(ssh->user_response >= 0);
  5154. s->dlgret = ssh->user_response;
  5155. }
  5156. ssh_set_frozen(ssh, 0);
  5157. if (s->dlgret == 0) {
  5158. ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
  5159. 0, TRUE);
  5160. crStopV;
  5161. }
  5162. }
  5163. if (s->ignorepkt) /* first_kex_packet_follows */
  5164. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_transport)) != NULL);
  5165. }
  5166. if (ssh->kex->main_type == KEXTYPE_DH) {
  5167. /*
  5168. * Work out the number of bits of key we will need from the
  5169. * key exchange. We start with the maximum key length of
  5170. * either cipher...
  5171. */
  5172. {
  5173. int csbits, scbits;
  5174. csbits = s->out.cipher ? s->out.cipher->real_keybits : 0;
  5175. scbits = s->in.cipher ? s->in.cipher->real_keybits : 0;
  5176. s->nbits = (csbits > scbits ? csbits : scbits);
  5177. }
  5178. /* The keys only have hlen-bit entropy, since they're based on
  5179. * a hash. So cap the key size at hlen bits. */
  5180. if (s->nbits > ssh->kex->hash->hlen * 8)
  5181. s->nbits = ssh->kex->hash->hlen * 8;
  5182. /*
  5183. * If we're doing Diffie-Hellman group exchange, start by
  5184. * requesting a group.
  5185. */
  5186. if (dh_is_gex(ssh->kex)) {
  5187. logevent("Doing Diffie-Hellman group exchange");
  5188. ssh->pls.kctx = SSH2_PKTCTX_DHGEX;
  5189. /*
  5190. * Work out how big a DH group we will need to allow that
  5191. * much data.
  5192. */
  5193. s->pbits = 512 << ((s->nbits - 1) / 64);
  5194. if (s->pbits < DH_MIN_SIZE)
  5195. s->pbits = DH_MIN_SIZE;
  5196. if (s->pbits > DH_MAX_SIZE)
  5197. s->pbits = DH_MAX_SIZE;
  5198. if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
  5199. s->pktout = ssh_bpp_new_pktout(
  5200. ssh->bpp, SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
  5201. put_uint32(s->pktout, s->pbits);
  5202. } else {
  5203. s->pktout = ssh_bpp_new_pktout(
  5204. ssh->bpp, SSH2_MSG_KEX_DH_GEX_REQUEST);
  5205. put_uint32(s->pktout, DH_MIN_SIZE);
  5206. put_uint32(s->pktout, s->pbits);
  5207. put_uint32(s->pktout, DH_MAX_SIZE);
  5208. }
  5209. ssh_pkt_write(ssh, s->pktout);
  5210. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_transport)) != NULL);
  5211. if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
  5212. bombout(("expected key exchange group packet from server"));
  5213. crStopV;
  5214. }
  5215. s->p = get_mp_ssh2(pktin);
  5216. s->g = get_mp_ssh2(pktin);
  5217. if (get_err(pktin)) {
  5218. freebn(s->p);
  5219. freebn(s->g);
  5220. bombout(("unable to read mp-ints from incoming group packet"));
  5221. crStopV;
  5222. }
  5223. ssh->kex_ctx = dh_setup_gex(s->p, s->g);
  5224. s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
  5225. s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
  5226. } else {
  5227. ssh->pls.kctx = SSH2_PKTCTX_DHGROUP;
  5228. ssh->kex_ctx = dh_setup_group(ssh->kex);
  5229. s->kex_init_value = SSH2_MSG_KEXDH_INIT;
  5230. s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
  5231. logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
  5232. ssh->kex->groupname);
  5233. }
  5234. logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
  5235. ssh->kex->hash->text_name);
  5236. /*
  5237. * Now generate and send e for Diffie-Hellman.
  5238. */
  5239. set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
  5240. s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
  5241. s->pktout = ssh_bpp_new_pktout(ssh->bpp, s->kex_init_value);
  5242. put_mp_ssh2(s->pktout, s->e);
  5243. ssh_pkt_write(ssh, s->pktout);
  5244. set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
  5245. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_transport)) != NULL);
  5246. if (pktin->type != s->kex_reply_value) {
  5247. bombout(("expected key exchange reply packet from server"));
  5248. crStopV;
  5249. }
  5250. set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
  5251. s->hostkeydata = get_string(pktin);
  5252. s->hkey = ssh_key_new_pub(ssh->hostkey_alg, s->hostkeydata);
  5253. s->f = get_mp_ssh2(pktin);
  5254. s->sigdata = get_string(pktin);
  5255. if (get_err(pktin)) {
  5256. bombout(("unable to parse key exchange reply packet"));
  5257. crStopV;
  5258. }
  5259. {
  5260. const char *err = dh_validate_f(ssh->kex_ctx, s->f);
  5261. if (err) {
  5262. bombout(("key exchange reply failed validation: %s", err));
  5263. crStopV;
  5264. }
  5265. }
  5266. s->K = dh_find_K(ssh->kex_ctx, s->f);
  5267. /* We assume everything from now on will be quick, and it might
  5268. * involve user interaction. */
  5269. set_busy_status(ssh->frontend, BUSY_NOT);
  5270. put_stringpl(ssh->exhash_bs, s->hostkeydata);
  5271. if (dh_is_gex(ssh->kex)) {
  5272. if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
  5273. put_uint32(ssh->exhash_bs, DH_MIN_SIZE);
  5274. put_uint32(ssh->exhash_bs, s->pbits);
  5275. if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
  5276. put_uint32(ssh->exhash_bs, DH_MAX_SIZE);
  5277. put_mp_ssh2(ssh->exhash_bs, s->p);
  5278. put_mp_ssh2(ssh->exhash_bs, s->g);
  5279. }
  5280. put_mp_ssh2(ssh->exhash_bs, s->e);
  5281. put_mp_ssh2(ssh->exhash_bs, s->f);
  5282. dh_cleanup(ssh->kex_ctx);
  5283. freebn(s->f);
  5284. if (dh_is_gex(ssh->kex)) {
  5285. freebn(s->g);
  5286. freebn(s->p);
  5287. }
  5288. } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
  5289. logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
  5290. ssh_ecdhkex_curve_textname(ssh->kex),
  5291. ssh->kex->hash->text_name);
  5292. ssh->pls.kctx = SSH2_PKTCTX_ECDHKEX;
  5293. s->eckey = ssh_ecdhkex_newkey(ssh->kex);
  5294. if (!s->eckey) {
  5295. bombout(("Unable to generate key for ECDH"));
  5296. crStopV;
  5297. }
  5298. s->pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_KEX_ECDH_INIT);
  5299. {
  5300. strbuf *pubpoint = strbuf_new();
  5301. ssh_ecdhkex_getpublic(s->eckey, BinarySink_UPCAST(pubpoint));
  5302. put_stringsb(s->pktout, pubpoint);
  5303. }
  5304. ssh_pkt_write(ssh, s->pktout);
  5305. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_transport)) != NULL);
  5306. if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
  5307. ssh_ecdhkex_freekey(s->eckey);
  5308. bombout(("expected ECDH reply packet from server"));
  5309. crStopV;
  5310. }
  5311. s->hostkeydata = get_string(pktin);
  5312. put_stringpl(ssh->exhash_bs, s->hostkeydata);
  5313. s->hkey = ssh_key_new_pub(ssh->hostkey_alg, s->hostkeydata);
  5314. {
  5315. strbuf *pubpoint = strbuf_new();
  5316. ssh_ecdhkex_getpublic(s->eckey, BinarySink_UPCAST(pubpoint));
  5317. put_string(ssh->exhash_bs, pubpoint->u, pubpoint->len);
  5318. strbuf_free(pubpoint);
  5319. }
  5320. {
  5321. ptrlen keydata = get_string(pktin);
  5322. put_stringpl(ssh->exhash_bs, keydata);
  5323. s->K = ssh_ecdhkex_getkey(s->eckey, keydata.ptr, keydata.len);
  5324. if (!get_err(pktin) && !s->K) {
  5325. ssh_ecdhkex_freekey(s->eckey);
  5326. bombout(("point received in ECDH was not valid"));
  5327. crStopV;
  5328. }
  5329. }
  5330. s->sigdata = get_string(pktin);
  5331. if (get_err(pktin)) {
  5332. bombout(("unable to parse key exchange reply packet"));
  5333. crStopV;
  5334. }
  5335. ssh_ecdhkex_freekey(s->eckey);
  5336. #ifndef NO_GSSAPI
  5337. } else if (ssh->kex->main_type == KEXTYPE_GSS) {
  5338. ptrlen data;
  5339. ssh->pls.kctx = SSH2_PKTCTX_GSSKEX;
  5340. s->init_token_sent = 0;
  5341. s->complete_rcvd = 0;
  5342. s->hkey = NULL;
  5343. s->fingerprint = NULL;
  5344. s->keystr = NULL;
  5345. /*
  5346. * Work out the number of bits of key we will need from the
  5347. * key exchange. We start with the maximum key length of
  5348. * either cipher...
  5349. *
  5350. * This is rote from the KEXTYPE_DH section above.
  5351. */
  5352. {
  5353. int csbits, scbits;
  5354. csbits = s->out.cipher->real_keybits;
  5355. scbits = s->in.cipher->real_keybits;
  5356. s->nbits = (csbits > scbits ? csbits : scbits);
  5357. }
  5358. /* The keys only have hlen-bit entropy, since they're based on
  5359. * a hash. So cap the key size at hlen bits. */
  5360. if (s->nbits > ssh->kex->hash->hlen * 8)
  5361. s->nbits = ssh->kex->hash->hlen * 8;
  5362. if (dh_is_gex(ssh->kex)) {
  5363. /*
  5364. * Work out how big a DH group we will need to allow that
  5365. * much data.
  5366. */
  5367. s->pbits = 512 << ((s->nbits - 1) / 64);
  5368. logeventf(ssh, "Doing GSSAPI (with Kerberos V5) Diffie-Hellman "
  5369. "group exchange, with minimum %d bits", s->pbits);
  5370. s->pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_KEXGSS_GROUPREQ);
  5371. put_uint32(s->pktout, s->pbits); /* min */
  5372. put_uint32(s->pktout, s->pbits); /* preferred */
  5373. put_uint32(s->pktout, s->pbits * 2); /* max */
  5374. ssh_pkt_write(ssh, s->pktout);
  5375. crMaybeWaitUntilV(
  5376. (pktin = pq_pop(&ssh->pq_ssh2_transport)) != NULL);
  5377. if (pktin->type != SSH2_MSG_KEXGSS_GROUP) {
  5378. bombout(("expected key exchange group packet from server"));
  5379. crStopV;
  5380. }
  5381. s->p = get_mp_ssh2(pktin);
  5382. s->g = get_mp_ssh2(pktin);
  5383. if (get_err(pktin)) {
  5384. bombout(("unable to read mp-ints from incoming group packet"));
  5385. crStopV;
  5386. }
  5387. ssh->kex_ctx = dh_setup_gex(s->p, s->g);
  5388. } else {
  5389. ssh->kex_ctx = dh_setup_group(ssh->kex);
  5390. logeventf(ssh, "Using GSSAPI (with Kerberos V5) Diffie-Hellman with standard group \"%s\"",
  5391. ssh->kex->groupname);
  5392. }
  5393. logeventf(ssh, "Doing GSSAPI (with Kerberos V5) Diffie-Hellman key exchange with hash %s",
  5394. ssh->kex->hash->text_name);
  5395. /* Now generate e for Diffie-Hellman. */
  5396. set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
  5397. s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
  5398. if (ssh->gsslib->gsslogmsg)
  5399. logevent(ssh->gsslib->gsslogmsg);
  5400. /* initial tokens are empty */
  5401. SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
  5402. SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
  5403. SSH_GSS_CLEAR_BUF(&s->mic);
  5404. s->gss_stat = ssh->gsslib->acquire_cred(ssh->gsslib, &s->gss_ctx,
  5405. &s->gss_cred_expiry);
  5406. if (s->gss_stat != SSH_GSS_OK) {
  5407. bombout(("GSSAPI key exchange failed to initialize"));
  5408. crStopV;
  5409. }
  5410. /* now enter the loop */
  5411. assert(ssh->gss_srv_name);
  5412. do {
  5413. /*
  5414. * When acquire_cred yields no useful expiration, go with the
  5415. * service ticket expiration.
  5416. */
  5417. s->gss_stat = ssh->gsslib->init_sec_context
  5418. (ssh->gsslib,
  5419. &s->gss_ctx,
  5420. ssh->gss_srv_name,
  5421. s->gss_delegate,
  5422. &s->gss_rcvtok,
  5423. &s->gss_sndtok,
  5424. (s->gss_cred_expiry == GSS_NO_EXPIRATION ?
  5425. &s->gss_cred_expiry : NULL),
  5426. NULL);
  5427. SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
  5428. if (s->gss_stat == SSH_GSS_S_COMPLETE && s->complete_rcvd)
  5429. break; /* MIC is verified after the loop */
  5430. if (s->gss_stat != SSH_GSS_S_COMPLETE &&
  5431. s->gss_stat != SSH_GSS_S_CONTINUE_NEEDED) {
  5432. if (ssh->gsslib->display_status(ssh->gsslib, s->gss_ctx,
  5433. &s->gss_buf) == SSH_GSS_OK) {
  5434. bombout(("GSSAPI key exchange failed to initialize"
  5435. " context: %s", (char *)s->gss_buf.value));
  5436. sfree(s->gss_buf.value);
  5437. crStopV;
  5438. } else {
  5439. bombout(("GSSAPI key exchange failed to initialize"
  5440. " context"));
  5441. crStopV;
  5442. }
  5443. }
  5444. assert(s->gss_stat == SSH_GSS_S_COMPLETE ||
  5445. s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
  5446. if (!s->init_token_sent) {
  5447. s->init_token_sent = 1;
  5448. s->pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_KEXGSS_INIT);
  5449. if (s->gss_sndtok.length == 0) {
  5450. bombout(("GSSAPI key exchange failed:"
  5451. " no initial context token"));
  5452. crStopV;
  5453. }
  5454. put_string(s->pktout,
  5455. s->gss_sndtok.value, s->gss_sndtok.length);
  5456. put_mp_ssh2(s->pktout, s->e);
  5457. ssh_pkt_write(ssh, s->pktout);
  5458. ssh->gsslib->free_tok(ssh->gsslib, &s->gss_sndtok);
  5459. logevent("GSSAPI key exchange initialised");
  5460. } else if (s->gss_sndtok.length != 0) {
  5461. s->pktout = ssh_bpp_new_pktout(
  5462. ssh->bpp, SSH2_MSG_KEXGSS_CONTINUE);
  5463. put_string(s->pktout,
  5464. s->gss_sndtok.value, s->gss_sndtok.length);
  5465. ssh_pkt_write(ssh, s->pktout);
  5466. ssh->gsslib->free_tok(ssh->gsslib, &s->gss_sndtok);
  5467. }
  5468. if (s->gss_stat == SSH_GSS_S_COMPLETE && s->complete_rcvd)
  5469. break;
  5470. wait_for_gss_token:
  5471. crMaybeWaitUntilV(
  5472. (pktin = pq_pop(&ssh->pq_ssh2_transport)) != NULL);
  5473. switch (pktin->type) {
  5474. case SSH2_MSG_KEXGSS_CONTINUE:
  5475. data = get_string(pktin);
  5476. s->gss_rcvtok.value = (char *)data.ptr;
  5477. s->gss_rcvtok.length = data.len;
  5478. continue;
  5479. case SSH2_MSG_KEXGSS_COMPLETE:
  5480. s->complete_rcvd = 1;
  5481. s->f = get_mp_ssh2(pktin);
  5482. data = get_string(pktin);
  5483. s->mic.value = (char *)data.ptr;
  5484. s->mic.length = data.len;
  5485. /* Save expiration time of cred when delegating */
  5486. if (s->gss_delegate && s->gss_cred_expiry != GSS_NO_EXPIRATION)
  5487. ssh->gss_cred_expiry = s->gss_cred_expiry;
  5488. /* If there's a final token we loop to consume it */
  5489. if (get_bool(pktin)) {
  5490. data = get_string(pktin);
  5491. s->gss_rcvtok.value = (char *)data.ptr;
  5492. s->gss_rcvtok.length = data.len;
  5493. continue;
  5494. }
  5495. break;
  5496. case SSH2_MSG_KEXGSS_HOSTKEY:
  5497. s->hostkeydata = get_string(pktin);
  5498. if (ssh->hostkey_alg) {
  5499. s->hkey = ssh_key_new_pub(ssh->hostkey_alg,
  5500. s->hostkeydata);
  5501. put_string(ssh->exhash_bs,
  5502. s->hostkeydata.ptr, s->hostkeydata.len);
  5503. }
  5504. /*
  5505. * Can't loop as we have no token to pass to
  5506. * init_sec_context.
  5507. */
  5508. goto wait_for_gss_token;
  5509. case SSH2_MSG_KEXGSS_ERROR:
  5510. /*
  5511. * We have no use for the server's major and minor
  5512. * status. The minor status is really only
  5513. * meaningful to the server, and with luck the major
  5514. * status means something to us (but not really all
  5515. * that much). The string is more meaningful, and
  5516. * hopefully the server sends any error tokens, as
  5517. * that will produce the most useful information for
  5518. * us.
  5519. */
  5520. get_uint32(pktin); /* server's major status */
  5521. get_uint32(pktin); /* server's minor status */
  5522. data = get_string(pktin);
  5523. logeventf(ssh, "GSSAPI key exchange failed; "
  5524. "server's message: %.*s", PTRLEN_PRINTF(data));
  5525. /* Language tag, but we have no use for it */
  5526. get_string(pktin);
  5527. /*
  5528. * Wait for an error token, if there is one, or the
  5529. * server's disconnect. The error token, if there
  5530. * is one, must follow the SSH2_MSG_KEXGSS_ERROR
  5531. * message, per the RFC.
  5532. */
  5533. goto wait_for_gss_token;
  5534. default:
  5535. bombout(("unexpected message type during gss kex"));
  5536. crStopV;
  5537. break;
  5538. }
  5539. } while (s->gss_rcvtok.length ||
  5540. s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED ||
  5541. !s->complete_rcvd);
  5542. s->K = dh_find_K(ssh->kex_ctx, s->f);
  5543. /* We assume everything from now on will be quick, and it might
  5544. * involve user interaction. */
  5545. set_busy_status(ssh->frontend, BUSY_NOT);
  5546. if (!s->hkey)
  5547. put_stringz(ssh->exhash_bs, "");
  5548. if (dh_is_gex(ssh->kex)) {
  5549. /* min, preferred, max */
  5550. put_uint32(ssh->exhash_bs, s->pbits);
  5551. put_uint32(ssh->exhash_bs, s->pbits);
  5552. put_uint32(ssh->exhash_bs, s->pbits * 2);
  5553. put_mp_ssh2(ssh->exhash_bs, s->p);
  5554. put_mp_ssh2(ssh->exhash_bs, s->g);
  5555. }
  5556. put_mp_ssh2(ssh->exhash_bs, s->e);
  5557. put_mp_ssh2(ssh->exhash_bs, s->f);
  5558. /*
  5559. * MIC verification is done below, after we compute the hash
  5560. * used as the MIC input.
  5561. */
  5562. dh_cleanup(ssh->kex_ctx);
  5563. freebn(s->f);
  5564. if (dh_is_gex(ssh->kex)) {
  5565. freebn(s->g);
  5566. freebn(s->p);
  5567. }
  5568. #endif
  5569. } else {
  5570. ptrlen rsakeydata;
  5571. assert(ssh->kex->main_type == KEXTYPE_RSA);
  5572. logeventf(ssh, "Doing RSA key exchange with hash %s",
  5573. ssh->kex->hash->text_name);
  5574. ssh->pls.kctx = SSH2_PKTCTX_RSAKEX;
  5575. /*
  5576. * RSA key exchange. First expect a KEXRSA_PUBKEY packet
  5577. * from the server.
  5578. */
  5579. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_transport)) != NULL);
  5580. if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
  5581. bombout(("expected RSA public key packet from server"));
  5582. crStopV;
  5583. }
  5584. s->hostkeydata = get_string(pktin);
  5585. put_stringpl(ssh->exhash_bs, s->hostkeydata);
  5586. s->hkey = ssh_key_new_pub(ssh->hostkey_alg, s->hostkeydata);
  5587. rsakeydata = get_string(pktin);
  5588. s->rsakey = ssh_rsakex_newkey(rsakeydata.ptr, rsakeydata.len);
  5589. if (!s->rsakey) {
  5590. bombout(("unable to parse RSA public key from server"));
  5591. crStopV;
  5592. }
  5593. put_stringpl(ssh->exhash_bs, rsakeydata);
  5594. /*
  5595. * Next, set up a shared secret K, of precisely KLEN -
  5596. * 2*HLEN - 49 bits, where KLEN is the bit length of the
  5597. * RSA key modulus and HLEN is the bit length of the hash
  5598. * we're using.
  5599. */
  5600. {
  5601. int klen = ssh_rsakex_klen(s->rsakey);
  5602. int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
  5603. int i, byte = 0;
  5604. strbuf *buf;
  5605. unsigned char *outstr;
  5606. int outstrlen;
  5607. s->K = bn_power_2(nbits - 1);
  5608. for (i = 0; i < nbits; i++) {
  5609. if ((i & 7) == 0) {
  5610. byte = random_byte();
  5611. }
  5612. bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
  5613. }
  5614. /*
  5615. * Encode this as an mpint.
  5616. */
  5617. buf = strbuf_new();
  5618. put_mp_ssh2(buf, s->K);
  5619. /*
  5620. * Encrypt it with the given RSA key.
  5621. */
  5622. outstrlen = (klen + 7) / 8;
  5623. outstr = snewn(outstrlen, unsigned char);
  5624. ssh_rsakex_encrypt(ssh->kex->hash, buf->u, buf->len,
  5625. outstr, outstrlen, s->rsakey);
  5626. /*
  5627. * And send it off in a return packet.
  5628. */
  5629. s->pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_KEXRSA_SECRET);
  5630. put_string(s->pktout, outstr, outstrlen);
  5631. ssh_pkt_write(ssh, s->pktout);
  5632. put_string(ssh->exhash_bs, outstr, outstrlen);
  5633. strbuf_free(buf);
  5634. sfree(outstr);
  5635. }
  5636. ssh_rsakex_freekey(s->rsakey);
  5637. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_transport)) != NULL);
  5638. if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
  5639. bombout(("expected signature packet from server"));
  5640. crStopV;
  5641. }
  5642. s->sigdata = get_string(pktin);
  5643. if (get_err(pktin)) {
  5644. bombout(("unable to parse signature packet"));
  5645. crStopV;
  5646. }
  5647. }
  5648. put_mp_ssh2(ssh->exhash_bs, s->K);
  5649. assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
  5650. ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
  5651. #ifndef NO_GSSAPI
  5652. if (ssh->kex->main_type == KEXTYPE_GSS) {
  5653. Ssh_gss_buf gss_buf;
  5654. SSH_GSS_CLEAR_BUF(&s->gss_buf);
  5655. gss_buf.value = s->exchange_hash;
  5656. gss_buf.length = ssh->kex->hash->hlen;
  5657. s->gss_stat = ssh->gsslib->verify_mic(ssh->gsslib, s->gss_ctx, &gss_buf, &s->mic);
  5658. if (s->gss_stat != SSH_GSS_OK) {
  5659. if (ssh->gsslib->display_status(ssh->gsslib, s->gss_ctx,
  5660. &s->gss_buf) == SSH_GSS_OK) {
  5661. bombout(("GSSAPI Key Exchange MIC was not valid: %s",
  5662. (char *)s->gss_buf.value));
  5663. sfree(s->gss_buf.value);
  5664. } else {
  5665. bombout(("GSSAPI Key Exchange MIC was not valid"));
  5666. }
  5667. crStopV;
  5668. }
  5669. ssh->gss_kex_used = TRUE;
  5670. /*-
  5671. * If this the first KEX, save the GSS context for "gssapi-keyex"
  5672. * authentication.
  5673. *
  5674. * http://tools.ietf.org/html/rfc4462#section-4
  5675. *
  5676. * This method may be used only if the initial key exchange was
  5677. * performed using a GSS-API-based key exchange method defined in
  5678. * accordance with Section 2. The GSS-API context used with this
  5679. * method is always that established during an initial GSS-API-based
  5680. * key exchange. Any context established during key exchange for the
  5681. * purpose of rekeying MUST NOT be used with this method.
  5682. */
  5683. if (!s->got_session_id) {
  5684. ssh->gss_ctx = s->gss_ctx;
  5685. } else {
  5686. ssh->gsslib->release_cred(ssh->gsslib, &s->gss_ctx);
  5687. }
  5688. logeventf(ssh, "GSSAPI Key Exchange complete!");
  5689. }
  5690. #endif
  5691. ssh->kex_ctx = NULL;
  5692. #if 0
  5693. debug(("Exchange hash is:\n"));
  5694. dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
  5695. #endif
  5696. /* In GSS keyex there's no hostkey signature to verify */
  5697. if (ssh->kex->main_type != KEXTYPE_GSS) {
  5698. if (!s->hkey) {
  5699. bombout(("Server's host key is invalid"));
  5700. crStopV;
  5701. }
  5702. if (!ssh_key_verify(
  5703. s->hkey, s->sigdata,
  5704. make_ptrlen(s->exchange_hash, ssh->kex->hash->hlen))) {
  5705. #ifndef FUZZING
  5706. bombout(("Server's host key did not match the signature "
  5707. "supplied"));
  5708. crStopV;
  5709. #endif
  5710. }
  5711. }
  5712. s->keystr = (s->hkey ? ssh_key_cache_str(s->hkey) : NULL);
  5713. #ifndef NO_GSSAPI
  5714. if (ssh->gss_kex_used) {
  5715. /*
  5716. * In a GSS-based session, check the host key (if any) against
  5717. * the transient host key cache. See comment above, at the
  5718. * definition of ssh_transient_hostkey_cache_entry.
  5719. */
  5720. if (ssh->kex->main_type == KEXTYPE_GSS) {
  5721. /*
  5722. * We've just done a GSS key exchange. If it gave us a
  5723. * host key, store it.
  5724. */
  5725. if (s->hkey) {
  5726. s->fingerprint = ssh2_fingerprint(s->hkey);
  5727. logevent("GSS kex provided fallback host key:");
  5728. logevent(s->fingerprint);
  5729. sfree(s->fingerprint);
  5730. s->fingerprint = NULL;
  5731. ssh_store_transient_hostkey(ssh, s->hkey);
  5732. } else if (!ssh_have_any_transient_hostkey(ssh)) {
  5733. /*
  5734. * But if it didn't, then we currently have no
  5735. * fallback host key to use in subsequent non-GSS
  5736. * rekeys. So we should immediately trigger a non-GSS
  5737. * rekey of our own, to set one up, before the session
  5738. * keys have been used for anything else.
  5739. *
  5740. * This is similar to the cross-certification done at
  5741. * user request in the permanent host key cache, but
  5742. * here we do it automatically, once, at session
  5743. * startup, and only add the key to the transient
  5744. * cache.
  5745. */
  5746. if (ssh->hostkey_alg) {
  5747. s->need_gss_transient_hostkey = TRUE;
  5748. } else {
  5749. /*
  5750. * If we negotiated the "null" host key algorithm
  5751. * in the key exchange, that's an indication that
  5752. * no host key at all is available from the server
  5753. * (both because we listed "null" last, and
  5754. * because RFC 4462 section 5 says that a server
  5755. * MUST NOT offer "null" as a host key algorithm
  5756. * unless that is the only algorithm it provides
  5757. * at all).
  5758. *
  5759. * In that case we actually _can't_ perform a
  5760. * non-GSSAPI key exchange, so it's pointless to
  5761. * attempt one proactively. This is also likely to
  5762. * cause trouble later if a rekey is required at a
  5763. * moment whne GSS credentials are not available,
  5764. * but someone setting up a server in this
  5765. * configuration presumably accepts that as a
  5766. * consequence.
  5767. */
  5768. if (!s->warned_about_no_gss_transient_hostkey) {
  5769. logevent("No fallback host key available");
  5770. s->warned_about_no_gss_transient_hostkey = TRUE;
  5771. }
  5772. }
  5773. }
  5774. } else {
  5775. /*
  5776. * We've just done a fallback key exchange, so make
  5777. * sure the host key it used is in the cache of keys
  5778. * we previously received in GSS kexes.
  5779. *
  5780. * An exception is if this was the non-GSS key exchange we
  5781. * triggered on purpose to populate the transient cache.
  5782. */
  5783. assert(s->hkey); /* only KEXTYPE_GSS lets this be null */
  5784. s->fingerprint = ssh2_fingerprint(s->hkey);
  5785. if (s->need_gss_transient_hostkey) {
  5786. logevent("Post-GSS rekey provided fallback host key:");
  5787. logevent(s->fingerprint);
  5788. ssh_store_transient_hostkey(ssh, s->hkey);
  5789. s->need_gss_transient_hostkey = FALSE;
  5790. } else if (!ssh_verify_transient_hostkey(ssh, s->hkey)) {
  5791. logevent("Non-GSS rekey after initial GSS kex "
  5792. "used host key:");
  5793. logevent(s->fingerprint);
  5794. bombout(("Host key was not previously sent via GSS kex"));
  5795. }
  5796. sfree(s->fingerprint);
  5797. s->fingerprint = NULL;
  5798. }
  5799. } else
  5800. #endif /* NO_GSSAPI */
  5801. if (!s->got_session_id) {
  5802. /*
  5803. * Make a note of any other host key formats that are available.
  5804. */
  5805. {
  5806. int i, j, nkeys = 0;
  5807. char *list = NULL;
  5808. for (i = 0; i < lenof(hostkey_algs); i++) {
  5809. if (hostkey_algs[i].alg == ssh->hostkey_alg)
  5810. continue;
  5811. for (j = 0; j < ssh->n_uncert_hostkeys; j++)
  5812. if (ssh->uncert_hostkeys[j] == i)
  5813. break;
  5814. if (j < ssh->n_uncert_hostkeys) {
  5815. char *newlist;
  5816. if (list)
  5817. newlist = dupprintf("%s/%s", list,
  5818. hostkey_algs[i].alg->ssh_id);
  5819. else
  5820. newlist = dupprintf("%s", hostkey_algs[i].alg->ssh_id);
  5821. sfree(list);
  5822. list = newlist;
  5823. nkeys++;
  5824. }
  5825. }
  5826. if (list) {
  5827. logeventf(ssh,
  5828. "Server also has %s host key%s, but we "
  5829. "don't know %s", list,
  5830. nkeys > 1 ? "s" : "",
  5831. nkeys > 1 ? "any of them" : "it");
  5832. sfree(list);
  5833. }
  5834. }
  5835. /*
  5836. * Authenticate remote host: verify host key. (We've already
  5837. * checked the signature of the exchange hash.)
  5838. */
  5839. s->fingerprint = ssh2_fingerprint(s->hkey);
  5840. logevent("Host key fingerprint is:");
  5841. logevent(s->fingerprint);
  5842. /* First check against manually configured host keys. */
  5843. s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint, s->hkey);
  5844. if (s->dlgret == 0) { /* did not match */
  5845. bombout(("Host key did not appear in manually configured list"));
  5846. crStopV;
  5847. } else if (s->dlgret < 0) { /* none configured; use standard handling */
  5848. ssh_set_frozen(ssh, 1);
  5849. s->dlgret = verify_ssh_host_key(ssh->frontend,
  5850. ssh->savedhost, ssh->savedport,
  5851. ssh_key_cache_id(s->hkey),
  5852. s->keystr, s->fingerprint,
  5853. ssh_dialog_callback, ssh);
  5854. #ifdef FUZZING
  5855. s->dlgret = 1;
  5856. #endif
  5857. if (s->dlgret < 0) {
  5858. ssh->user_response = -1;
  5859. crWaitUntilV(ssh->user_response >= 0);
  5860. s->dlgret = ssh->user_response;
  5861. }
  5862. ssh_set_frozen(ssh, 0);
  5863. if (s->dlgret == 0) {
  5864. ssh_disconnect(ssh, "Aborted at host key verification", NULL,
  5865. 0, TRUE);
  5866. crStopV;
  5867. }
  5868. }
  5869. sfree(s->fingerprint);
  5870. /*
  5871. * Save this host key, to check against the one presented in
  5872. * subsequent rekeys.
  5873. */
  5874. ssh->hostkey_str = s->keystr;
  5875. s->keystr = NULL;
  5876. } else if (ssh->cross_certifying) {
  5877. s->fingerprint = ssh2_fingerprint(s->hkey);
  5878. logevent("Storing additional host key for this host:");
  5879. logevent(s->fingerprint);
  5880. sfree(s->fingerprint);
  5881. store_host_key(ssh->savedhost, ssh->savedport,
  5882. ssh_key_cache_id(s->hkey), s->keystr);
  5883. ssh->cross_certifying = FALSE;
  5884. /*
  5885. * Don't forget to store the new key as the one we'll be
  5886. * re-checking in future normal rekeys.
  5887. */
  5888. ssh->hostkey_str = s->keystr;
  5889. s->keystr = NULL;
  5890. } else {
  5891. /*
  5892. * In a rekey, we never present an interactive host key
  5893. * verification request to the user. Instead, we simply
  5894. * enforce that the key we're seeing this time is identical to
  5895. * the one we saw before.
  5896. */
  5897. if (strcmp(ssh->hostkey_str, s->keystr)) {
  5898. #ifndef FUZZING
  5899. bombout(("Host key was different in repeat key exchange"));
  5900. crStopV;
  5901. #endif
  5902. }
  5903. }
  5904. sfree(s->keystr);
  5905. if (s->hkey) {
  5906. ssh_key_free(s->hkey);
  5907. s->hkey = NULL;
  5908. }
  5909. /*
  5910. * The exchange hash from the very first key exchange is also
  5911. * the session id, used in session key construction and
  5912. * authentication.
  5913. */
  5914. if (!s->got_session_id) {
  5915. assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
  5916. memcpy(ssh->v2_session_id, s->exchange_hash,
  5917. sizeof(s->exchange_hash));
  5918. ssh->v2_session_id_len = ssh->kex->hash->hlen;
  5919. assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
  5920. s->got_session_id = TRUE;
  5921. }
  5922. /*
  5923. * Send SSH2_MSG_NEWKEYS.
  5924. */
  5925. s->pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_NEWKEYS);
  5926. ssh_pkt_write(ssh, s->pktout);
  5927. ssh->outgoing_data_size = 0; /* start counting from here */
  5928. /*
  5929. * We've sent client NEWKEYS, so create and initialise
  5930. * client-to-server session keys.
  5931. */
  5932. {
  5933. strbuf *cipher_key = strbuf_new();
  5934. strbuf *cipher_iv = strbuf_new();
  5935. strbuf *mac_key = strbuf_new();
  5936. if (s->out.cipher) {
  5937. ssh2_mkkey(ssh, cipher_iv, s->K, s->exchange_hash, 'A',
  5938. s->out.cipher->blksize);
  5939. ssh2_mkkey(ssh, cipher_key, s->K, s->exchange_hash, 'C',
  5940. s->out.cipher->padded_keybytes);
  5941. }
  5942. if (s->out.mac) {
  5943. ssh2_mkkey(ssh, mac_key, s->K, s->exchange_hash, 'E',
  5944. s->out.mac->keylen);
  5945. }
  5946. ssh2_bpp_new_outgoing_crypto(
  5947. ssh->bpp,
  5948. s->out.cipher, cipher_key->u, cipher_iv->u,
  5949. s->out.mac, s->out.etm_mode, mac_key->u,
  5950. s->out.comp);
  5951. /*
  5952. * Remember some details we'll need later for making other
  5953. * policy decisions based on the crypto we've just
  5954. * initialised.
  5955. */
  5956. ssh->v2_cbc_ignore_workaround = (
  5957. s->out.cipher &&
  5958. (s->out.cipher->flags & SSH_CIPHER_IS_CBC) &&
  5959. !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE));
  5960. ssh->v2_out_cipherblksize = s->out.cipher->blksize;
  5961. strbuf_free(cipher_key);
  5962. strbuf_free(cipher_iv);
  5963. strbuf_free(mac_key);
  5964. }
  5965. if (s->out.cipher)
  5966. logeventf(ssh, "Initialised %.200s client->server encryption",
  5967. s->out.cipher->text_name);
  5968. if (s->out.mac)
  5969. logeventf(ssh, "Initialised %.200s client->server"
  5970. " MAC algorithm%s%s",
  5971. s->out.mac->text_name,
  5972. s->out.etm_mode ? " (in ETM mode)" : "",
  5973. (s->out.cipher->required_mac ?
  5974. " (required by cipher)" : ""));
  5975. if (s->out.comp->text_name)
  5976. logeventf(ssh, "Initialised %s compression",
  5977. s->out.comp->text_name);
  5978. /*
  5979. * Now our end of the key exchange is complete, we can send all
  5980. * our queued higher-layer packets.
  5981. */
  5982. ssh->queueing = FALSE;
  5983. ssh2_pkt_queuesend(ssh);
  5984. /*
  5985. * Expect SSH2_MSG_NEWKEYS from server.
  5986. */
  5987. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_transport)) != NULL);
  5988. if (pktin->type != SSH2_MSG_NEWKEYS) {
  5989. bombout(("expected new-keys packet from server"));
  5990. crStopV;
  5991. }
  5992. ssh->incoming_data_size = 0; /* start counting from here */
  5993. /*
  5994. * We've seen server NEWKEYS, so create and initialise
  5995. * server-to-client session keys.
  5996. */
  5997. {
  5998. strbuf *cipher_key = strbuf_new();
  5999. strbuf *cipher_iv = strbuf_new();
  6000. strbuf *mac_key = strbuf_new();
  6001. if (s->in.cipher) {
  6002. ssh2_mkkey(ssh, cipher_iv, s->K, s->exchange_hash, 'B',
  6003. s->in.cipher->blksize);
  6004. ssh2_mkkey(ssh, cipher_key, s->K, s->exchange_hash, 'D',
  6005. s->in.cipher->padded_keybytes);
  6006. }
  6007. if (s->in.mac) {
  6008. ssh2_mkkey(ssh, mac_key, s->K, s->exchange_hash, 'F',
  6009. s->in.mac->keylen);
  6010. }
  6011. ssh2_bpp_new_incoming_crypto(
  6012. ssh->bpp,
  6013. s->in.cipher, cipher_key->u, cipher_iv->u,
  6014. s->in.mac, s->in.etm_mode, mac_key->u,
  6015. s->in.comp);
  6016. strbuf_free(cipher_key);
  6017. strbuf_free(cipher_iv);
  6018. strbuf_free(mac_key);
  6019. }
  6020. if (s->in.cipher)
  6021. logeventf(ssh, "Initialised %.200s server->client encryption",
  6022. s->in.cipher->text_name);
  6023. if (s->in.mac)
  6024. logeventf(ssh, "Initialised %.200s server->client"
  6025. " MAC algorithm%s%s",
  6026. s->in.mac->text_name,
  6027. s->in.etm_mode ? " (in ETM mode)" : "",
  6028. (s->in.cipher->required_mac ?
  6029. " (required by cipher)" : ""));
  6030. if (s->in.comp->text_name)
  6031. logeventf(ssh, "Initialised %s decompression",
  6032. s->in.comp->text_name);
  6033. /*
  6034. * Free shared secret.
  6035. */
  6036. freebn(s->K);
  6037. /*
  6038. * Update the specials menu to list the remaining uncertified host
  6039. * keys.
  6040. */
  6041. update_specials_menu(ssh->frontend);
  6042. /*
  6043. * Key exchange is over. Loop straight back round if we have a
  6044. * deferred rekey reason.
  6045. */
  6046. if (ssh->deferred_rekey_reason) {
  6047. logevent(ssh->deferred_rekey_reason);
  6048. pktin = NULL;
  6049. ssh->deferred_rekey_reason = NULL;
  6050. goto begin_key_exchange;
  6051. }
  6052. /*
  6053. * Otherwise, schedule a timer for our next rekey.
  6054. */
  6055. ssh->kex_in_progress = FALSE;
  6056. ssh->last_rekey = GETTICKCOUNT();
  6057. (void) ssh2_timer_update(ssh, 0);
  6058. /*
  6059. * Now we're encrypting. Get the next-layer protocol started if it
  6060. * hasn't already, and then sit here waiting for reasons to go
  6061. * back to the start and do a repeat key exchange. One of those
  6062. * reasons is that we receive KEXINIT from the other end; the
  6063. * other is if we find ssh->rekey_reason is non-NULL, i.e. we've
  6064. * decided to initiate a rekey ourselves for some reason.
  6065. */
  6066. ssh->rekey_class = RK_NONE;
  6067. while (!pq_peek(&ssh->pq_ssh2_transport) && !ssh->rekey_class) {
  6068. wait_for_rekey:
  6069. if (!ssh->current_user_input_fn) {
  6070. /*
  6071. * Allow userauth to initialise itself.
  6072. */
  6073. do_ssh2_userauth(ssh);
  6074. ssh->current_user_input_fn = ssh2_userauth_input;
  6075. }
  6076. crReturnV;
  6077. }
  6078. if ((pktin = pq_pop(&ssh->pq_ssh2_transport)) != NULL) {
  6079. if (pktin->type != SSH2_MSG_KEXINIT) {
  6080. bombout(("unexpected key exchange packet, type %d", pktin->type));
  6081. crStopV;
  6082. }
  6083. logevent("Server initiated key re-exchange");
  6084. } else {
  6085. if (ssh->rekey_class == RK_POST_USERAUTH) {
  6086. /*
  6087. * userauth has seen a USERAUTH_SUCCEEDED. For a couple of
  6088. * reasons, this may be the moment to do an immediate
  6089. * rekey with different parameters.
  6090. *
  6091. * One is to turn on delayed compression. We do this by a
  6092. * rekey to work around a protocol design bug:
  6093. * draft-miller-secsh-compression-delayed-00 says that you
  6094. * negotiate delayed compression in the first key
  6095. * exchange, and both sides start compressing when the
  6096. * server has sent USERAUTH_SUCCESS. This has a race
  6097. * condition -- the server can't know when the client has
  6098. * seen it, and thus which incoming packets it should
  6099. * treat as compressed.
  6100. *
  6101. * Instead, we do the initial key exchange without
  6102. * offering the delayed methods, but note if the server
  6103. * offers them; when we get here, if a delayed method was
  6104. * available that was higher on our list than what we got,
  6105. * we initiate a rekey in which we _do_ list the delayed
  6106. * methods (and hopefully get it as a result). Subsequent
  6107. * rekeys will do the same.
  6108. *
  6109. * Another reason for a rekey at this point is if we've
  6110. * done a GSS key exchange and don't have anything in our
  6111. * transient hostkey cache, in which case we should make
  6112. * an attempt to populate the cache now.
  6113. */
  6114. assert(!s->userauth_succeeded); /* should only happen once */
  6115. s->userauth_succeeded = TRUE;
  6116. if (s->pending_compression) {
  6117. ssh->rekey_reason = "enabling delayed compression";
  6118. } else if (s->need_gss_transient_hostkey) {
  6119. ssh->rekey_reason = "populating transient host key cache";
  6120. } else {
  6121. /* Can't see any point rekeying. */
  6122. goto wait_for_rekey; /* this is utterly horrid */
  6123. }
  6124. /* else fall through to rekey... */
  6125. s->pending_compression = FALSE;
  6126. }
  6127. /*
  6128. * Now we've decided to rekey.
  6129. *
  6130. * Special case: if the server bug is set that doesn't
  6131. * allow rekeying, we give a different log message and
  6132. * continue waiting. (If such a server _initiates_ a rekey,
  6133. * we process it anyway!)
  6134. */
  6135. if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
  6136. logeventf(ssh, "Server bug prevents key re-exchange (%s)",
  6137. ssh->rekey_reason);
  6138. /* Reset the counters, so that at least this message doesn't
  6139. * hit the event log _too_ often. */
  6140. ssh->outgoing_data_size = 0;
  6141. ssh->incoming_data_size = 0;
  6142. (void) ssh2_timer_update(ssh, 0);
  6143. goto wait_for_rekey; /* this is still utterly horrid */
  6144. } else {
  6145. logeventf(ssh, "Initiating key re-exchange (%s)",
  6146. ssh->rekey_reason);
  6147. }
  6148. }
  6149. goto begin_key_exchange;
  6150. crFinishV;
  6151. }
  6152. /*
  6153. * Send data on an SSH channel. In SSH-2, this involves buffering it
  6154. * first.
  6155. */
  6156. static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
  6157. int len)
  6158. {
  6159. assert(!(c->closes & CLOSES_SENT_EOF));
  6160. if (c->ssh->version == 2) {
  6161. bufchain_add(&c->v.v2.outbuffer, buf, len);
  6162. return ssh2_try_send(c);
  6163. } else {
  6164. PktOut *pkt = ssh_bpp_new_pktout(c->ssh->bpp, SSH1_MSG_CHANNEL_DATA);
  6165. put_uint32(pkt, c->remoteid);
  6166. put_string(pkt, buf, len);
  6167. ssh_pkt_write(c->ssh, pkt);
  6168. /*
  6169. * In SSH-1 we can return 0 here - implying that channels are
  6170. * never individually throttled - because the only
  6171. * circumstance that can cause throttling will be the whole
  6172. * SSH connection backing up, in which case _everything_ will
  6173. * be throttled as a whole.
  6174. */
  6175. return 0;
  6176. }
  6177. }
  6178. /*
  6179. * Attempt to send data on an SSH-2 channel.
  6180. */
  6181. static int ssh2_try_send(struct ssh_channel *c)
  6182. {
  6183. Ssh ssh = c->ssh;
  6184. PktOut *pktout;
  6185. int ret;
  6186. while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
  6187. int len;
  6188. void *data;
  6189. bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
  6190. if ((unsigned)len > c->v.v2.remwindow)
  6191. len = c->v.v2.remwindow;
  6192. if ((unsigned)len > c->v.v2.remmaxpkt)
  6193. len = c->v.v2.remmaxpkt;
  6194. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_CHANNEL_DATA);
  6195. put_uint32(pktout, c->remoteid);
  6196. put_string(pktout, data, len);
  6197. ssh2_pkt_send(ssh, pktout);
  6198. if (!ssh->s) /* a network error might have closed the socket */
  6199. break;
  6200. bufchain_consume(&c->v.v2.outbuffer, len);
  6201. c->v.v2.remwindow -= len;
  6202. }
  6203. /*
  6204. * After having sent as much data as we can, return the amount
  6205. * still buffered.
  6206. */
  6207. ret = bufchain_size(&c->v.v2.outbuffer);
  6208. /*
  6209. * And if there's no data pending but we need to send an EOF, send
  6210. * it.
  6211. */
  6212. if (!ret && c->pending_eof)
  6213. ssh_channel_try_eof(c);
  6214. return ret;
  6215. }
  6216. static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
  6217. {
  6218. int bufsize;
  6219. if (c->closes & CLOSES_SENT_EOF)
  6220. return; /* don't send on channels we've EOFed */
  6221. bufsize = ssh2_try_send(c);
  6222. if (bufsize == 0) {
  6223. c->throttled_by_backlog = FALSE;
  6224. ssh_channel_check_throttle(c);
  6225. }
  6226. }
  6227. static int ssh_is_simple(Ssh ssh)
  6228. {
  6229. /*
  6230. * We use the 'simple' variant of the SSH protocol if we're asked
  6231. * to, except not if we're also doing connection-sharing (either
  6232. * tunnelling our packets over an upstream or expecting to be
  6233. * tunnelled over ourselves), since then the assumption that we
  6234. * have only one channel to worry about is not true after all.
  6235. */
  6236. return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
  6237. !ssh->bare_connection && !ssh->connshare);
  6238. }
  6239. /*
  6240. * Set up most of a new ssh_channel. Nulls out sharectx, but leaves
  6241. * chan untouched (since it will sometimes have been filled in before
  6242. * calling this).
  6243. */
  6244. static void ssh_channel_init(struct ssh_channel *c)
  6245. {
  6246. Ssh ssh = c->ssh;
  6247. c->localid = alloc_channel_id(ssh);
  6248. c->closes = 0;
  6249. c->pending_eof = FALSE;
  6250. c->throttling_conn = FALSE;
  6251. c->sharectx = NULL;
  6252. if (ssh->version == 2) {
  6253. c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
  6254. ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
  6255. c->v.v2.chanreq_head = NULL;
  6256. c->v.v2.throttle_state = UNTHROTTLED;
  6257. bufchain_init(&c->v.v2.outbuffer);
  6258. }
  6259. add234(ssh->channels, c);
  6260. }
  6261. /*
  6262. * Construct the common parts of a CHANNEL_OPEN.
  6263. */
  6264. static PktOut *ssh2_chanopen_init(struct ssh_channel *c,
  6265. const char *type)
  6266. {
  6267. PktOut *pktout;
  6268. pktout = ssh_bpp_new_pktout(c->ssh->bpp, SSH2_MSG_CHANNEL_OPEN);
  6269. put_stringz(pktout, type);
  6270. put_uint32(pktout, c->localid);
  6271. put_uint32(pktout, c->v.v2.locwindow);/* our window size */
  6272. put_uint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
  6273. return pktout;
  6274. }
  6275. /*
  6276. * CHANNEL_FAILURE doesn't come with any indication of what message
  6277. * caused it, so we have to keep track of the outstanding
  6278. * CHANNEL_REQUESTs ourselves.
  6279. */
  6280. static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
  6281. cchandler_fn_t handler, void *ctx)
  6282. {
  6283. struct outstanding_channel_request *ocr =
  6284. snew(struct outstanding_channel_request);
  6285. assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
  6286. ocr->handler = handler;
  6287. ocr->ctx = ctx;
  6288. ocr->next = NULL;
  6289. if (!c->v.v2.chanreq_head)
  6290. c->v.v2.chanreq_head = ocr;
  6291. else
  6292. c->v.v2.chanreq_tail->next = ocr;
  6293. c->v.v2.chanreq_tail = ocr;
  6294. }
  6295. /*
  6296. * Construct the common parts of a CHANNEL_REQUEST. If handler is not
  6297. * NULL then a reply will be requested and the handler will be called
  6298. * when it arrives. The returned packet is ready to have any
  6299. * request-specific data added and be sent. Note that if a handler is
  6300. * provided, it's essential that the request actually be sent.
  6301. *
  6302. * The handler will usually be passed the response packet in pktin. If
  6303. * pktin is NULL, this means that no reply will ever be forthcoming
  6304. * (e.g. because the entire connection is being destroyed, or because
  6305. * the server initiated channel closure before we saw the response)
  6306. * and the handler should free any storage it's holding.
  6307. */
  6308. static PktOut *ssh2_chanreq_init(struct ssh_channel *c,
  6309. const char *type,
  6310. cchandler_fn_t handler, void *ctx)
  6311. {
  6312. PktOut *pktout;
  6313. assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
  6314. pktout = ssh_bpp_new_pktout(c->ssh->bpp, SSH2_MSG_CHANNEL_REQUEST);
  6315. put_uint32(pktout, c->remoteid);
  6316. put_stringz(pktout, type);
  6317. put_bool(pktout, handler != NULL);
  6318. if (handler != NULL)
  6319. ssh2_queue_chanreq_handler(c, handler, ctx);
  6320. return pktout;
  6321. }
  6322. static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
  6323. {
  6324. Ssh ssh = c->ssh;
  6325. int buflimit;
  6326. if (ssh->version == 1) {
  6327. buflimit = SSH1_BUFFER_LIMIT;
  6328. } else {
  6329. if (ssh_is_simple(ssh))
  6330. buflimit = 0;
  6331. else
  6332. buflimit = c->v.v2.locmaxwin;
  6333. if (bufsize < buflimit)
  6334. ssh2_set_window(c, buflimit - bufsize);
  6335. }
  6336. if (c->throttling_conn && bufsize <= buflimit) {
  6337. c->throttling_conn = 0;
  6338. ssh_throttle_conn(ssh, -1);
  6339. }
  6340. }
  6341. /*
  6342. * Potentially enlarge the window on an SSH-2 channel.
  6343. */
  6344. static void ssh2_handle_winadj_response(struct ssh_channel *, PktIn *,
  6345. void *);
  6346. static void ssh2_set_window(struct ssh_channel *c, int newwin)
  6347. {
  6348. Ssh ssh = c->ssh;
  6349. /*
  6350. * Never send WINDOW_ADJUST for a channel that the remote side has
  6351. * already sent EOF on; there's no point, since it won't be
  6352. * sending any more data anyway. Ditto if _we've_ already sent
  6353. * CLOSE.
  6354. */
  6355. if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
  6356. return;
  6357. /*
  6358. * If the client-side Channel is in an initial setup phase with a
  6359. * fixed window size, e.g. for an X11 channel when we're still
  6360. * waiting to see its initial auth and may yet hand it off to a
  6361. * downstream, don't send any WINDOW_ADJUST either.
  6362. */
  6363. if (c->chan->initial_fixed_window_size)
  6364. return;
  6365. /*
  6366. * If the remote end has a habit of ignoring maxpkt, limit the
  6367. * window so that it has no choice (assuming it doesn't ignore the
  6368. * window as well).
  6369. */
  6370. if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
  6371. newwin = OUR_V2_MAXPKT;
  6372. /*
  6373. * Only send a WINDOW_ADJUST if there's significantly more window
  6374. * available than the other end thinks there is. This saves us
  6375. * sending a WINDOW_ADJUST for every character in a shell session.
  6376. *
  6377. * "Significant" is arbitrarily defined as half the window size.
  6378. */
  6379. if (newwin / 2 >= c->v.v2.locwindow) {
  6380. PktOut *pktout;
  6381. unsigned *up;
  6382. /*
  6383. * In order to keep track of how much window the client
  6384. * actually has available, we'd like it to acknowledge each
  6385. * WINDOW_ADJUST. We can't do that directly, so we accompany
  6386. * it with a CHANNEL_REQUEST that has to be acknowledged.
  6387. *
  6388. * This is only necessary if we're opening the window wide.
  6389. * If we're not, then throughput is being constrained by
  6390. * something other than the maximum window size anyway.
  6391. */
  6392. if (newwin == c->v.v2.locmaxwin &&
  6393. !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
  6394. up = snew(unsigned);
  6395. *up = newwin - c->v.v2.locwindow;
  6396. pktout = ssh2_chanreq_init(c, "[email protected]",
  6397. ssh2_handle_winadj_response, up);
  6398. ssh2_pkt_send(ssh, pktout);
  6399. if (c->v.v2.throttle_state != UNTHROTTLED)
  6400. c->v.v2.throttle_state = UNTHROTTLING;
  6401. } else {
  6402. /* Pretend the WINDOW_ADJUST was acked immediately. */
  6403. c->v.v2.remlocwin = newwin;
  6404. c->v.v2.throttle_state = THROTTLED;
  6405. }
  6406. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  6407. put_uint32(pktout, c->remoteid);
  6408. put_uint32(pktout, newwin - c->v.v2.locwindow);
  6409. ssh2_pkt_send(ssh, pktout);
  6410. c->v.v2.locwindow = newwin;
  6411. }
  6412. }
  6413. /*
  6414. * Find the channel associated with a message. If there's no channel,
  6415. * or it's not properly open, make a noise about it and return NULL.
  6416. * If the channel is shared, pass the message on to downstream and
  6417. * also return NULL (meaning the caller should ignore this message).
  6418. */
  6419. static struct ssh_channel *ssh_channel_msg(Ssh ssh, PktIn *pktin)
  6420. {
  6421. unsigned localid = get_uint32(pktin);
  6422. struct ssh_channel *c;
  6423. int halfopen_ok;
  6424. /* Is this message OK on a half-open connection? */
  6425. if (ssh->version == 1)
  6426. halfopen_ok = (pktin->type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION ||
  6427. pktin->type == SSH1_MSG_CHANNEL_OPEN_FAILURE);
  6428. else
  6429. halfopen_ok = (pktin->type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION ||
  6430. pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE);
  6431. c = find234(ssh->channels, &localid, ssh_channelfind);
  6432. if (c && c->sharectx) {
  6433. share_got_pkt_from_server(c->sharectx, pktin->type,
  6434. BinarySource_UPCAST(pktin)->data,
  6435. BinarySource_UPCAST(pktin)->len);
  6436. return NULL;
  6437. }
  6438. if (!c || c->halfopen != halfopen_ok) {
  6439. char *buf = dupprintf("Received %s for %s channel %u",
  6440. ssh_pkt_type(ssh, pktin->type),
  6441. !c ? "nonexistent" :
  6442. c->halfopen ? "half-open" : "open",
  6443. localid);
  6444. ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
  6445. sfree(buf);
  6446. return NULL;
  6447. }
  6448. return c;
  6449. }
  6450. static void ssh2_handle_winadj_response(struct ssh_channel *c,
  6451. PktIn *pktin, void *ctx)
  6452. {
  6453. unsigned *sizep = ctx;
  6454. /*
  6455. * Winadj responses should always be failures. However, at least
  6456. * one server ("boks_sshd") is known to return SUCCESS for channel
  6457. * requests it's never heard of, such as "winadj@putty". Raised
  6458. * with foxt.com as bug 090916-090424, but for the sake of a quiet
  6459. * life, we don't worry about what kind of response we got.
  6460. */
  6461. c->v.v2.remlocwin += *sizep;
  6462. sfree(sizep);
  6463. /*
  6464. * winadj messages are only sent when the window is fully open, so
  6465. * if we get an ack of one, we know any pending unthrottle is
  6466. * complete.
  6467. */
  6468. if (c->v.v2.throttle_state == UNTHROTTLING)
  6469. c->v.v2.throttle_state = UNTHROTTLED;
  6470. }
  6471. static void ssh2_msg_channel_response(Ssh ssh, PktIn *pktin)
  6472. {
  6473. struct ssh_channel *c = ssh_channel_msg(ssh, pktin);
  6474. struct outstanding_channel_request *ocr;
  6475. if (!c) return;
  6476. ocr = c->v.v2.chanreq_head;
  6477. if (!ocr) {
  6478. ssh2_msg_unexpected(ssh, pktin);
  6479. return;
  6480. }
  6481. ocr->handler(c, pktin, ocr->ctx);
  6482. if (ssh->state == SSH_STATE_CLOSED)
  6483. return; /* in case the handler called bomb_out(), which some can */
  6484. c->v.v2.chanreq_head = ocr->next;
  6485. sfree(ocr);
  6486. /*
  6487. * We may now initiate channel-closing procedures, if that
  6488. * CHANNEL_REQUEST was the last thing outstanding before we send
  6489. * CHANNEL_CLOSE.
  6490. */
  6491. ssh2_channel_check_close(c);
  6492. }
  6493. static void ssh2_msg_channel_window_adjust(Ssh ssh, PktIn *pktin)
  6494. {
  6495. struct ssh_channel *c;
  6496. c = ssh_channel_msg(ssh, pktin);
  6497. if (!c)
  6498. return;
  6499. if (!(c->closes & CLOSES_SENT_EOF)) {
  6500. c->v.v2.remwindow += get_uint32(pktin);
  6501. ssh2_try_send_and_unthrottle(ssh, c);
  6502. }
  6503. }
  6504. static void ssh2_msg_channel_data(Ssh ssh, PktIn *pktin)
  6505. {
  6506. ptrlen data;
  6507. unsigned ext_type = 0; /* 0 means not extended */
  6508. struct ssh_channel *c;
  6509. c = ssh_channel_msg(ssh, pktin);
  6510. if (!c)
  6511. return;
  6512. if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
  6513. ext_type = get_uint32(pktin);
  6514. data = get_string(pktin);
  6515. if (!get_err(pktin)) {
  6516. int bufsize;
  6517. c->v.v2.locwindow -= data.len;
  6518. c->v.v2.remlocwin -= data.len;
  6519. if (ext_type != 0 && ext_type != SSH2_EXTENDED_DATA_STDERR)
  6520. data.len = 0; /* Don't do anything with unknown extended data. */
  6521. bufsize = ssh_channel_data(c, ext_type == SSH2_EXTENDED_DATA_STDERR,
  6522. data.ptr, data.len);
  6523. /*
  6524. * If it looks like the remote end hit the end of its window,
  6525. * and we didn't want it to do that, think about using a
  6526. * larger window.
  6527. */
  6528. if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
  6529. c->v.v2.locmaxwin < 0x40000000)
  6530. c->v.v2.locmaxwin += OUR_V2_WINSIZE;
  6531. /*
  6532. * If we are not buffering too much data,
  6533. * enlarge the window again at the remote side.
  6534. * If we are buffering too much, we may still
  6535. * need to adjust the window if the server's
  6536. * sent excess data.
  6537. */
  6538. if (bufsize < c->v.v2.locmaxwin)
  6539. ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
  6540. /*
  6541. * If we're either buffering way too much data, or if we're
  6542. * buffering anything at all and we're in "simple" mode,
  6543. * throttle the whole channel.
  6544. */
  6545. if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
  6546. && !c->throttling_conn) {
  6547. c->throttling_conn = 1;
  6548. ssh_throttle_conn(ssh, +1);
  6549. }
  6550. }
  6551. }
  6552. static void ssh_check_termination(Ssh ssh)
  6553. {
  6554. if (ssh->version == 2 &&
  6555. !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
  6556. (ssh->channels && count234(ssh->channels) == 0) &&
  6557. !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
  6558. /*
  6559. * We used to send SSH_MSG_DISCONNECT here, because I'd
  6560. * believed that _every_ conforming SSH-2 connection had to
  6561. * end with a disconnect being sent by at least one side;
  6562. * apparently I was wrong and it's perfectly OK to
  6563. * unceremoniously slam the connection shut when you're done,
  6564. * and indeed OpenSSH feels this is more polite than sending a
  6565. * DISCONNECT. So now we don't.
  6566. */
  6567. ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
  6568. }
  6569. }
  6570. void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
  6571. const char *peerinfo)
  6572. {
  6573. if (peerinfo)
  6574. logeventf(ssh, "Connection sharing downstream #%u connected from %s",
  6575. id, peerinfo);
  6576. else
  6577. logeventf(ssh, "Connection sharing downstream #%u connected", id);
  6578. }
  6579. void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
  6580. {
  6581. logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
  6582. ssh_check_termination(ssh);
  6583. }
  6584. void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
  6585. {
  6586. va_list ap;
  6587. char *buf;
  6588. va_start(ap, logfmt);
  6589. buf = dupvprintf(logfmt, ap);
  6590. va_end(ap);
  6591. if (id)
  6592. logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
  6593. else
  6594. logeventf(ssh, "Connection sharing: %s", buf);
  6595. sfree(buf);
  6596. }
  6597. /*
  6598. * Close any local socket and free any local resources associated with
  6599. * a channel. This converts the channel into a zombie.
  6600. */
  6601. static void ssh_channel_close_local(struct ssh_channel *c, char const *reason)
  6602. {
  6603. Ssh ssh = c->ssh;
  6604. const char *msg = NULL;
  6605. if (c->sharectx)
  6606. return;
  6607. msg = chan_log_close_msg(c->chan);
  6608. chan_free(c->chan);
  6609. c->chan = zombiechan_new();
  6610. if (msg != NULL) {
  6611. if (reason != NULL)
  6612. logeventf(ssh, "%s %s", msg, reason);
  6613. else
  6614. logevent(msg);
  6615. }
  6616. }
  6617. static void ssh_channel_destroy(struct ssh_channel *c)
  6618. {
  6619. Ssh ssh = c->ssh;
  6620. ssh_channel_close_local(c, NULL);
  6621. del234(ssh->channels, c);
  6622. if (ssh->version == 2) {
  6623. bufchain_clear(&c->v.v2.outbuffer);
  6624. assert(c->v.v2.chanreq_head == NULL);
  6625. }
  6626. sfree(c);
  6627. /*
  6628. * If that was the last channel left open, we might need to
  6629. * terminate.
  6630. */
  6631. ssh_check_termination(ssh);
  6632. }
  6633. static void ssh2_channel_check_close(struct ssh_channel *c)
  6634. {
  6635. Ssh ssh = c->ssh;
  6636. PktOut *pktout;
  6637. assert(ssh->version == 2);
  6638. if (c->halfopen) {
  6639. /*
  6640. * If we've sent out our own CHANNEL_OPEN but not yet seen
  6641. * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
  6642. * it's too early to be sending close messages of any kind.
  6643. */
  6644. return;
  6645. }
  6646. if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
  6647. chan_want_close(c->chan, (c->closes & CLOSES_SENT_EOF),
  6648. (c->closes & CLOSES_RCVD_EOF))) &&
  6649. !c->v.v2.chanreq_head &&
  6650. !(c->closes & CLOSES_SENT_CLOSE)) {
  6651. /*
  6652. * We have both sent and received EOF (or the channel is a
  6653. * zombie), and we have no outstanding channel requests, which
  6654. * means the channel is in final wind-up. But we haven't sent
  6655. * CLOSE, so let's do so now.
  6656. */
  6657. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_CHANNEL_CLOSE);
  6658. put_uint32(pktout, c->remoteid);
  6659. ssh2_pkt_send(ssh, pktout);
  6660. c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
  6661. }
  6662. if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
  6663. assert(c->v.v2.chanreq_head == NULL);
  6664. /*
  6665. * We have both sent and received CLOSE, which means we're
  6666. * completely done with the channel.
  6667. */
  6668. ssh_channel_destroy(c);
  6669. }
  6670. }
  6671. static void ssh_channel_got_eof(struct ssh_channel *c)
  6672. {
  6673. if (c->closes & CLOSES_RCVD_EOF)
  6674. return; /* already seen EOF */
  6675. c->closes |= CLOSES_RCVD_EOF;
  6676. chan_send_eof(c->chan);
  6677. }
  6678. static void ssh2_msg_channel_eof(Ssh ssh, PktIn *pktin)
  6679. {
  6680. struct ssh_channel *c;
  6681. c = ssh_channel_msg(ssh, pktin);
  6682. if (!c)
  6683. return;
  6684. ssh_channel_got_eof(c);
  6685. ssh2_channel_check_close(c);
  6686. }
  6687. static void ssh2_msg_channel_close(Ssh ssh, PktIn *pktin)
  6688. {
  6689. struct ssh_channel *c;
  6690. c = ssh_channel_msg(ssh, pktin);
  6691. if (!c)
  6692. return;
  6693. /*
  6694. * When we receive CLOSE on a channel, we assume it comes with an
  6695. * implied EOF if we haven't seen EOF yet.
  6696. */
  6697. ssh_channel_got_eof(c);
  6698. if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
  6699. /*
  6700. * It also means we stop expecting to see replies to any
  6701. * outstanding channel requests, so clean those up too.
  6702. * (ssh_chanreq_init will enforce by assertion that we don't
  6703. * subsequently put anything back on this list.)
  6704. */
  6705. while (c->v.v2.chanreq_head) {
  6706. struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
  6707. ocr->handler(c, NULL, ocr->ctx);
  6708. c->v.v2.chanreq_head = ocr->next;
  6709. sfree(ocr);
  6710. }
  6711. }
  6712. /*
  6713. * And we also send an outgoing EOF, if we haven't already, on the
  6714. * assumption that CLOSE is a pretty forceful announcement that
  6715. * the remote side is doing away with the entire channel. (If it
  6716. * had wanted to send us EOF and continue receiving data from us,
  6717. * it would have just sent CHANNEL_EOF.)
  6718. */
  6719. if (!(c->closes & CLOSES_SENT_EOF)) {
  6720. /*
  6721. * Abandon any buffered data we still wanted to send to this
  6722. * channel. Receiving a CHANNEL_CLOSE is an indication that
  6723. * the server really wants to get on and _destroy_ this
  6724. * channel, and it isn't going to send us any further
  6725. * WINDOW_ADJUSTs to permit us to send pending stuff.
  6726. */
  6727. bufchain_clear(&c->v.v2.outbuffer);
  6728. /*
  6729. * Send outgoing EOF.
  6730. */
  6731. sshfwd_write_eof(c);
  6732. /*
  6733. * Make sure we don't read any more from whatever our local
  6734. * data source is for this channel. (This will pick up on the
  6735. * changes made by sshfwd_write_eof.)
  6736. */
  6737. ssh_channel_check_throttle(c);
  6738. }
  6739. /*
  6740. * Now process the actual close.
  6741. */
  6742. if (!(c->closes & CLOSES_RCVD_CLOSE)) {
  6743. c->closes |= CLOSES_RCVD_CLOSE;
  6744. ssh2_channel_check_close(c);
  6745. }
  6746. }
  6747. static void ssh2_msg_channel_open_confirmation(Ssh ssh, PktIn *pktin)
  6748. {
  6749. struct ssh_channel *c;
  6750. c = ssh_channel_msg(ssh, pktin);
  6751. if (!c)
  6752. return;
  6753. assert(c->halfopen); /* ssh_channel_msg will have enforced this */
  6754. c->remoteid = get_uint32(pktin);
  6755. c->halfopen = FALSE;
  6756. c->v.v2.remwindow = get_uint32(pktin);
  6757. c->v.v2.remmaxpkt = get_uint32(pktin);
  6758. chan_open_confirmation(c->chan);
  6759. /*
  6760. * Now that the channel is fully open, it's possible in principle
  6761. * to immediately close it. Check whether it wants us to!
  6762. *
  6763. * This can occur if a local socket error occurred between us
  6764. * sending out CHANNEL_OPEN and receiving OPEN_CONFIRMATION. If
  6765. * that happens, all we can do is immediately initiate close
  6766. * proceedings now that we know the server's id to put in the
  6767. * close message. We'll have handled that in this code by having
  6768. * already turned c->chan into a zombie, so its want_close method
  6769. * (which ssh2_channel_check_close will consult) will already be
  6770. * returning TRUE.
  6771. */
  6772. ssh2_channel_check_close(c);
  6773. if (c->pending_eof)
  6774. ssh_channel_try_eof(c); /* in case we had a pending EOF */
  6775. }
  6776. static char *ssh2_channel_open_failure_error_text(PktIn *pktin)
  6777. {
  6778. static const char *const reasons[] = {
  6779. NULL,
  6780. "Administratively prohibited",
  6781. "Connect failed",
  6782. "Unknown channel type",
  6783. "Resource shortage",
  6784. };
  6785. unsigned reason_code;
  6786. const char *reason_code_string;
  6787. char reason_code_buf[256];
  6788. ptrlen reason;
  6789. reason_code = get_uint32(pktin);
  6790. if (reason_code < lenof(reasons) && reasons[reason_code]) {
  6791. reason_code_string = reasons[reason_code];
  6792. } else {
  6793. reason_code_string = reason_code_buf;
  6794. sprintf(reason_code_buf, "unknown reason code %#x", reason_code);
  6795. }
  6796. reason = get_string(pktin);
  6797. return dupprintf("%s [%.*s]", reason_code_string, PTRLEN_PRINTF(reason));
  6798. }
  6799. static void ssh2_msg_channel_open_failure(Ssh ssh, PktIn *pktin)
  6800. {
  6801. struct ssh_channel *c;
  6802. c = ssh_channel_msg(ssh, pktin);
  6803. if (!c)
  6804. return;
  6805. assert(c->halfopen); /* ssh_channel_msg will have enforced this */
  6806. {
  6807. char *errtext = ssh2_channel_open_failure_error_text(pktin);
  6808. chan_open_failed(c->chan, errtext);
  6809. sfree(errtext);
  6810. }
  6811. chan_free(c->chan);
  6812. del234(ssh->channels, c);
  6813. sfree(c);
  6814. }
  6815. static void ssh2_msg_channel_request(Ssh ssh, PktIn *pktin)
  6816. {
  6817. ptrlen type;
  6818. int want_reply;
  6819. int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
  6820. struct ssh_channel *c;
  6821. PktOut *pktout;
  6822. c = ssh_channel_msg(ssh, pktin);
  6823. if (!c)
  6824. return;
  6825. type = get_string(pktin);
  6826. want_reply = get_bool(pktin);
  6827. if (c->closes & CLOSES_SENT_CLOSE) {
  6828. /*
  6829. * We don't reply to channel requests after we've sent
  6830. * CHANNEL_CLOSE for the channel, because our reply might
  6831. * cross in the network with the other side's CHANNEL_CLOSE
  6832. * and arrive after they have wound the channel up completely.
  6833. */
  6834. want_reply = FALSE;
  6835. }
  6836. /*
  6837. * Having got the channel number, we now look at
  6838. * the request type string to see if it's something
  6839. * we recognise.
  6840. */
  6841. if (c == ssh->mainchan) {
  6842. /*
  6843. * We recognise "exit-status" and "exit-signal" on
  6844. * the primary channel.
  6845. */
  6846. if (ptrlen_eq_string(type, "exit-status")) {
  6847. ssh->exitcode = get_uint32(pktin);
  6848. logeventf(ssh, "Server sent command exit status %d",
  6849. ssh->exitcode);
  6850. reply = SSH2_MSG_CHANNEL_SUCCESS;
  6851. } else if (ptrlen_eq_string(type, "exit-signal")) {
  6852. char *fmt_sig = NULL, *fmt_msg = NULL;
  6853. ptrlen errmsg;
  6854. int core = FALSE;
  6855. int format, exitcode;
  6856. /* ICK: older versions of OpenSSH (e.g. 3.4p1)
  6857. * provide an `int' for the signal, despite its
  6858. * having been a `string' in the drafts of RFC 4254 since at
  6859. * least 2001. (Fixed in session.c 1.147.) Try to
  6860. * infer which we can safely parse it as. */
  6861. size_t startpos = BinarySource_UPCAST(pktin)->pos;
  6862. for (format = 0; format < 2; format++) {
  6863. BinarySource_UPCAST(pktin)->pos = startpos;
  6864. BinarySource_UPCAST(pktin)->err = BSE_NO_ERROR;
  6865. if (format == 0) { /* standard string-based format */
  6866. ptrlen signame = get_string(pktin);
  6867. fmt_sig = dupprintf(" \"%.*s\"", PTRLEN_PRINTF(signame));
  6868. /*
  6869. * Really hideous method of translating the
  6870. * signal description back into a locally
  6871. * meaningful number.
  6872. */
  6873. if (0)
  6874. ;
  6875. #define TRANSLATE_SIGNAL(s) \
  6876. else if (ptrlen_eq_string(signame, #s)) \
  6877. exitcode = 128 + SIG ## s
  6878. #ifdef SIGABRT
  6879. TRANSLATE_SIGNAL(ABRT);
  6880. #endif
  6881. #ifdef SIGALRM
  6882. TRANSLATE_SIGNAL(ALRM);
  6883. #endif
  6884. #ifdef SIGFPE
  6885. TRANSLATE_SIGNAL(FPE);
  6886. #endif
  6887. #ifdef SIGHUP
  6888. TRANSLATE_SIGNAL(HUP);
  6889. #endif
  6890. #ifdef SIGILL
  6891. TRANSLATE_SIGNAL(ILL);
  6892. #endif
  6893. #ifdef SIGINT
  6894. TRANSLATE_SIGNAL(INT);
  6895. #endif
  6896. #ifdef SIGKILL
  6897. TRANSLATE_SIGNAL(KILL);
  6898. #endif
  6899. #ifdef SIGPIPE
  6900. TRANSLATE_SIGNAL(PIPE);
  6901. #endif
  6902. #ifdef SIGQUIT
  6903. TRANSLATE_SIGNAL(QUIT);
  6904. #endif
  6905. #ifdef SIGSEGV
  6906. TRANSLATE_SIGNAL(SEGV);
  6907. #endif
  6908. #ifdef SIGTERM
  6909. TRANSLATE_SIGNAL(TERM);
  6910. #endif
  6911. #ifdef SIGUSR1
  6912. TRANSLATE_SIGNAL(USR1);
  6913. #endif
  6914. #ifdef SIGUSR2
  6915. TRANSLATE_SIGNAL(USR2);
  6916. #endif
  6917. #undef TRANSLATE_SIGNAL
  6918. else
  6919. exitcode = 128;
  6920. } else { /* nonstandard integer format */
  6921. unsigned signum = get_uint32(pktin);
  6922. fmt_sig = dupprintf(" %u", signum);
  6923. exitcode = 128 + signum;
  6924. }
  6925. core = get_bool(pktin);
  6926. errmsg = get_string(pktin); /* error message */
  6927. get_string(pktin); /* language tag */
  6928. if (!get_err(pktin) && get_avail(pktin) == 0)
  6929. break; /* successful parse */
  6930. sfree(fmt_sig);
  6931. }
  6932. if (format == 2) {
  6933. fmt_sig = NULL;
  6934. exitcode = 128;
  6935. }
  6936. ssh->exitcode = exitcode;
  6937. if (errmsg.len) {
  6938. fmt_msg = dupprintf(" (\"%.*s\")", PTRLEN_PRINTF(errmsg));
  6939. }
  6940. logeventf(ssh, "Server exited on signal%s%s%s",
  6941. fmt_sig ? fmt_sig : "",
  6942. core ? " (core dumped)" : "",
  6943. fmt_msg ? fmt_msg : "");
  6944. sfree(fmt_sig);
  6945. sfree(fmt_msg);
  6946. reply = SSH2_MSG_CHANNEL_SUCCESS;
  6947. }
  6948. } else {
  6949. /*
  6950. * This is a channel request we don't know
  6951. * about, so we now either ignore the request
  6952. * or respond with CHANNEL_FAILURE, depending
  6953. * on want_reply.
  6954. */
  6955. reply = SSH2_MSG_CHANNEL_FAILURE;
  6956. }
  6957. if (want_reply) {
  6958. pktout = ssh_bpp_new_pktout(ssh->bpp, reply);
  6959. put_uint32(pktout, c->remoteid);
  6960. ssh2_pkt_send(ssh, pktout);
  6961. }
  6962. }
  6963. static void ssh2_msg_global_request(Ssh ssh, PktIn *pktin)
  6964. {
  6965. int want_reply;
  6966. PktOut *pktout;
  6967. get_string(pktin); /* ignore request type (see below) */
  6968. want_reply = get_bool(pktin);
  6969. /*
  6970. * We currently don't support any global requests
  6971. * at all, so we either ignore the request or
  6972. * respond with REQUEST_FAILURE, depending on
  6973. * want_reply.
  6974. */
  6975. if (want_reply) {
  6976. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_REQUEST_FAILURE);
  6977. ssh2_pkt_send(ssh, pktout);
  6978. }
  6979. }
  6980. struct X11FakeAuth *ssh_sharing_add_x11_display(
  6981. Ssh ssh, int authtype, ssh_sharing_connstate *share_cs,
  6982. share_channel *share_chan)
  6983. {
  6984. struct X11FakeAuth *auth;
  6985. /*
  6986. * Make up a new set of fake X11 auth data, and add it to the tree
  6987. * of currently valid ones with an indication of the sharing
  6988. * context that it's relevant to.
  6989. */
  6990. auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
  6991. auth->share_cs = share_cs;
  6992. auth->share_chan = share_chan;
  6993. return auth;
  6994. }
  6995. void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
  6996. {
  6997. del234(ssh->x11authtree, auth);
  6998. x11_free_fake_auth(auth);
  6999. }
  7000. static void ssh2_msg_channel_open(Ssh ssh, PktIn *pktin)
  7001. {
  7002. ptrlen type;
  7003. int peerport;
  7004. const char *error = NULL;
  7005. struct ssh_channel *c;
  7006. unsigned remid, winsize, pktsize;
  7007. PktOut *pktout;
  7008. type = get_string(pktin);
  7009. c = snew(struct ssh_channel);
  7010. c->ssh = ssh;
  7011. remid = get_uint32(pktin);
  7012. winsize = get_uint32(pktin);
  7013. pktsize = get_uint32(pktin);
  7014. if (ptrlen_eq_string(type, "x11")) {
  7015. char *addrstr = mkstr(get_string(pktin));
  7016. peerport = get_uint32(pktin);
  7017. logeventf(ssh, "Received X11 connect request from %s:%d",
  7018. addrstr, peerport);
  7019. if (!ssh->X11_fwd_enabled && !ssh->connshare)
  7020. error = "X11 forwarding is not enabled";
  7021. else {
  7022. c->chan = x11_new_channel(ssh->x11authtree, c, addrstr, peerport,
  7023. ssh->connshare != NULL);
  7024. logevent("Opened X11 forward channel");
  7025. }
  7026. sfree(addrstr);
  7027. } else if (ptrlen_eq_string(type, "forwarded-tcpip")) {
  7028. struct ssh_rportfwd pf, *realpf;
  7029. ptrlen peeraddr;
  7030. pf.shost = mkstr(get_string(pktin));
  7031. pf.sport = get_uint32(pktin);
  7032. peeraddr = get_string(pktin);
  7033. peerport = get_uint32(pktin);
  7034. realpf = find234(ssh->rportfwds, &pf, NULL);
  7035. logeventf(ssh, "Received remote port %s:%d open request "
  7036. "from %.*s:%d", pf.shost, pf.sport,
  7037. PTRLEN_PRINTF(peeraddr), peerport);
  7038. sfree(pf.shost);
  7039. if (realpf == NULL) {
  7040. error = "Remote port is not recognised";
  7041. } else {
  7042. char *err;
  7043. if (realpf->share_ctx) {
  7044. /*
  7045. * This port forwarding is on behalf of a
  7046. * connection-sharing downstream, so abandon our own
  7047. * channel-open procedure and just pass the message on
  7048. * to sshshare.c.
  7049. */
  7050. share_got_pkt_from_server(realpf->share_ctx, pktin->type,
  7051. BinarySource_UPCAST(pktin)->data,
  7052. BinarySource_UPCAST(pktin)->len);
  7053. sfree(c);
  7054. return;
  7055. }
  7056. err = pfd_connect(&c->chan, realpf->dhost, realpf->dport,
  7057. c, ssh->conf, realpf->pfrec->addressfamily);
  7058. logeventf(ssh, "Attempting to forward remote port to "
  7059. "%s:%d", realpf->dhost, realpf->dport);
  7060. if (err != NULL) {
  7061. logeventf(ssh, "Port open failed: %s", err);
  7062. sfree(err);
  7063. error = "Port open failed";
  7064. } else {
  7065. logevent("Forwarded port opened successfully");
  7066. }
  7067. }
  7068. } else if (ptrlen_eq_string(type, "[email protected]")) {
  7069. if (!ssh->agentfwd_enabled)
  7070. error = "Agent forwarding is not enabled";
  7071. else
  7072. c->chan = agentf_new(c);
  7073. } else {
  7074. error = "Unsupported channel type requested";
  7075. }
  7076. c->remoteid = remid;
  7077. c->halfopen = FALSE;
  7078. if (error) {
  7079. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_CHANNEL_OPEN_FAILURE);
  7080. put_uint32(pktout, c->remoteid);
  7081. put_uint32(pktout, SSH2_OPEN_CONNECT_FAILED);
  7082. put_stringz(pktout, error);
  7083. put_stringz(pktout, "en"); /* language tag */
  7084. ssh2_pkt_send(ssh, pktout);
  7085. logeventf(ssh, "Rejected channel open: %s", error);
  7086. sfree(c);
  7087. } else {
  7088. ssh_channel_init(c);
  7089. c->v.v2.remwindow = winsize;
  7090. c->v.v2.remmaxpkt = pktsize;
  7091. if (c->chan->initial_fixed_window_size) {
  7092. c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
  7093. c->chan->initial_fixed_window_size;
  7094. }
  7095. pktout = ssh_bpp_new_pktout(
  7096. ssh->bpp, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
  7097. put_uint32(pktout, c->remoteid);
  7098. put_uint32(pktout, c->localid);
  7099. put_uint32(pktout, c->v.v2.locwindow);
  7100. put_uint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
  7101. ssh2_pkt_send(ssh, pktout);
  7102. }
  7103. }
  7104. void sshfwd_x11_sharing_handover(struct ssh_channel *c,
  7105. ssh_sharing_connstate *share_cs,
  7106. share_channel *share_chan,
  7107. const char *peer_addr, int peer_port,
  7108. int endian, int protomajor, int protominor,
  7109. const void *initial_data, int initial_len)
  7110. {
  7111. /*
  7112. * This function is called when we've just discovered that an X
  7113. * forwarding channel on which we'd been handling the initial auth
  7114. * ourselves turns out to be destined for a connection-sharing
  7115. * downstream. So we turn the channel into a sharing one, meaning
  7116. * that we completely stop tracking windows and buffering data and
  7117. * just pass more or less unmodified SSH messages back and forth.
  7118. */
  7119. c->sharectx = share_cs;
  7120. share_setup_x11_channel(share_cs, share_chan,
  7121. c->localid, c->remoteid, c->v.v2.remwindow,
  7122. c->v.v2.remmaxpkt, c->v.v2.locwindow,
  7123. peer_addr, peer_port, endian,
  7124. protomajor, protominor,
  7125. initial_data, initial_len);
  7126. chan_free(c->chan);
  7127. c->chan = NULL;
  7128. }
  7129. void sshfwd_window_override_removed(struct ssh_channel *c)
  7130. {
  7131. /*
  7132. * This function is called when a client-side Channel has just
  7133. * stopped requiring an initial fixed-size window.
  7134. */
  7135. assert(!c->chan->initial_fixed_window_size);
  7136. if (c->ssh->version == 2)
  7137. ssh2_set_window(
  7138. c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
  7139. }
  7140. /*
  7141. * Buffer banner messages for later display at some convenient point,
  7142. * if we're going to display them.
  7143. */
  7144. static void ssh2_msg_userauth_banner(Ssh ssh, PktIn *pktin)
  7145. {
  7146. /* Arbitrary limit to prevent unbounded inflation of buffer */
  7147. if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
  7148. bufchain_size(&ssh->banner) <= 131072) {
  7149. ptrlen banner = get_string(pktin);
  7150. if (banner.len)
  7151. bufchain_add(&ssh->banner, banner.ptr, banner.len);
  7152. }
  7153. }
  7154. /* Helper function to deal with sending tty modes for "pty-req" */
  7155. static void ssh2_send_ttymode(BinarySink *bs,
  7156. const struct ssh_ttymode *mode, char *val)
  7157. {
  7158. put_byte(bs, mode->opcode);
  7159. switch (mode->type) {
  7160. case TTY_OP_CHAR:
  7161. put_uint32(bs, ssh_tty_parse_specchar(val));
  7162. break;
  7163. case TTY_OP_BOOL:
  7164. put_uint32(bs, ssh_tty_parse_boolean(val));
  7165. break;
  7166. }
  7167. }
  7168. static void ssh2_setup_x11(struct ssh_channel *c, PktIn *pktin,
  7169. void *ctx)
  7170. {
  7171. struct ssh2_setup_x11_state {
  7172. int crLine;
  7173. };
  7174. Ssh ssh = c->ssh;
  7175. PktOut *pktout;
  7176. crStateP(ssh2_setup_x11_state, ctx);
  7177. crBeginState;
  7178. logevent("Requesting X11 forwarding");
  7179. pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
  7180. ssh2_setup_x11, s);
  7181. put_bool(pktout, 0); /* many connections */
  7182. put_stringz(pktout, ssh->x11auth->protoname);
  7183. put_stringz(pktout, ssh->x11auth->datastring);
  7184. put_uint32(pktout, ssh->x11disp->screennum);
  7185. ssh2_pkt_send(ssh, pktout);
  7186. /* Wait to be called back with either a response packet, or NULL
  7187. * meaning clean up and free our data */
  7188. crReturnV;
  7189. if (pktin) {
  7190. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
  7191. logevent("X11 forwarding enabled");
  7192. ssh->X11_fwd_enabled = TRUE;
  7193. } else
  7194. logevent("X11 forwarding refused");
  7195. }
  7196. crFinishFreeV;
  7197. }
  7198. static void ssh2_setup_agent(struct ssh_channel *c, PktIn *pktin,
  7199. void *ctx)
  7200. {
  7201. struct ssh2_setup_agent_state {
  7202. int crLine;
  7203. };
  7204. Ssh ssh = c->ssh;
  7205. PktOut *pktout;
  7206. crStateP(ssh2_setup_agent_state, ctx);
  7207. crBeginState;
  7208. logevent("Requesting OpenSSH-style agent forwarding");
  7209. pktout = ssh2_chanreq_init(ssh->mainchan, "[email protected]",
  7210. ssh2_setup_agent, s);
  7211. ssh2_pkt_send(ssh, pktout);
  7212. /* Wait to be called back with either a response packet, or NULL
  7213. * meaning clean up and free our data */
  7214. crReturnV;
  7215. if (pktin) {
  7216. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
  7217. logevent("Agent forwarding enabled");
  7218. ssh->agentfwd_enabled = TRUE;
  7219. } else
  7220. logevent("Agent forwarding refused");
  7221. }
  7222. crFinishFreeV;
  7223. }
  7224. static void ssh2_setup_pty(struct ssh_channel *c, PktIn *pktin,
  7225. void *ctx)
  7226. {
  7227. struct ssh2_setup_pty_state {
  7228. int crLine;
  7229. };
  7230. Ssh ssh = c->ssh;
  7231. PktOut *pktout;
  7232. crStateP(ssh2_setup_pty_state, ctx);
  7233. crBeginState;
  7234. /* Unpick the terminal-speed string. */
  7235. /* XXX perhaps we should allow no speeds to be sent. */
  7236. ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
  7237. sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
  7238. /* Build the pty request. */
  7239. pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
  7240. ssh2_setup_pty, s);
  7241. put_stringz(pktout, conf_get_str(ssh->conf, CONF_termtype));
  7242. put_uint32(pktout, ssh->term_width);
  7243. put_uint32(pktout, ssh->term_height);
  7244. put_uint32(pktout, 0); /* pixel width */
  7245. put_uint32(pktout, 0); /* pixel height */
  7246. {
  7247. strbuf *modebuf = strbuf_new();
  7248. parse_ttymodes(BinarySink_UPCAST(modebuf), ssh, ssh2_send_ttymode);
  7249. put_byte(modebuf, SSH2_TTY_OP_ISPEED);
  7250. put_uint32(modebuf, ssh->ispeed);
  7251. put_byte(modebuf, SSH2_TTY_OP_OSPEED);
  7252. put_uint32(modebuf, ssh->ospeed);
  7253. put_byte(modebuf, SSH_TTY_OP_END);
  7254. put_stringsb(pktout, modebuf);
  7255. }
  7256. ssh2_pkt_send(ssh, pktout);
  7257. ssh->state = SSH_STATE_INTERMED;
  7258. /* Wait to be called back with either a response packet, or NULL
  7259. * meaning clean up and free our data */
  7260. crReturnV;
  7261. if (pktin) {
  7262. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
  7263. logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
  7264. ssh->ospeed, ssh->ispeed);
  7265. ssh->got_pty = TRUE;
  7266. } else {
  7267. c_write_str(ssh, "Server refused to allocate pty\r\n");
  7268. ssh->editing = ssh->echoing = 1;
  7269. }
  7270. }
  7271. crFinishFreeV;
  7272. }
  7273. static void ssh2_setup_env(struct ssh_channel *c, PktIn *pktin,
  7274. void *ctx)
  7275. {
  7276. struct ssh2_setup_env_state {
  7277. int crLine;
  7278. int num_env, env_left, env_ok;
  7279. };
  7280. Ssh ssh = c->ssh;
  7281. PktOut *pktout;
  7282. crStateP(ssh2_setup_env_state, ctx);
  7283. crBeginState;
  7284. /*
  7285. * Send environment variables.
  7286. *
  7287. * Simplest thing here is to send all the requests at once, and
  7288. * then wait for a whole bunch of successes or failures.
  7289. */
  7290. s->num_env = 0;
  7291. {
  7292. char *key, *val;
  7293. for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
  7294. val != NULL;
  7295. val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
  7296. pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
  7297. put_stringz(pktout, key);
  7298. put_stringz(pktout, val);
  7299. ssh2_pkt_send(ssh, pktout);
  7300. s->num_env++;
  7301. }
  7302. if (s->num_env)
  7303. logeventf(ssh, "Sent %d environment variables", s->num_env);
  7304. }
  7305. if (s->num_env) {
  7306. s->env_ok = 0;
  7307. s->env_left = s->num_env;
  7308. while (s->env_left > 0) {
  7309. /* Wait to be called back with either a response packet,
  7310. * or NULL meaning clean up and free our data */
  7311. crReturnV;
  7312. if (!pktin) goto out;
  7313. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
  7314. s->env_ok++;
  7315. s->env_left--;
  7316. }
  7317. if (s->env_ok == s->num_env) {
  7318. logevent("All environment variables successfully set");
  7319. } else if (s->env_ok == 0) {
  7320. logevent("All environment variables refused");
  7321. c_write_str(ssh, "Server refused to set environment variables\r\n");
  7322. } else {
  7323. logeventf(ssh, "%d environment variables refused",
  7324. s->num_env - s->env_ok);
  7325. c_write_str(ssh, "Server refused to set all environment variables\r\n");
  7326. }
  7327. }
  7328. out:;
  7329. crFinishFreeV;
  7330. }
  7331. /*
  7332. * Handle the SSH-2 userauth layer.
  7333. */
  7334. static void ssh2_msg_userauth(Ssh ssh, PktIn *pktin)
  7335. {
  7336. pktin->refcount++; /* avoid packet being freed when we return */
  7337. pq_push(&ssh->pq_ssh2_userauth, pktin);
  7338. if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
  7339. /*
  7340. * The very instant we see this message, the connection
  7341. * protocol has officially started, which means we must
  7342. * install the dispatch-table entries for all the
  7343. * connection-layer messages. In particular, we must do this
  7344. * _before_ we return to the loop in ssh_process_pq_full
  7345. * that's processing the currently queued packets through the
  7346. * dispatch table, because if (say) an SSH_MSG_GLOBAL_REQUEST
  7347. * is already pending in pq_full, we can't afford to delay
  7348. * installing its dispatch table entry until after that queue
  7349. * run is done.
  7350. */
  7351. ssh2_connection_setup(ssh);
  7352. }
  7353. queue_idempotent_callback(&ssh->ssh2_userauth_icb);
  7354. }
  7355. static void do_ssh2_userauth(void *vctx)
  7356. {
  7357. Ssh ssh = (Ssh)vctx;
  7358. PktIn *pktin;
  7359. struct do_ssh2_userauth_state {
  7360. int crLine;
  7361. enum {
  7362. AUTH_TYPE_NONE,
  7363. AUTH_TYPE_PUBLICKEY,
  7364. AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
  7365. AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
  7366. AUTH_TYPE_PASSWORD,
  7367. AUTH_TYPE_GSSAPI, /* always QUIET */
  7368. AUTH_TYPE_KEYBOARD_INTERACTIVE,
  7369. AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
  7370. } type;
  7371. int done_service_req;
  7372. int need_pw, can_pubkey, can_passwd, can_keyb_inter;
  7373. int userpass_ret;
  7374. int tried_pubkey_config, done_agent;
  7375. #ifndef NO_GSSAPI
  7376. int can_gssapi;
  7377. int can_gssapi_keyex_auth;
  7378. int tried_gssapi;
  7379. int tried_gssapi_keyex_auth;
  7380. time_t gss_cred_expiry;
  7381. #endif
  7382. int kbd_inter_refused;
  7383. int we_are_in, userauth_success;
  7384. prompts_t *cur_prompt;
  7385. #ifdef MPEXT
  7386. int change_password;
  7387. #endif
  7388. int num_prompts;
  7389. char *username;
  7390. char *password;
  7391. int got_username;
  7392. strbuf *publickey_blob;
  7393. int privatekey_available, privatekey_encrypted;
  7394. char *publickey_algorithm;
  7395. char *publickey_comment;
  7396. unsigned char *agent_response;
  7397. BinarySource asrc[1]; /* for reading SSH agent response */
  7398. size_t pkblob_pos_in_agent;
  7399. int keyi, nkeys;
  7400. ptrlen pk, alg, comment;
  7401. int len;
  7402. PktOut *pktout;
  7403. Filename *keyfile;
  7404. #ifndef NO_GSSAPI
  7405. Ssh_gss_ctx gss_ctx;
  7406. Ssh_gss_buf gss_buf;
  7407. Ssh_gss_buf gss_rcvtok, gss_sndtok;
  7408. Ssh_gss_stat gss_stat;
  7409. #endif
  7410. };
  7411. crState(do_ssh2_userauth_state);
  7412. crBeginState;
  7413. /* Register as a handler for all the messages this coroutine handles. */
  7414. ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_userauth;
  7415. ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_userauth;
  7416. ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_userauth;
  7417. ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_userauth;
  7418. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_userauth;
  7419. ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_userauth;
  7420. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_userauth; duplicate case value */
  7421. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_userauth; duplicate case value */
  7422. ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_userauth;
  7423. s->done_service_req = FALSE;
  7424. s->we_are_in = s->userauth_success = FALSE;
  7425. s->agent_response = NULL;
  7426. #ifndef NO_GSSAPI
  7427. s->tried_gssapi = FALSE;
  7428. s->tried_gssapi_keyex_auth = FALSE;
  7429. #endif
  7430. if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
  7431. /*
  7432. * Request userauth protocol, and await a response to it.
  7433. */
  7434. s->pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_SERVICE_REQUEST);
  7435. put_stringz(s->pktout, "ssh-userauth");
  7436. ssh2_pkt_send(ssh, s->pktout);
  7437. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_userauth)) != NULL);
  7438. if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
  7439. s->done_service_req = TRUE;
  7440. }
  7441. if (!s->done_service_req) {
  7442. /*
  7443. * Request connection protocol directly, without authentication.
  7444. */
  7445. s->pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_SERVICE_REQUEST);
  7446. put_stringz(s->pktout, "ssh-connection");
  7447. ssh2_pkt_send(ssh, s->pktout);
  7448. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_userauth)) != NULL);
  7449. if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
  7450. s->we_are_in = TRUE; /* no auth required */
  7451. } else {
  7452. bombout(("Server refused service request"));
  7453. crStopV;
  7454. }
  7455. }
  7456. /* Arrange to be able to deal with any BANNERs that come in.
  7457. * (We do this now as packets may come in during the next bit.) */
  7458. bufchain_init(&ssh->banner);
  7459. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
  7460. ssh2_msg_userauth_banner;
  7461. /*
  7462. * Misc one-time setup for authentication.
  7463. */
  7464. s->publickey_blob = NULL;
  7465. if (!s->we_are_in) {
  7466. /*
  7467. * Load the public half of any configured public key file
  7468. * for later use.
  7469. */
  7470. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  7471. if (!filename_is_null(s->keyfile)) {
  7472. int keytype;
  7473. #ifdef _DEBUG
  7474. // To suppress CodeGuard warning
  7475. logeventf(ssh, MPEXT_BOM "Reading key file \"%s\"",
  7476. filename_to_str(s->keyfile));
  7477. #else
  7478. logeventf(ssh, MPEXT_BOM "Reading key file \"%.150s\"",
  7479. filename_to_str(s->keyfile));
  7480. #endif
  7481. keytype = key_type(s->keyfile);
  7482. if (keytype == SSH_KEYTYPE_SSH2 ||
  7483. keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
  7484. keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  7485. const char *error;
  7486. s->publickey_blob = strbuf_new();
  7487. if (ssh2_userkey_loadpub(s->keyfile,
  7488. &s->publickey_algorithm,
  7489. BinarySink_UPCAST(s->publickey_blob),
  7490. &s->publickey_comment, &error)) {
  7491. s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
  7492. if (!s->privatekey_available)
  7493. logeventf(ssh, "Key file contains public key only");
  7494. s->privatekey_encrypted =
  7495. ssh2_userkey_encrypted(s->keyfile, NULL);
  7496. } else {
  7497. char *msgbuf;
  7498. logeventf(ssh, "Unable to load key (%s)",
  7499. error);
  7500. msgbuf = dupprintf(MPEXT_BOM "Unable to load key file "
  7501. "\"%.150s\" (%s)\r\n",
  7502. filename_to_str(s->keyfile),
  7503. error);
  7504. c_write_str(ssh, msgbuf);
  7505. sfree(msgbuf);
  7506. strbuf_free(s->publickey_blob);
  7507. s->publickey_blob = NULL;
  7508. }
  7509. } else {
  7510. char *msgbuf;
  7511. logeventf(ssh, "Unable to use this key file (%s)",
  7512. key_type_to_str(keytype));
  7513. msgbuf = dupprintf(MPEXT_BOM "Unable to use key file \"%.150s\""
  7514. " (%s)\r\n",
  7515. filename_to_str(s->keyfile),
  7516. key_type_to_str(keytype));
  7517. c_write_str(ssh, msgbuf);
  7518. sfree(msgbuf);
  7519. s->publickey_blob = NULL;
  7520. }
  7521. }
  7522. /*
  7523. * Find out about any keys Pageant has (but if there's a
  7524. * public key configured, filter out all others).
  7525. */
  7526. s->nkeys = 0;
  7527. s->agent_response = NULL;
  7528. s->pkblob_pos_in_agent = 0;
  7529. if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
  7530. void *r;
  7531. int rlen;
  7532. strbuf *agent_request;
  7533. logevent("Pageant is running. Requesting keys.");
  7534. /* Request the keys held by the agent. */
  7535. agent_request = strbuf_new_for_agent_query();
  7536. put_byte(agent_request, SSH2_AGENTC_REQUEST_IDENTITIES);
  7537. ssh->auth_agent_query = agent_query(
  7538. agent_request, &r, &rlen, ssh_agent_callback, ssh);
  7539. strbuf_free(agent_request);
  7540. if (ssh->auth_agent_query) {
  7541. ssh->agent_response = NULL;
  7542. crWaitUntilV(ssh->agent_response);
  7543. r = ssh->agent_response;
  7544. rlen = ssh->agent_response_len;
  7545. }
  7546. s->agent_response = r;
  7547. BinarySource_BARE_INIT(s->asrc, r, rlen);
  7548. get_uint32(s->asrc); /* skip length field */
  7549. if (get_byte(s->asrc) == SSH2_AGENT_IDENTITIES_ANSWER) {
  7550. int keyi;
  7551. s->nkeys = toint(get_uint32(s->asrc));
  7552. /*
  7553. * Vet the Pageant response to ensure that the key
  7554. * count and blob lengths make sense.
  7555. */
  7556. if (s->nkeys < 0) {
  7557. logeventf(ssh, "Pageant response contained a negative"
  7558. " key count %d", s->nkeys);
  7559. s->nkeys = 0;
  7560. goto done_agent_query;
  7561. } else {
  7562. logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
  7563. /* See if configured key is in agent. */
  7564. for (keyi = 0; keyi < s->nkeys; keyi++) {
  7565. size_t pos = s->asrc->pos;
  7566. ptrlen blob = get_string(s->asrc);
  7567. get_string(s->asrc); /* skip comment */
  7568. if (get_err(s->asrc)) {
  7569. logeventf(ssh, "Pageant response was truncated");
  7570. s->nkeys = 0;
  7571. goto done_agent_query;
  7572. }
  7573. if (s->publickey_blob &&
  7574. blob.len == s->publickey_blob->len &&
  7575. !memcmp(blob.ptr, s->publickey_blob->s,
  7576. s->publickey_blob->len)) {
  7577. logeventf(ssh, "Pageant key #%d matches "
  7578. "configured key file", keyi);
  7579. s->keyi = keyi;
  7580. s->pkblob_pos_in_agent = pos;
  7581. break;
  7582. }
  7583. }
  7584. if (s->publickey_blob && !s->pkblob_pos_in_agent) {
  7585. logevent("Configured key file not in Pageant");
  7586. s->nkeys = 0;
  7587. }
  7588. }
  7589. } else {
  7590. logevent("Failed to get reply from Pageant");
  7591. }
  7592. done_agent_query:;
  7593. }
  7594. }
  7595. /*
  7596. * We repeat this whole loop, including the username prompt,
  7597. * until we manage a successful authentication. If the user
  7598. * types the wrong _password_, they can be sent back to the
  7599. * beginning to try another username, if this is configured on.
  7600. * (If they specify a username in the config, they are never
  7601. * asked, even if they do give a wrong password.)
  7602. *
  7603. * I think this best serves the needs of
  7604. *
  7605. * - the people who have no configuration, no keys, and just
  7606. * want to try repeated (username,password) pairs until they
  7607. * type both correctly
  7608. *
  7609. * - people who have keys and configuration but occasionally
  7610. * need to fall back to passwords
  7611. *
  7612. * - people with a key held in Pageant, who might not have
  7613. * logged in to a particular machine before; so they want to
  7614. * type a username, and then _either_ their key will be
  7615. * accepted, _or_ they will type a password. If they mistype
  7616. * the username they will want to be able to get back and
  7617. * retype it!
  7618. */
  7619. s->got_username = FALSE;
  7620. while (!s->we_are_in) {
  7621. /*
  7622. * Get a username.
  7623. */
  7624. if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
  7625. /*
  7626. * We got a username last time round this loop, and
  7627. * with change_username turned off we don't try to get
  7628. * it again.
  7629. */
  7630. } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
  7631. s->cur_prompt = new_prompts(ssh->frontend);
  7632. s->cur_prompt->to_server = TRUE;
  7633. s->cur_prompt->name = dupstr("SSH login name");
  7634. add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
  7635. s->userpass_ret = get_userpass_input(s->cur_prompt, NULL);
  7636. while (1) {
  7637. while (s->userpass_ret < 0 &&
  7638. bufchain_size(&ssh->user_input) > 0)
  7639. s->userpass_ret = get_userpass_input(
  7640. s->cur_prompt, &ssh->user_input);
  7641. if (s->userpass_ret >= 0)
  7642. break;
  7643. ssh->send_ok = 1;
  7644. crReturnV;
  7645. ssh->send_ok = 0;
  7646. }
  7647. if (!s->userpass_ret) {
  7648. /*
  7649. * get_userpass_input() failed to get a username.
  7650. * Terminate.
  7651. */
  7652. free_prompts(s->cur_prompt);
  7653. ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
  7654. crStopV;
  7655. }
  7656. ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
  7657. free_prompts(s->cur_prompt);
  7658. } else {
  7659. char *stuff;
  7660. if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
  7661. stuff = dupprintf(MPEXT_BOM "Using username \"%s\".\r\n", ssh->username);
  7662. c_write_str(ssh, stuff);
  7663. sfree(stuff);
  7664. }
  7665. }
  7666. s->got_username = TRUE;
  7667. /*
  7668. * Send an authentication request using method "none": (a)
  7669. * just in case it succeeds, and (b) so that we know what
  7670. * authentication methods we can usefully try next.
  7671. */
  7672. ssh->pls.actx = SSH2_PKTCTX_NOAUTH;
  7673. s->pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_USERAUTH_REQUEST);
  7674. put_stringz(s->pktout, ssh->username);
  7675. put_stringz(s->pktout, "ssh-connection");/* service requested */
  7676. put_stringz(s->pktout, "none"); /* method */
  7677. ssh2_pkt_send(ssh, s->pktout);
  7678. s->type = AUTH_TYPE_NONE;
  7679. s->we_are_in = FALSE;
  7680. s->tried_pubkey_config = FALSE;
  7681. s->kbd_inter_refused = FALSE;
  7682. /* Reset agent request state. */
  7683. s->done_agent = FALSE;
  7684. if (s->agent_response) {
  7685. if (s->pkblob_pos_in_agent) {
  7686. s->asrc->pos = s->pkblob_pos_in_agent;
  7687. } else {
  7688. s->asrc->pos = 9; /* skip length + type + key count */
  7689. s->keyi = 0;
  7690. }
  7691. }
  7692. while (1) {
  7693. ptrlen methods;
  7694. methods.ptr = "";
  7695. methods.len = 0;
  7696. /*
  7697. * Wait for the result of the last authentication request.
  7698. */
  7699. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_userauth)) != NULL);
  7700. /*
  7701. * Now is a convenient point to spew any banner material
  7702. * that we've accumulated. (This should ensure that when
  7703. * we exit the auth loop, we haven't any left to deal
  7704. * with.)
  7705. */
  7706. {
  7707. int size = bufchain_size(&ssh->banner);
  7708. /*
  7709. * Don't show the banner if we're operating in
  7710. * non-verbose non-interactive mode. (It's probably
  7711. * a script, which means nobody will read the
  7712. * banner _anyway_, and moreover the printing of
  7713. * the banner will screw up processing on the
  7714. * output of (say) plink.)
  7715. */
  7716. if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
  7717. char *banner = snewn(size, char);
  7718. bufchain_fetch(&ssh->banner, banner, size);
  7719. #ifdef MPEXT
  7720. display_banner(ssh->frontend, banner, size);
  7721. #endif
  7722. c_write_untrusted(ssh, banner, size);
  7723. sfree(banner);
  7724. }
  7725. bufchain_clear(&ssh->banner);
  7726. }
  7727. if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
  7728. logevent("Access granted");
  7729. s->we_are_in = s->userauth_success = TRUE;
  7730. break;
  7731. }
  7732. if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
  7733. bombout(("Strange packet received during authentication: "
  7734. "type %d", pktin->type));
  7735. crStopV;
  7736. }
  7737. /*
  7738. * OK, we're now sitting on a USERAUTH_FAILURE message, so
  7739. * we can look at the string in it and know what we can
  7740. * helpfully try next.
  7741. */
  7742. if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
  7743. methods = get_string(pktin);
  7744. if (!get_bool(pktin)) {
  7745. /*
  7746. * We have received an unequivocal Access
  7747. * Denied. This can translate to a variety of
  7748. * messages, or no message at all.
  7749. *
  7750. * For forms of authentication which are attempted
  7751. * implicitly, by which I mean without printing
  7752. * anything in the window indicating that we're
  7753. * trying them, we should never print 'Access
  7754. * denied'.
  7755. *
  7756. * If we do print a message saying that we're
  7757. * attempting some kind of authentication, it's OK
  7758. * to print a followup message saying it failed -
  7759. * but the message may sometimes be more specific
  7760. * than simply 'Access denied'.
  7761. *
  7762. * Additionally, if we'd just tried password
  7763. * authentication, we should break out of this
  7764. * whole loop so as to go back to the username
  7765. * prompt (iff we're configured to allow
  7766. * username change attempts).
  7767. */
  7768. if (s->type == AUTH_TYPE_NONE) {
  7769. /* do nothing */
  7770. } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
  7771. s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
  7772. if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
  7773. c_write_str(ssh, "Server refused our key\r\n");
  7774. logevent("Server refused our key");
  7775. } else if (s->type == AUTH_TYPE_PUBLICKEY) {
  7776. /* This _shouldn't_ happen except by a
  7777. * protocol bug causing client and server to
  7778. * disagree on what is a correct signature. */
  7779. c_write_str(ssh, "Server refused public-key signature"
  7780. " despite accepting key!\r\n");
  7781. logevent("Server refused public-key signature"
  7782. " despite accepting key!");
  7783. } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
  7784. /* quiet, so no c_write */
  7785. logevent("Server refused keyboard-interactive authentication");
  7786. } else if (s->type==AUTH_TYPE_GSSAPI) {
  7787. /* always quiet, so no c_write */
  7788. /* also, the code down in the GSSAPI block has
  7789. * already logged this in the Event Log */
  7790. } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
  7791. logevent("Keyboard-interactive authentication failed");
  7792. c_write_str(ssh, "Access denied\r\n");
  7793. } else {
  7794. assert(s->type == AUTH_TYPE_PASSWORD);
  7795. logevent("Password authentication failed");
  7796. c_write_str(ssh, "Access denied\r\n");
  7797. if (conf_get_int(ssh->conf, CONF_change_username)) {
  7798. /* XXX perhaps we should allow
  7799. * keyboard-interactive to do this too? */
  7800. s->we_are_in = FALSE;
  7801. break;
  7802. }
  7803. }
  7804. } else {
  7805. c_write_str(ssh, "Further authentication required\r\n");
  7806. logevent("Further authentication required");
  7807. }
  7808. #ifdef MPEXT
  7809. logeventf(ssh, "Server offered these authentication methods: %*s", methods.len, methods.ptr);
  7810. #endif
  7811. s->can_pubkey =
  7812. in_commasep_string("publickey", methods.ptr, methods.len);
  7813. s->can_passwd =
  7814. in_commasep_string("password", methods.ptr, methods.len);
  7815. s->can_keyb_inter =
  7816. conf_get_int(ssh->conf, CONF_try_ki_auth) &&
  7817. in_commasep_string("keyboard-interactive",
  7818. methods.ptr, methods.len);
  7819. #ifndef NO_GSSAPI
  7820. s->can_gssapi =
  7821. conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
  7822. in_commasep_string("gssapi-with-mic",
  7823. methods.ptr, methods.len) &&
  7824. ssh->gsslibs->nlibraries > 0;
  7825. s->can_gssapi_keyex_auth =
  7826. conf_get_int(ssh->conf, CONF_try_gssapi_kex) &&
  7827. in_commasep_string("gssapi-keyex",
  7828. methods.ptr, methods.len) &&
  7829. ssh->gsslibs->nlibraries > 0 &&
  7830. ssh->gss_ctx;
  7831. #endif
  7832. }
  7833. ssh->pls.actx = SSH2_PKTCTX_NOAUTH;
  7834. #ifndef NO_GSSAPI
  7835. if (s->can_gssapi_keyex_auth && !s->tried_gssapi_keyex_auth) {
  7836. /* gssapi-keyex authentication */
  7837. s->type = AUTH_TYPE_GSSAPI;
  7838. s->tried_gssapi_keyex_auth = TRUE;
  7839. ssh->pls.actx = SSH2_PKTCTX_GSSAPI;
  7840. if (ssh->gsslib->gsslogmsg)
  7841. logevent(ssh->gsslib->gsslogmsg);
  7842. logeventf(ssh, "Trying gssapi-keyex...");
  7843. s->pktout =
  7844. ssh2_gss_authpacket(ssh, ssh->gss_ctx, "gssapi-keyex");
  7845. ssh2_pkt_send(ssh, s->pktout);
  7846. ssh->gsslib->release_cred(ssh->gsslib, &ssh->gss_ctx);
  7847. ssh->gss_ctx = NULL;
  7848. continue;
  7849. } else
  7850. #endif /* NO_GSSAPI */
  7851. if (s->can_pubkey && !s->done_agent && s->nkeys) {
  7852. /*
  7853. * Attempt public-key authentication using a key from Pageant.
  7854. */
  7855. ssh->pls.actx = SSH2_PKTCTX_PUBLICKEY;
  7856. logeventf(ssh, "Trying Pageant key #%d", s->keyi);
  7857. /* Unpack key from agent response */
  7858. s->pk = get_string(s->asrc);
  7859. s->comment = get_string(s->asrc);
  7860. {
  7861. BinarySource src[1];
  7862. BinarySource_BARE_INIT(src, s->pk.ptr, s->pk.len);
  7863. s->alg = get_string(src);
  7864. }
  7865. /* See if server will accept it */
  7866. s->pktout = ssh_bpp_new_pktout(
  7867. ssh->bpp, SSH2_MSG_USERAUTH_REQUEST);
  7868. put_stringz(s->pktout, ssh->username);
  7869. put_stringz(s->pktout, "ssh-connection");
  7870. /* service requested */
  7871. put_stringz(s->pktout, "publickey");
  7872. /* method */
  7873. put_bool(s->pktout, FALSE); /* no signature included */
  7874. put_stringpl(s->pktout, s->alg);
  7875. put_stringpl(s->pktout, s->pk);
  7876. ssh2_pkt_send(ssh, s->pktout);
  7877. s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
  7878. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_userauth)) != NULL);
  7879. if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
  7880. /* Offer of key refused, presumably via
  7881. * USERAUTH_FAILURE. Requeue for the next iteration. */
  7882. pq_push_front(&ssh->pq_ssh2_userauth, pktin);
  7883. } else {
  7884. strbuf *agentreq, *sigdata;
  7885. void *r;
  7886. int rlen;
  7887. if (flags & FLAG_VERBOSE) {
  7888. c_write_str(ssh, "Authenticating with "
  7889. "public key \"");
  7890. c_write(ssh, s->comment.ptr, s->comment.len);
  7891. c_write_str(ssh, "\" from agent\r\n");
  7892. }
  7893. /*
  7894. * Server is willing to accept the key.
  7895. * Construct a SIGN_REQUEST.
  7896. */
  7897. s->pktout = ssh_bpp_new_pktout(
  7898. ssh->bpp, SSH2_MSG_USERAUTH_REQUEST);
  7899. put_stringz(s->pktout, ssh->username);
  7900. put_stringz(s->pktout, "ssh-connection");
  7901. /* service requested */
  7902. put_stringz(s->pktout, "publickey");
  7903. /* method */
  7904. put_bool(s->pktout, TRUE); /* signature included */
  7905. put_stringpl(s->pktout, s->alg);
  7906. put_stringpl(s->pktout, s->pk);
  7907. /* Ask agent for signature. */
  7908. agentreq = strbuf_new_for_agent_query();
  7909. put_byte(agentreq, SSH2_AGENTC_SIGN_REQUEST);
  7910. put_stringpl(agentreq, s->pk);
  7911. /* Now the data to be signed... */
  7912. sigdata = strbuf_new();
  7913. if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID) {
  7914. put_data(sigdata, ssh->v2_session_id,
  7915. ssh->v2_session_id_len);
  7916. } else {
  7917. put_string(sigdata, ssh->v2_session_id,
  7918. ssh->v2_session_id_len);
  7919. }
  7920. put_data(sigdata, s->pktout->data + 5,
  7921. s->pktout->length - 5);
  7922. put_stringsb(agentreq, sigdata);
  7923. /* And finally the (zero) flags word. */
  7924. put_uint32(agentreq, 0);
  7925. ssh->auth_agent_query = agent_query(
  7926. agentreq, &r, &rlen, ssh_agent_callback, ssh);
  7927. strbuf_free(agentreq);
  7928. if (ssh->auth_agent_query) {
  7929. ssh->agent_response = NULL;
  7930. crWaitUntilV(ssh->agent_response);
  7931. r = ssh->agent_response;
  7932. rlen = ssh->agent_response_len;
  7933. }
  7934. if (r) {
  7935. ptrlen sigblob;
  7936. BinarySource src[1];
  7937. BinarySource_BARE_INIT(src, r, rlen);
  7938. get_uint32(src); /* skip length field */
  7939. if (get_byte(src) == SSH2_AGENT_SIGN_RESPONSE &&
  7940. (sigblob = get_string(src), !get_err(src))) {
  7941. logevent("Sending Pageant's response");
  7942. ssh2_add_sigblob(ssh, s->pktout,
  7943. s->pk.ptr, s->pk.len,
  7944. sigblob.ptr, sigblob.len);
  7945. ssh2_pkt_send(ssh, s->pktout);
  7946. s->type = AUTH_TYPE_PUBLICKEY;
  7947. } else {
  7948. /* FIXME: less drastic response */
  7949. bombout(("Pageant failed to answer challenge"));
  7950. crStopV;
  7951. }
  7952. }
  7953. }
  7954. /* Do we have any keys left to try? */
  7955. if (s->pkblob_pos_in_agent) {
  7956. s->done_agent = TRUE;
  7957. s->tried_pubkey_config = TRUE;
  7958. } else {
  7959. s->keyi++;
  7960. if (s->keyi >= s->nkeys)
  7961. s->done_agent = TRUE;
  7962. }
  7963. } else if (s->can_pubkey && s->publickey_blob &&
  7964. s->privatekey_available && !s->tried_pubkey_config) {
  7965. struct ssh2_userkey *key; /* not live over crReturn */
  7966. char *passphrase; /* not live over crReturn */
  7967. ssh->pls.actx = SSH2_PKTCTX_PUBLICKEY;
  7968. s->tried_pubkey_config = TRUE;
  7969. /*
  7970. * Try the public key supplied in the configuration.
  7971. *
  7972. * First, offer the public blob to see if the server is
  7973. * willing to accept it.
  7974. */
  7975. s->pktout = ssh_bpp_new_pktout(
  7976. ssh->bpp, SSH2_MSG_USERAUTH_REQUEST);
  7977. put_stringz(s->pktout, ssh->username);
  7978. put_stringz(s->pktout, "ssh-connection");
  7979. /* service requested */
  7980. put_stringz(s->pktout, "publickey"); /* method */
  7981. put_bool(s->pktout, FALSE);
  7982. /* no signature included */
  7983. put_stringz(s->pktout, s->publickey_algorithm);
  7984. put_string(s->pktout, s->publickey_blob->s,
  7985. s->publickey_blob->len);
  7986. ssh2_pkt_send(ssh, s->pktout);
  7987. logevent("Offered public key");
  7988. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_userauth)) != NULL);
  7989. if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
  7990. /* Key refused. Give up. */
  7991. pq_push_front(&ssh->pq_ssh2_userauth, pktin);
  7992. s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
  7993. continue; /* process this new message */
  7994. }
  7995. logevent("Offer of public key accepted");
  7996. /*
  7997. * Actually attempt a serious authentication using
  7998. * the key.
  7999. */
  8000. if (flags & FLAG_VERBOSE) {
  8001. c_write_str(ssh, "Authenticating with public key \"");
  8002. c_write_str(ssh, s->publickey_comment);
  8003. c_write_str(ssh, "\"\r\n");
  8004. }
  8005. key = NULL;
  8006. while (!key) {
  8007. const char *error; /* not live over crReturn */
  8008. if (s->privatekey_encrypted) {
  8009. /*
  8010. * Get a passphrase from the user.
  8011. */
  8012. s->cur_prompt = new_prompts(ssh->frontend);
  8013. s->cur_prompt->to_server = FALSE;
  8014. s->cur_prompt->name = dupstr("SSH key passphrase");
  8015. add_prompt(s->cur_prompt,
  8016. dupprintf("Passphrase for key \"%.100s\": ",
  8017. s->publickey_comment),
  8018. FALSE);
  8019. s->userpass_ret = get_userpass_input(
  8020. s->cur_prompt, NULL);
  8021. while (1) {
  8022. while (s->userpass_ret < 0 &&
  8023. bufchain_size(&ssh->user_input) > 0)
  8024. s->userpass_ret = get_userpass_input(
  8025. s->cur_prompt, &ssh->user_input);
  8026. if (s->userpass_ret >= 0)
  8027. break;
  8028. ssh->send_ok = 1;
  8029. crReturnV;
  8030. ssh->send_ok = 0;
  8031. }
  8032. if (!s->userpass_ret) {
  8033. /* Failed to get a passphrase. Terminate. */
  8034. free_prompts(s->cur_prompt);
  8035. ssh_disconnect(ssh, NULL,
  8036. "Unable to authenticate",
  8037. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  8038. TRUE);
  8039. crStopV;
  8040. }
  8041. passphrase =
  8042. dupstr(s->cur_prompt->prompts[0]->result);
  8043. free_prompts(s->cur_prompt);
  8044. } else {
  8045. passphrase = NULL; /* no passphrase needed */
  8046. }
  8047. /*
  8048. * Try decrypting the key.
  8049. */
  8050. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  8051. key = ssh2_load_userkey(s->keyfile, passphrase, &error);
  8052. if (passphrase) {
  8053. /* burn the evidence */
  8054. smemclr(passphrase, strlen(passphrase));
  8055. sfree(passphrase);
  8056. }
  8057. if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
  8058. if (passphrase &&
  8059. (key == SSH2_WRONG_PASSPHRASE)) {
  8060. c_write_str(ssh, "Wrong passphrase\r\n");
  8061. key = NULL;
  8062. /* and loop again */
  8063. } else {
  8064. c_write_str(ssh, "Unable to load private key (");
  8065. c_write_str(ssh, error);
  8066. c_write_str(ssh, ")\r\n");
  8067. key = NULL;
  8068. break; /* try something else */
  8069. }
  8070. }
  8071. }
  8072. if (key) {
  8073. strbuf *pkblob, *sigdata, *sigblob;
  8074. /*
  8075. * We have loaded the private key and the server
  8076. * has announced that it's willing to accept it.
  8077. * Hallelujah. Generate a signature and send it.
  8078. */
  8079. s->pktout = ssh_bpp_new_pktout(
  8080. ssh->bpp, SSH2_MSG_USERAUTH_REQUEST);
  8081. put_stringz(s->pktout, ssh->username);
  8082. put_stringz(s->pktout, "ssh-connection");
  8083. /* service requested */
  8084. put_stringz(s->pktout, "publickey"); /* method */
  8085. put_bool(s->pktout, TRUE); /* signature follows */
  8086. put_stringz(s->pktout, ssh_key_ssh_id(key->key));
  8087. pkblob = strbuf_new();
  8088. ssh_key_public_blob(key->key, BinarySink_UPCAST(pkblob));
  8089. put_string(s->pktout, pkblob->s, pkblob->len);
  8090. /*
  8091. * The data to be signed is:
  8092. *
  8093. * string session-id
  8094. *
  8095. * followed by everything so far placed in the
  8096. * outgoing packet.
  8097. */
  8098. sigdata = strbuf_new();
  8099. if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID) {
  8100. put_data(sigdata, ssh->v2_session_id,
  8101. ssh->v2_session_id_len);
  8102. } else {
  8103. put_string(sigdata, ssh->v2_session_id,
  8104. ssh->v2_session_id_len);
  8105. }
  8106. put_data(sigdata, s->pktout->data + 5,
  8107. s->pktout->length - 5);
  8108. sigblob = strbuf_new();
  8109. ssh_key_sign(key->key, sigdata->s, sigdata->len,
  8110. BinarySink_UPCAST(sigblob));
  8111. strbuf_free(sigdata);
  8112. ssh2_add_sigblob(ssh, s->pktout, pkblob->s, pkblob->len,
  8113. sigblob->s, sigblob->len);
  8114. strbuf_free(pkblob);
  8115. strbuf_free(sigblob);
  8116. ssh2_pkt_send(ssh, s->pktout);
  8117. logevent("Sent public key signature");
  8118. s->type = AUTH_TYPE_PUBLICKEY;
  8119. ssh_key_free(key->key);
  8120. sfree(key->comment);
  8121. sfree(key);
  8122. }
  8123. #ifndef NO_GSSAPI
  8124. } else if (s->can_gssapi && !s->tried_gssapi) {
  8125. /* gssapi-with-mic authentication */
  8126. ptrlen data;
  8127. #ifdef MPEXT
  8128. const char * fullhostname;
  8129. char *loghost;
  8130. #endif
  8131. s->type = AUTH_TYPE_GSSAPI;
  8132. s->tried_gssapi = TRUE;
  8133. ssh->pls.actx = SSH2_PKTCTX_GSSAPI;
  8134. if (ssh->gsslib->gsslogmsg)
  8135. logevent(ssh->gsslib->gsslogmsg);
  8136. /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
  8137. logeventf(ssh, "Trying gssapi-with-mic...");
  8138. s->pktout = ssh_bpp_new_pktout(
  8139. ssh->bpp, SSH2_MSG_USERAUTH_REQUEST);
  8140. put_stringz(s->pktout, ssh->username);
  8141. put_stringz(s->pktout, "ssh-connection");
  8142. put_stringz(s->pktout, "gssapi-with-mic");
  8143. logevent("Attempting GSSAPI authentication");
  8144. /* add mechanism info */
  8145. ssh->gsslib->indicate_mech(ssh->gsslib, &s->gss_buf);
  8146. /* number of GSSAPI mechanisms */
  8147. put_uint32(s->pktout, 1);
  8148. /* length of OID + 2 */
  8149. put_uint32(s->pktout, s->gss_buf.length + 2);
  8150. put_byte(s->pktout, SSH2_GSS_OIDTYPE);
  8151. /* length of OID */
  8152. put_byte(s->pktout, s->gss_buf.length);
  8153. put_data(s->pktout, s->gss_buf.value, s->gss_buf.length);
  8154. ssh2_pkt_send(ssh, s->pktout);
  8155. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_userauth)) != NULL);
  8156. if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
  8157. logevent("GSSAPI authentication request refused");
  8158. pq_push_front(&ssh->pq_ssh2_userauth, pktin);
  8159. continue;
  8160. }
  8161. /* check returned packet ... */
  8162. data = get_string(pktin);
  8163. s->gss_rcvtok.value = (char *)data.ptr;
  8164. s->gss_rcvtok.length = data.len;
  8165. if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
  8166. ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
  8167. ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
  8168. memcmp((char *)s->gss_rcvtok.value + 2,
  8169. s->gss_buf.value,s->gss_buf.length) ) {
  8170. logevent("GSSAPI authentication - wrong response from server");
  8171. continue;
  8172. }
  8173. #ifdef MPEXT
  8174. fullhostname = ssh->fullhostname;
  8175. loghost = conf_get_str(ssh->conf, CONF_loghost);
  8176. if (loghost[0] != '\0')
  8177. {
  8178. fullhostname = loghost;
  8179. }
  8180. #endif
  8181. /* Import server name if not cached from KEX */
  8182. if (ssh->gss_srv_name == GSS_C_NO_NAME) {
  8183. s->gss_stat = ssh->gsslib->import_name(ssh->gsslib,
  8184. #ifdef MPEXT
  8185. fullhostname,
  8186. #else
  8187. ssh->fullhostname,
  8188. #endif
  8189. &ssh->gss_srv_name);
  8190. if (s->gss_stat != SSH_GSS_OK) {
  8191. if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
  8192. logevent("GSSAPI import name failed -"
  8193. " Bad service name");
  8194. else
  8195. logevent("GSSAPI import name failed");
  8196. continue;
  8197. }
  8198. }
  8199. /* Allocate our gss_ctx */
  8200. s->gss_stat = ssh->gsslib->acquire_cred(ssh->gsslib,
  8201. &s->gss_ctx, NULL);
  8202. if (s->gss_stat != SSH_GSS_OK) {
  8203. logevent("GSSAPI authentication failed to get credentials");
  8204. continue;
  8205. }
  8206. /* initial tokens are empty */
  8207. SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
  8208. SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
  8209. /* now enter the loop */
  8210. do {
  8211. /*
  8212. * When acquire_cred yields no useful expiration, go with
  8213. * the service ticket expiration.
  8214. */
  8215. s->gss_stat = ssh->gsslib->init_sec_context
  8216. (ssh->gsslib,
  8217. &s->gss_ctx,
  8218. ssh->gss_srv_name,
  8219. conf_get_int(ssh->conf, CONF_gssapifwd),
  8220. &s->gss_rcvtok,
  8221. &s->gss_sndtok,
  8222. NULL,
  8223. NULL);
  8224. if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
  8225. s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
  8226. logevent("GSSAPI authentication initialisation failed");
  8227. if (ssh->gsslib->display_status(ssh->gsslib,
  8228. s->gss_ctx, &s->gss_buf) == SSH_GSS_OK) {
  8229. logevent(s->gss_buf.value);
  8230. sfree(s->gss_buf.value);
  8231. }
  8232. pq_push_front(&ssh->pq_ssh2_userauth, pktin);
  8233. break;
  8234. }
  8235. logevent("GSSAPI authentication initialised");
  8236. /*
  8237. * Client and server now exchange tokens until GSSAPI
  8238. * no longer says CONTINUE_NEEDED
  8239. */
  8240. if (s->gss_sndtok.length != 0) {
  8241. s->pktout =
  8242. ssh_bpp_new_pktout(
  8243. ssh->bpp, SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
  8244. put_string(s->pktout,
  8245. s->gss_sndtok.value, s->gss_sndtok.length);
  8246. ssh2_pkt_send(ssh, s->pktout);
  8247. ssh->gsslib->free_tok(ssh->gsslib, &s->gss_sndtok);
  8248. }
  8249. if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
  8250. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_userauth)) != NULL);
  8251. if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
  8252. logevent("GSSAPI authentication -"
  8253. " bad server response");
  8254. s->gss_stat = SSH_GSS_FAILURE;
  8255. pq_push_front(&ssh->pq_ssh2_userauth, pktin);
  8256. break;
  8257. }
  8258. data = get_string(pktin);
  8259. s->gss_rcvtok.value = (char *)data.ptr;
  8260. s->gss_rcvtok.length = data.len;
  8261. }
  8262. } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
  8263. if (s->gss_stat != SSH_GSS_OK) {
  8264. ssh->gsslib->release_cred(ssh->gsslib, &s->gss_ctx);
  8265. continue;
  8266. }
  8267. logevent("GSSAPI authentication loop finished OK");
  8268. /* Now send the MIC */
  8269. s->pktout =
  8270. ssh2_gss_authpacket(ssh, s->gss_ctx, "gssapi-with-mic");
  8271. ssh2_pkt_send(ssh, s->pktout);
  8272. ssh->gsslib->release_cred(ssh->gsslib, &s->gss_ctx);
  8273. continue;
  8274. #endif
  8275. } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
  8276. /*
  8277. * Keyboard-interactive authentication.
  8278. */
  8279. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
  8280. ssh->pls.actx = SSH2_PKTCTX_KBDINTER;
  8281. s->pktout = ssh_bpp_new_pktout(
  8282. ssh->bpp, SSH2_MSG_USERAUTH_REQUEST);
  8283. put_stringz(s->pktout, ssh->username);
  8284. put_stringz(s->pktout, "ssh-connection");
  8285. /* service requested */
  8286. put_stringz(s->pktout, "keyboard-interactive");
  8287. /* method */
  8288. put_stringz(s->pktout, ""); /* lang */
  8289. put_stringz(s->pktout, ""); /* submethods */
  8290. ssh2_pkt_send(ssh, s->pktout);
  8291. logevent("Attempting keyboard-interactive authentication");
  8292. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_userauth)) != NULL);
  8293. if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
  8294. /* Server is not willing to do keyboard-interactive
  8295. * at all (or, bizarrely but legally, accepts the
  8296. * user without actually issuing any prompts).
  8297. * Give up on it entirely. */
  8298. pq_push_front(&ssh->pq_ssh2_userauth, pktin);
  8299. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
  8300. s->kbd_inter_refused = TRUE; /* don't try it again */
  8301. continue;
  8302. }
  8303. /*
  8304. * Loop while the server continues to send INFO_REQUESTs.
  8305. */
  8306. while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
  8307. ptrlen name, inst;
  8308. int i;
  8309. /*
  8310. * We've got a fresh USERAUTH_INFO_REQUEST.
  8311. * Get the preamble and start building a prompt.
  8312. */
  8313. name = get_string(pktin);
  8314. inst = get_string(pktin);
  8315. get_string(pktin); /* skip language tag */
  8316. s->cur_prompt = new_prompts(ssh->frontend);
  8317. s->cur_prompt->to_server = TRUE;
  8318. /*
  8319. * Get any prompt(s) from the packet.
  8320. */
  8321. s->num_prompts = get_uint32(pktin);
  8322. for (i = 0; i < s->num_prompts; i++) {
  8323. ptrlen prompt;
  8324. int echo;
  8325. static char noprompt[] =
  8326. "<server failed to send prompt>: ";
  8327. prompt = get_string(pktin);
  8328. echo = get_bool(pktin);
  8329. if (!prompt.len) {
  8330. prompt.ptr = noprompt;
  8331. prompt.len = lenof(noprompt)-1;
  8332. }
  8333. add_prompt(s->cur_prompt, mkstr(prompt), echo);
  8334. }
  8335. if (name.len) {
  8336. /* FIXME: better prefix to distinguish from
  8337. * local prompts? */
  8338. s->cur_prompt->name =
  8339. dupprintf("SSH server: %.*s", PTRLEN_PRINTF(name));
  8340. s->cur_prompt->name_reqd = TRUE;
  8341. } else {
  8342. s->cur_prompt->name =
  8343. dupstr("SSH server authentication");
  8344. s->cur_prompt->name_reqd = FALSE;
  8345. }
  8346. /* We add a prefix to try to make it clear that a prompt
  8347. * has come from the server.
  8348. * FIXME: ugly to print "Using..." in prompt _every_
  8349. * time round. Can this be done more subtly? */
  8350. /* Special case: for reasons best known to themselves,
  8351. * some servers send k-i requests with no prompts and
  8352. * nothing to display. Keep quiet in this case. */
  8353. if (s->num_prompts || name.len || inst.len) {
  8354. s->cur_prompt->instruction =
  8355. dupprintf("Using keyboard-interactive "
  8356. "authentication.%s%.*s",
  8357. inst.len ? "\n" : "",
  8358. PTRLEN_PRINTF(inst));
  8359. s->cur_prompt->instr_reqd = TRUE;
  8360. } else {
  8361. s->cur_prompt->instr_reqd = FALSE;
  8362. }
  8363. /*
  8364. * Display any instructions, and get the user's
  8365. * response(s).
  8366. */
  8367. s->userpass_ret = get_userpass_input(s->cur_prompt, NULL);
  8368. while (1) {
  8369. while (s->userpass_ret < 0 &&
  8370. bufchain_size(&ssh->user_input) > 0)
  8371. s->userpass_ret = get_userpass_input(
  8372. s->cur_prompt, &ssh->user_input);
  8373. if (s->userpass_ret >= 0)
  8374. break;
  8375. ssh->send_ok = 1;
  8376. crReturnV;
  8377. ssh->send_ok = 0;
  8378. }
  8379. if (!s->userpass_ret) {
  8380. /*
  8381. * Failed to get responses. Terminate.
  8382. */
  8383. free_prompts(s->cur_prompt);
  8384. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  8385. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  8386. TRUE);
  8387. crStopV;
  8388. }
  8389. /*
  8390. * Send the response(s) to the server, padding
  8391. * them to disguise their true length.
  8392. */
  8393. s->pktout = ssh_bpp_new_pktout(
  8394. ssh->bpp, SSH2_MSG_USERAUTH_INFO_RESPONSE);
  8395. put_uint32(s->pktout, s->num_prompts);
  8396. for (i=0; i < s->num_prompts; i++) {
  8397. put_stringz(s->pktout,
  8398. s->cur_prompt->prompts[i]->result);
  8399. }
  8400. s->pktout->minlen = 256;
  8401. ssh2_pkt_send(ssh, s->pktout);
  8402. /*
  8403. * Free the prompts structure from this iteration.
  8404. * If there's another, a new one will be allocated
  8405. * when we return to the top of this while loop.
  8406. */
  8407. free_prompts(s->cur_prompt);
  8408. /*
  8409. * Get the next packet in case it's another
  8410. * INFO_REQUEST.
  8411. */
  8412. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_userauth)) != NULL);
  8413. }
  8414. /*
  8415. * We should have SUCCESS or FAILURE now.
  8416. */
  8417. pq_push_front(&ssh->pq_ssh2_userauth, pktin);
  8418. } else if (s->can_passwd) {
  8419. /*
  8420. * Plain old password authentication.
  8421. */
  8422. int changereq_first_time; /* not live over crReturn */
  8423. ssh->pls.actx = SSH2_PKTCTX_PASSWORD;
  8424. #ifdef MPEXT
  8425. s->change_password = conf_get_int(ssh->conf, CONF_change_password);
  8426. if (s->change_password != 0)
  8427. {
  8428. s->password = dupstr("");
  8429. s->type = AUTH_TYPE_PASSWORD;
  8430. }
  8431. else
  8432. {
  8433. /* no indentation to ease merges */
  8434. #endif
  8435. s->cur_prompt = new_prompts(ssh->frontend);
  8436. s->cur_prompt->to_server = TRUE;
  8437. s->cur_prompt->name = dupstr("SSH password");
  8438. #ifdef _DEBUG
  8439. // To suppress CodeGuard warning
  8440. add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
  8441. #else
  8442. add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
  8443. #endif
  8444. ssh->username,
  8445. ssh->savedhost),
  8446. FALSE);
  8447. s->userpass_ret = get_userpass_input(s->cur_prompt, NULL);
  8448. while (1) {
  8449. while (s->userpass_ret < 0 &&
  8450. bufchain_size(&ssh->user_input) > 0)
  8451. s->userpass_ret = get_userpass_input(
  8452. s->cur_prompt, &ssh->user_input);
  8453. if (s->userpass_ret >= 0)
  8454. break;
  8455. ssh->send_ok = 1;
  8456. crReturnV;
  8457. ssh->send_ok = 0;
  8458. }
  8459. if (!s->userpass_ret) {
  8460. /*
  8461. * Failed to get responses. Terminate.
  8462. */
  8463. free_prompts(s->cur_prompt);
  8464. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  8465. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  8466. TRUE);
  8467. crStopV;
  8468. }
  8469. /*
  8470. * Squirrel away the password. (We may need it later if
  8471. * asked to change it.)
  8472. */
  8473. s->password = dupstr(s->cur_prompt->prompts[0]->result);
  8474. free_prompts(s->cur_prompt);
  8475. /*
  8476. * Send the password packet.
  8477. *
  8478. * We pad out the password packet to 256 bytes to make
  8479. * it harder for an attacker to find the length of the
  8480. * user's password.
  8481. *
  8482. * Anyone using a password longer than 256 bytes
  8483. * probably doesn't have much to worry about from
  8484. * people who find out how long their password is!
  8485. */
  8486. s->pktout = ssh_bpp_new_pktout(
  8487. ssh->bpp, SSH2_MSG_USERAUTH_REQUEST);
  8488. put_stringz(s->pktout, ssh->username);
  8489. put_stringz(s->pktout, "ssh-connection");
  8490. /* service requested */
  8491. put_stringz(s->pktout, "password");
  8492. put_bool(s->pktout, FALSE);
  8493. put_stringz(s->pktout, s->password);
  8494. s->pktout->minlen = 256;
  8495. ssh2_pkt_send(ssh, s->pktout);
  8496. logevent("Sent password");
  8497. s->type = AUTH_TYPE_PASSWORD;
  8498. /*
  8499. * Wait for next packet, in case it's a password change
  8500. * request.
  8501. */
  8502. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_userauth)) != NULL);
  8503. #ifdef MPEXT
  8504. }
  8505. #endif
  8506. changereq_first_time = TRUE;
  8507. while ((pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ)
  8508. #ifdef MPEXT
  8509. || (s->change_password != 0)
  8510. #endif
  8511. ) {
  8512. /*
  8513. * We're being asked for a new password
  8514. * (perhaps not for the first time).
  8515. * Loop until the server accepts it.
  8516. */
  8517. int got_new = FALSE; /* not live over crReturn */
  8518. ptrlen prompt; /* not live over crReturn */
  8519. #ifdef MPEXT
  8520. if (s->change_password == 0)
  8521. #endif
  8522. {
  8523. const char *msg;
  8524. if (changereq_first_time)
  8525. msg = "Server requested password change";
  8526. else
  8527. msg = "Server rejected new password";
  8528. logevent(msg);
  8529. c_write_str(ssh, msg);
  8530. c_write_str(ssh, "\r\n");
  8531. }
  8532. prompt = get_string(pktin);
  8533. #ifdef MPEXT
  8534. s->change_password = 0;
  8535. #endif
  8536. s->cur_prompt = new_prompts(ssh->frontend);
  8537. s->cur_prompt->to_server = TRUE;
  8538. s->cur_prompt->name = dupstr("New SSH password");
  8539. s->cur_prompt->instruction = mkstr(prompt);
  8540. s->cur_prompt->instr_reqd = TRUE;
  8541. /*
  8542. * There's no explicit requirement in the protocol
  8543. * for the "old" passwords in the original and
  8544. * password-change messages to be the same, and
  8545. * apparently some Cisco kit supports password change
  8546. * by the user entering a blank password originally
  8547. * and the real password subsequently, so,
  8548. * reluctantly, we prompt for the old password again.
  8549. *
  8550. * (On the other hand, some servers don't even bother
  8551. * to check this field.)
  8552. */
  8553. add_prompt(s->cur_prompt,
  8554. dupstr("Current password (blank for previously entered password): "),
  8555. FALSE);
  8556. add_prompt(s->cur_prompt, dupstr("Enter new password: "),
  8557. FALSE);
  8558. add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
  8559. FALSE);
  8560. /*
  8561. * Loop until the user manages to enter the same
  8562. * password twice.
  8563. */
  8564. while (!got_new) {
  8565. s->userpass_ret = get_userpass_input(
  8566. s->cur_prompt, NULL);
  8567. while (1) {
  8568. while (s->userpass_ret < 0 &&
  8569. bufchain_size(&ssh->user_input) > 0)
  8570. s->userpass_ret = get_userpass_input(
  8571. s->cur_prompt, &ssh->user_input);
  8572. if (s->userpass_ret >= 0)
  8573. break;
  8574. ssh->send_ok = 1;
  8575. crReturnV;
  8576. ssh->send_ok = 0;
  8577. }
  8578. if (!s->userpass_ret) {
  8579. /*
  8580. * Failed to get responses. Terminate.
  8581. */
  8582. /* burn the evidence */
  8583. free_prompts(s->cur_prompt);
  8584. smemclr(s->password, strlen(s->password));
  8585. sfree(s->password);
  8586. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  8587. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  8588. TRUE);
  8589. crStopV;
  8590. }
  8591. /*
  8592. * If the user specified a new original password
  8593. * (IYSWIM), overwrite any previously specified
  8594. * one.
  8595. * (A side effect is that the user doesn't have to
  8596. * re-enter it if they louse up the new password.)
  8597. */
  8598. if (s->cur_prompt->prompts[0]->result[0]) {
  8599. smemclr(s->password, strlen(s->password));
  8600. /* burn the evidence */
  8601. sfree(s->password);
  8602. s->password =
  8603. dupstr(s->cur_prompt->prompts[0]->result);
  8604. }
  8605. /*
  8606. * Check the two new passwords match.
  8607. */
  8608. got_new = (strcmp(s->cur_prompt->prompts[1]->result,
  8609. s->cur_prompt->prompts[2]->result)
  8610. == 0);
  8611. if (!got_new)
  8612. /* They don't. Silly user. */
  8613. c_write_str(ssh, "Passwords do not match\r\n");
  8614. }
  8615. /*
  8616. * Send the new password (along with the old one).
  8617. * (see above for padding rationale)
  8618. */
  8619. s->pktout = ssh_bpp_new_pktout(
  8620. ssh->bpp, SSH2_MSG_USERAUTH_REQUEST);
  8621. put_stringz(s->pktout, ssh->username);
  8622. put_stringz(s->pktout, "ssh-connection");
  8623. /* service requested */
  8624. put_stringz(s->pktout, "password");
  8625. put_bool(s->pktout, TRUE);
  8626. put_stringz(s->pktout, s->password);
  8627. put_stringz(s->pktout,
  8628. s->cur_prompt->prompts[1]->result);
  8629. free_prompts(s->cur_prompt);
  8630. s->pktout->minlen = 256;
  8631. ssh2_pkt_send(ssh, s->pktout);
  8632. logevent("Sent new password");
  8633. /*
  8634. * Now see what the server has to say about it.
  8635. * (If it's CHANGEREQ again, it's not happy with the
  8636. * new password.)
  8637. */
  8638. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_userauth)) != NULL);
  8639. changereq_first_time = FALSE;
  8640. }
  8641. /*
  8642. * We need to reexamine the current pktin at the top
  8643. * of the loop. Either:
  8644. * - we weren't asked to change password at all, in
  8645. * which case it's a SUCCESS or FAILURE with the
  8646. * usual meaning
  8647. * - we sent a new password, and the server was
  8648. * either OK with it (SUCCESS or FAILURE w/partial
  8649. * success) or unhappy with the _old_ password
  8650. * (FAILURE w/o partial success)
  8651. * In any of these cases, we go back to the top of
  8652. * the loop and start again.
  8653. */
  8654. pq_push_front(&ssh->pq_ssh2_userauth, pktin);
  8655. /*
  8656. * We don't need the old password any more, in any
  8657. * case. Burn the evidence.
  8658. */
  8659. smemclr(s->password, strlen(s->password));
  8660. sfree(s->password);
  8661. } else {
  8662. char *str = dupprintf(
  8663. "No supported authentication methods available"
  8664. " (server sent: %.*s)", PTRLEN_PRINTF(methods));
  8665. ssh_disconnect(ssh, str,
  8666. "No supported authentication methods available",
  8667. SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
  8668. FALSE);
  8669. sfree(str);
  8670. crStopV;
  8671. }
  8672. }
  8673. }
  8674. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
  8675. /* Clear up various bits and pieces from authentication. */
  8676. if (s->publickey_blob) {
  8677. sfree(s->publickey_algorithm);
  8678. strbuf_free(s->publickey_blob);
  8679. sfree(s->publickey_comment);
  8680. }
  8681. if (s->agent_response)
  8682. sfree(s->agent_response);
  8683. if (s->userauth_success) {
  8684. /*
  8685. * We've just received USERAUTH_SUCCESS, and we haven't sent
  8686. * any packets since. Signal the transport layer to consider
  8687. * doing an immediate rekey, if it has any reason to want to.
  8688. *
  8689. * (Relying on we_are_in is not sufficient. One of the reasons
  8690. * to do a post-userauth rekey is OpenSSH delayed compression;
  8691. * draft-miller-secsh-compression-delayed is quite clear that
  8692. * that triggers on USERAUTH_SUCCESS specifically, and
  8693. * we_are_in can become set for other reasons.)
  8694. */
  8695. ssh->rekey_reason = NULL; /* will be filled in later */
  8696. ssh->rekey_class = RK_POST_USERAUTH;
  8697. queue_idempotent_callback(&ssh->ssh2_transport_icb);
  8698. }
  8699. /*
  8700. * Finally, hand over to the connection layer.
  8701. */
  8702. do_ssh2_connection(ssh);
  8703. ssh->current_user_input_fn = ssh2_connection_input;
  8704. queue_idempotent_callback(&ssh->user_input_consumer);
  8705. crFinishV;
  8706. }
  8707. static void ssh2_userauth_input(Ssh ssh)
  8708. {
  8709. do_ssh2_userauth(ssh);
  8710. }
  8711. /*
  8712. * Handle the SSH-2 connection layer.
  8713. */
  8714. static void ssh2_msg_connection(Ssh ssh, PktIn *pktin)
  8715. {
  8716. pktin->refcount++; /* avoid packet being freed when we return */
  8717. pq_push(&ssh->pq_ssh2_connection, pktin);
  8718. queue_idempotent_callback(&ssh->ssh2_connection_icb);
  8719. }
  8720. static void ssh2_response_connection(struct ssh_channel *c,
  8721. PktIn *pktin, void *ctx)
  8722. {
  8723. if (pktin)
  8724. ssh2_msg_connection(c->ssh, pktin);
  8725. }
  8726. static void ssh2_connection_setup(Ssh ssh)
  8727. {
  8728. /*
  8729. * Initially, most connection-protocol messages go to the function
  8730. * that queues them for handling by the main do_ssh2_connection
  8731. * coroutine.
  8732. */
  8733. ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_connection;
  8734. ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_connection;
  8735. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_connection;
  8736. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
  8737. ssh2_msg_connection;
  8738. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_connection;
  8739. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_connection;
  8740. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_connection;
  8741. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_connection;
  8742. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_connection;
  8743. /*
  8744. * But a couple of them are easier to pass to special handler
  8745. * functions right from the start.
  8746. */
  8747. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
  8748. ssh2_msg_channel_window_adjust;
  8749. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
  8750. ssh2_msg_global_request;
  8751. /*
  8752. * Ensure our channels tree exists.
  8753. */
  8754. if (!ssh->channels)
  8755. ssh->channels = newtree234(ssh_channelcmp);
  8756. }
  8757. typedef struct mainchan {
  8758. Ssh ssh;
  8759. struct ssh_channel *c;
  8760. Channel chan;
  8761. } mainchan;
  8762. static void mainchan_free(Channel *chan);
  8763. static void mainchan_open_confirmation(Channel *chan);
  8764. static void mainchan_open_failure(Channel *chan, const char *errtext);
  8765. static int mainchan_send(Channel *chan, int is_stderr, const void *, int);
  8766. static void mainchan_send_eof(Channel *chan);
  8767. static void mainchan_set_input_wanted(Channel *chan, int wanted);
  8768. static char *mainchan_log_close_msg(Channel *chan);
  8769. static const struct ChannelVtable mainchan_channelvt = {
  8770. mainchan_free,
  8771. mainchan_open_confirmation,
  8772. mainchan_open_failure,
  8773. mainchan_send,
  8774. mainchan_send_eof,
  8775. mainchan_set_input_wanted,
  8776. mainchan_log_close_msg,
  8777. chan_no_eager_close,
  8778. };
  8779. static mainchan *mainchan_new(Ssh ssh)
  8780. {
  8781. mainchan *mc = snew(mainchan);
  8782. mc->ssh = ssh;
  8783. mc->c = NULL;
  8784. mc->chan.vt = &mainchan_channelvt;
  8785. mc->chan.initial_fixed_window_size = 0;
  8786. return mc;
  8787. }
  8788. static void mainchan_free(Channel *chan)
  8789. {
  8790. pinitassert(chan->vt == &mainchan_channelvt);
  8791. mainchan *mc = FROMFIELD(chan, mainchan, chan);
  8792. mc->ssh->mainchan = NULL;
  8793. sfree(mc);
  8794. }
  8795. static void mainchan_open_confirmation(Channel *chan)
  8796. {
  8797. assert(FALSE && "OPEN_CONFIRMATION for main channel should be "
  8798. "handled by connection layer setup");
  8799. }
  8800. static void mainchan_open_failure(Channel *chan, const char *errtext)
  8801. {
  8802. assert(FALSE && "OPEN_FAILURE for main channel should be "
  8803. "handled by connection layer setup");
  8804. }
  8805. static int mainchan_send(Channel *chan, int is_stderr,
  8806. const void *data, int length)
  8807. {
  8808. pinitassert(chan->vt == &mainchan_channelvt);
  8809. mainchan *mc = FROMFIELD(chan, mainchan, chan);
  8810. return from_backend(mc->ssh->frontend, is_stderr, data, length);
  8811. }
  8812. static void mainchan_send_eof(Channel *chan)
  8813. {
  8814. pinitassert(chan->vt == &mainchan_channelvt);
  8815. mainchan *mc = FROMFIELD(chan, mainchan, chan);
  8816. if (!mc->ssh->sent_console_eof &&
  8817. (from_backend_eof(mc->ssh->frontend) || mc->ssh->got_pty)) {
  8818. /*
  8819. * Either from_backend_eof told us that the front end wants us
  8820. * to close the outgoing side of the connection as soon as we
  8821. * see EOF from the far end, or else we've unilaterally
  8822. * decided to do that because we've allocated a remote pty and
  8823. * hence EOF isn't a particularly meaningful concept.
  8824. */
  8825. sshfwd_write_eof(mc->c);
  8826. }
  8827. mc->ssh->sent_console_eof = TRUE;
  8828. }
  8829. static void mainchan_set_input_wanted(Channel *chan, int wanted)
  8830. {
  8831. pinitassert(chan->vt == &mainchan_channelvt);
  8832. mainchan *mc = FROMFIELD(chan, mainchan, chan);
  8833. /*
  8834. * This is the main channel of the SSH session, i.e. the one tied
  8835. * to the standard input (or GUI) of the primary SSH client user
  8836. * interface. So ssh->send_ok is how we control whether we're
  8837. * reading from that input.
  8838. */
  8839. mc->ssh->send_ok = wanted;
  8840. }
  8841. static char *mainchan_log_close_msg(Channel *chan)
  8842. {
  8843. return dupstr("Main session channel closed");
  8844. }
  8845. static void do_ssh2_connection(void *vctx)
  8846. {
  8847. Ssh ssh = (Ssh)vctx;
  8848. PktIn *pktin;
  8849. struct do_ssh2_connection_state {
  8850. int crLine;
  8851. PktOut *pktout;
  8852. };
  8853. crState(do_ssh2_connection_state);
  8854. crBeginState;
  8855. /*
  8856. * Initialise our dispatch table entries. Normally this will have
  8857. * been done as a side effect of USERAUTH_SUCCESS, but in some
  8858. * cases, it might not (e.g. if we bypassed userauth, or if we're
  8859. * running the bare-connection protocol).
  8860. */
  8861. ssh2_connection_setup(ssh);
  8862. /*
  8863. * Create the main session channel.
  8864. */
  8865. if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
  8866. ssh->mainchan = NULL;
  8867. } else {
  8868. mainchan *mc = mainchan_new(ssh);
  8869. if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
  8870. /*
  8871. * Just start a direct-tcpip channel and use it as the main
  8872. * channel.
  8873. */
  8874. ssh->mainchan = mc->c = ssh_send_port_open
  8875. (ssh, conf_get_str(ssh->conf, CONF_ssh_nc_host),
  8876. conf_get_int(ssh->conf, CONF_ssh_nc_port),
  8877. "main channel", &mc->chan);
  8878. ssh->ncmode = TRUE;
  8879. } else {
  8880. ssh->mainchan = mc->c = snew(struct ssh_channel);
  8881. ssh->mainchan->ssh = ssh;
  8882. ssh_channel_init(ssh->mainchan);
  8883. ssh->mainchan->chan = &mc->chan;
  8884. s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
  8885. logevent("Opening session as main channel");
  8886. ssh2_pkt_send(ssh, s->pktout);
  8887. ssh->ncmode = FALSE;
  8888. }
  8889. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_connection)) != NULL);
  8890. if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
  8891. pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE) {
  8892. bombout(("Server sent strange packet %d in response to main "
  8893. "channel open request", pktin->type));
  8894. crStopV;
  8895. }
  8896. if (get_uint32(pktin) != ssh->mainchan->localid) {
  8897. bombout(("Server's response to main channel open cited wrong"
  8898. " channel number"));
  8899. crStopV;
  8900. }
  8901. if (pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
  8902. char *errtext = ssh2_channel_open_failure_error_text(pktin);
  8903. bombout(("Server refused to open main channel: %s", errtext));
  8904. sfree(errtext);
  8905. crStopV;
  8906. }
  8907. ssh->mainchan->remoteid = get_uint32(pktin);
  8908. ssh->mainchan->halfopen = FALSE;
  8909. ssh->mainchan->v.v2.remwindow = get_uint32(pktin);
  8910. ssh->mainchan->v.v2.remmaxpkt = get_uint32(pktin);
  8911. update_specials_menu(ssh->frontend);
  8912. logevent("Opened main channel");
  8913. }
  8914. /*
  8915. * Now we have a channel, make dispatch table entries for
  8916. * general channel-based messages.
  8917. */
  8918. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
  8919. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
  8920. ssh2_msg_channel_data;
  8921. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
  8922. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
  8923. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
  8924. ssh2_msg_channel_open_confirmation;
  8925. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
  8926. ssh2_msg_channel_open_failure;
  8927. ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
  8928. ssh2_msg_channel_request;
  8929. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
  8930. ssh2_msg_channel_open;
  8931. ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
  8932. ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
  8933. /*
  8934. * Put our current pending packet queue back to the front of
  8935. * pq_full, and then schedule a callback to re-process those
  8936. * packets (if any). That way, anything already in our queue that
  8937. * matches any of the table entries we've just modified will go to
  8938. * the right handler function, and won't come here to confuse us.
  8939. */
  8940. if (pq_empty_on_to_front_of(&ssh->pq_ssh2_connection, &ssh->pq_full))
  8941. queue_idempotent_callback(&ssh->pq_full_consumer);
  8942. /*
  8943. * Now the connection protocol is properly up and running, with
  8944. * all those dispatch table entries, so it's safe to let
  8945. * downstreams start trying to open extra channels through us.
  8946. */
  8947. if (ssh->connshare)
  8948. share_activate(ssh->connshare, ssh->v_s);
  8949. if (ssh->mainchan && ssh_is_simple(ssh)) {
  8950. /*
  8951. * This message indicates to the server that we promise
  8952. * not to try to run any other channel in parallel with
  8953. * this one, so it's safe for it to advertise a very large
  8954. * window and leave the flow control to TCP.
  8955. */
  8956. s->pktout = ssh2_chanreq_init(ssh->mainchan,
  8957. "[email protected]",
  8958. NULL, NULL);
  8959. ssh2_pkt_send(ssh, s->pktout);
  8960. }
  8961. /*
  8962. * Enable port forwardings.
  8963. */
  8964. ssh_setup_portfwd(ssh, ssh->conf);
  8965. if (ssh->mainchan && !ssh->ncmode) {
  8966. /*
  8967. * Send the CHANNEL_REQUESTS for the main session channel.
  8968. * Each one is handled by its own little asynchronous
  8969. * co-routine.
  8970. */
  8971. /* Potentially enable X11 forwarding. */
  8972. if (conf_get_int(ssh->conf, CONF_x11_forward)) {
  8973. ssh->x11disp =
  8974. x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
  8975. ssh->conf);
  8976. if (!ssh->x11disp) {
  8977. /* FIXME: return an error message from x11_setup_display */
  8978. logevent("X11 forwarding not enabled: unable to"
  8979. " initialise X display");
  8980. } else {
  8981. ssh->x11auth = x11_invent_fake_auth
  8982. (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
  8983. ssh->x11auth->disp = ssh->x11disp;
  8984. ssh2_setup_x11(ssh->mainchan, NULL, NULL);
  8985. }
  8986. }
  8987. /* Potentially enable agent forwarding. */
  8988. if (ssh_agent_forwarding_permitted(ssh))
  8989. ssh2_setup_agent(ssh->mainchan, NULL, NULL);
  8990. /* Now allocate a pty for the session. */
  8991. if (!conf_get_int(ssh->conf, CONF_nopty))
  8992. ssh2_setup_pty(ssh->mainchan, NULL, NULL);
  8993. /* Send environment variables. */
  8994. ssh2_setup_env(ssh->mainchan, NULL, NULL);
  8995. /*
  8996. * Start a shell or a remote command. We may have to attempt
  8997. * this twice if the config data has provided a second choice
  8998. * of command.
  8999. */
  9000. while (1) {
  9001. int subsys;
  9002. char *cmd;
  9003. if (ssh->fallback_cmd) {
  9004. subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
  9005. cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
  9006. } else {
  9007. subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
  9008. cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
  9009. }
  9010. if (subsys) {
  9011. s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
  9012. ssh2_response_connection, NULL);
  9013. put_stringz(s->pktout, cmd);
  9014. } else if (*cmd) {
  9015. s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
  9016. ssh2_response_connection, NULL);
  9017. put_stringz(s->pktout, cmd);
  9018. } else {
  9019. s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
  9020. ssh2_response_connection, NULL);
  9021. }
  9022. ssh2_pkt_send(ssh, s->pktout);
  9023. crMaybeWaitUntilV((pktin = pq_pop(&ssh->pq_ssh2_connection)) != NULL);
  9024. if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
  9025. if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
  9026. bombout(("Unexpected response to shell/command request:"
  9027. " packet type %d", pktin->type));
  9028. crStopV;
  9029. }
  9030. /*
  9031. * We failed to start the command. If this is the
  9032. * fallback command, we really are finished; if it's
  9033. * not, and if the fallback command exists, try falling
  9034. * back to it before complaining.
  9035. */
  9036. if (!ssh->fallback_cmd &&
  9037. (*conf_get_str(ssh->conf, CONF_remote_cmd2)
  9038. #ifdef MPEXT
  9039. ||
  9040. conf_get_int(ssh->conf, CONF_force_remote_cmd2)
  9041. #endif
  9042. )
  9043. ) {
  9044. logevent("Primary command failed; attempting fallback");
  9045. ssh->fallback_cmd = TRUE;
  9046. continue;
  9047. }
  9048. bombout(("Server refused to start a shell/command"));
  9049. crStopV;
  9050. } else {
  9051. logevent("Started a shell/command");
  9052. }
  9053. break;
  9054. }
  9055. } else {
  9056. ssh->editing = ssh->echoing = TRUE;
  9057. }
  9058. ssh->state = SSH_STATE_SESSION;
  9059. if (ssh->size_needed)
  9060. backend_size(&ssh->backend, ssh->term_width, ssh->term_height);
  9061. if (ssh->eof_needed)
  9062. backend_special(&ssh->backend, TS_EOF);
  9063. /*
  9064. * Transfer data!
  9065. */
  9066. if (ssh->ldisc)
  9067. ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
  9068. if (ssh->mainchan)
  9069. ssh->send_ok = 1;
  9070. while (1) {
  9071. if ((pktin = pq_pop(&ssh->pq_ssh2_connection)) != NULL) {
  9072. /*
  9073. * _All_ the connection-layer packets we expect to
  9074. * receive are now handled by the dispatch table.
  9075. * Anything that reaches here must be bogus.
  9076. */
  9077. bombout(("Strange packet received: type %d", pktin->type));
  9078. crStopV;
  9079. }
  9080. while (ssh->mainchan && bufchain_size(&ssh->user_input) > 0) {
  9081. /*
  9082. * Add user input to the main channel's buffer.
  9083. */
  9084. void *data;
  9085. int len;
  9086. bufchain_prefix(&ssh->user_input, &data, &len);
  9087. ssh_send_channel_data(ssh->mainchan, data, len);
  9088. bufchain_consume(&ssh->user_input, len);
  9089. }
  9090. crReturnV;
  9091. }
  9092. crFinishV;
  9093. }
  9094. static void ssh2_connection_input(Ssh ssh)
  9095. {
  9096. do_ssh2_connection(ssh);
  9097. }
  9098. /*
  9099. * Handlers for SSH-2 messages that might arrive at any moment.
  9100. */
  9101. static void ssh2_msg_disconnect(Ssh ssh, PktIn *pktin)
  9102. {
  9103. /* log reason code in disconnect message */
  9104. char *buf;
  9105. ptrlen msg;
  9106. int reason;
  9107. reason = get_uint32(pktin);
  9108. msg = get_string(pktin);
  9109. if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
  9110. buf = dupprintf("Received disconnect message (%s)",
  9111. ssh2_disconnect_reasons[reason]);
  9112. } else {
  9113. buf = dupprintf("Received disconnect message (unknown"
  9114. " type %d)", reason);
  9115. }
  9116. logevent(buf);
  9117. sfree(buf);
  9118. buf = dupprintf("Disconnection message text: %.*s", PTRLEN_PRINTF(msg));
  9119. logevent(buf);
  9120. bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
  9121. reason,
  9122. (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
  9123. ssh2_disconnect_reasons[reason] : "unknown", PTRLEN_PRINTF(msg)));
  9124. sfree(buf);
  9125. }
  9126. static void ssh2_msg_debug(Ssh ssh, PktIn *pktin)
  9127. {
  9128. /* log the debug message */
  9129. ptrlen msg;
  9130. /* XXX maybe we should actually take notice of the return value */
  9131. get_bool(pktin);
  9132. msg = get_string(pktin);
  9133. logeventf(ssh, "Remote debug message: %.*s", PTRLEN_PRINTF(msg));
  9134. }
  9135. static void ssh2_msg_transport(Ssh ssh, PktIn *pktin)
  9136. {
  9137. pktin->refcount++; /* avoid packet being freed when we return */
  9138. pq_push(&ssh->pq_ssh2_transport, pktin);
  9139. queue_idempotent_callback(&ssh->ssh2_transport_icb);
  9140. }
  9141. /*
  9142. * Called if we receive a packet that isn't allowed by the protocol.
  9143. * This only applies to packets whose meaning PuTTY understands.
  9144. * Entirely unknown packets are handled below.
  9145. */
  9146. static void ssh2_msg_unexpected(Ssh ssh, PktIn *pktin)
  9147. {
  9148. char *buf = dupprintf("Server protocol violation: unexpected %s packet",
  9149. ssh2_pkt_type(ssh->pls.kctx, ssh->pls.actx,
  9150. pktin->type));
  9151. ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
  9152. sfree(buf);
  9153. }
  9154. static void ssh2_msg_something_unimplemented(Ssh ssh, PktIn *pktin)
  9155. {
  9156. PktOut *pktout;
  9157. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_UNIMPLEMENTED);
  9158. put_uint32(pktout, pktin->sequence);
  9159. /*
  9160. * UNIMPLEMENTED messages MUST appear in the same order as the
  9161. * messages they respond to. Hence, never queue them.
  9162. */
  9163. ssh_pkt_write(ssh, pktout);
  9164. }
  9165. /*
  9166. * Handle the top-level SSH-2 protocol.
  9167. */
  9168. static void ssh2_protocol_setup(Ssh ssh)
  9169. {
  9170. int i;
  9171. ssh->bpp = ssh2_bpp_new();
  9172. #ifndef NO_GSSAPI
  9173. /* Load and pick the highest GSS library on the preference list. */
  9174. if (!ssh->gsslibs)
  9175. ssh->gsslibs = ssh_gss_setup(ssh->conf, ssh->frontend); // MPEXT
  9176. ssh->gsslib = NULL;
  9177. if (ssh->gsslibs->nlibraries > 0) {
  9178. int i, j;
  9179. for (i = 0; i < ngsslibs; i++) {
  9180. int want_id = conf_get_int_int(ssh->conf,
  9181. CONF_ssh_gsslist, i);
  9182. for (j = 0; j < ssh->gsslibs->nlibraries; j++)
  9183. if (ssh->gsslibs->libraries[j].id == want_id) {
  9184. ssh->gsslib = &ssh->gsslibs->libraries[j];
  9185. goto got_gsslib; /* double break */
  9186. }
  9187. }
  9188. got_gsslib:
  9189. /*
  9190. * We always expect to have found something in
  9191. * the above loop: we only came here if there
  9192. * was at least one viable GSS library, and the
  9193. * preference list should always mention
  9194. * everything and only change the order.
  9195. */
  9196. assert(ssh->gsslib);
  9197. }
  9198. #endif
  9199. /*
  9200. * Most messages cause SSH2_MSG_UNIMPLEMENTED.
  9201. */
  9202. for (i = 0; i < SSH_MAX_MSG; i++)
  9203. ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
  9204. /*
  9205. * Initially, we only accept transport messages (and a few generic
  9206. * ones). do_ssh2_userauth and do_ssh2_connection will each add
  9207. * more when they start. Messages that are understood but not
  9208. * currently acceptable go to ssh2_msg_unexpected.
  9209. */
  9210. ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
  9211. ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
  9212. ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
  9213. ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
  9214. ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
  9215. ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
  9216. ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
  9217. /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
  9218. /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
  9219. ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
  9220. ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
  9221. ssh->packet_dispatch[SSH2_MSG_KEXGSS_GROUP] = ssh2_msg_transport;
  9222. ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
  9223. ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
  9224. ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
  9225. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
  9226. ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
  9227. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
  9228. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
  9229. ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
  9230. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
  9231. ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
  9232. ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
  9233. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
  9234. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
  9235. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
  9236. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
  9237. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
  9238. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
  9239. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
  9240. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
  9241. ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
  9242. ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
  9243. ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
  9244. /*
  9245. * These messages have a special handler from the start.
  9246. */
  9247. ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
  9248. ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
  9249. ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
  9250. }
  9251. static void ssh2_bare_connection_protocol_setup(Ssh ssh)
  9252. {
  9253. int i;
  9254. ssh->bpp = ssh2_bare_bpp_new();
  9255. /*
  9256. * Most messages cause SSH2_MSG_UNIMPLEMENTED.
  9257. */
  9258. for (i = 0; i < SSH_MAX_MSG; i++)
  9259. ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
  9260. /*
  9261. * Initially, we set all ssh-connection messages to 'unexpected';
  9262. * do_ssh2_connection will fill things in properly. We also handle
  9263. * a couple of messages from the transport protocol which aren't
  9264. * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
  9265. * DISCONNECT).
  9266. */
  9267. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
  9268. ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
  9269. ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
  9270. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
  9271. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
  9272. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
  9273. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
  9274. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
  9275. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
  9276. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
  9277. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
  9278. ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
  9279. ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
  9280. ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
  9281. ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
  9282. /*
  9283. * These messages have a special handler from the start.
  9284. */
  9285. ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
  9286. ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
  9287. ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
  9288. }
  9289. #ifndef NO_GSSAPI
  9290. static PktOut *ssh2_gss_authpacket(Ssh ssh, Ssh_gss_ctx gss_ctx,
  9291. const char *authtype)
  9292. {
  9293. strbuf *sb;
  9294. PktOut *p;
  9295. Ssh_gss_buf buf;
  9296. Ssh_gss_buf mic;
  9297. /*
  9298. * The mic is computed over the session id + intended
  9299. * USERAUTH_REQUEST packet.
  9300. */
  9301. sb = strbuf_new();
  9302. put_string(sb, ssh->v2_session_id, ssh->v2_session_id_len);
  9303. put_byte(sb, SSH2_MSG_USERAUTH_REQUEST);
  9304. put_stringz(sb, ssh->username);
  9305. put_stringz(sb, "ssh-connection");
  9306. put_stringz(sb, authtype);
  9307. /* Compute the mic */
  9308. buf.value = sb->s;
  9309. buf.length = sb->len;
  9310. ssh->gsslib->get_mic(ssh->gsslib, gss_ctx, &buf, &mic);
  9311. strbuf_free(sb);
  9312. /* Now we can build the real packet */
  9313. if (strcmp(authtype, "gssapi-with-mic") == 0) {
  9314. p = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_USERAUTH_GSSAPI_MIC);
  9315. } else {
  9316. p = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_USERAUTH_REQUEST);
  9317. put_stringz(p, ssh->username);
  9318. put_stringz(p, "ssh-connection");
  9319. put_stringz(p, authtype);
  9320. }
  9321. put_string(p, mic.value, mic.length);
  9322. return p;
  9323. }
  9324. /*
  9325. * This is called at the beginning of each SSH rekey to determine whether we are
  9326. * GSS capable, and if we did GSS key exchange, and are delegating credentials,
  9327. * it is also called periodically to determine whether we should rekey in order
  9328. * to delegate (more) fresh credentials. This is called "credential cascading".
  9329. *
  9330. * On Windows, with SSPI, we may not get the credential expiration, as Windows
  9331. * automatically renews from cached passwords, so the credential effectively
  9332. * never expires. Since we still want to cascade when the local TGT is updated,
  9333. * we use the expiration of a newly obtained context as a proxy for the
  9334. * expiration of the TGT.
  9335. */
  9336. static void ssh2_gss_update(Ssh ssh, int definitely_rekeying)
  9337. {
  9338. int gss_stat;
  9339. time_t gss_cred_expiry;
  9340. unsigned long mins;
  9341. Ssh_gss_buf gss_sndtok;
  9342. Ssh_gss_buf gss_rcvtok;
  9343. Ssh_gss_ctx gss_ctx;
  9344. ssh->gss_status = 0;
  9345. /*
  9346. * Nothing to do if no GSSAPI libraries are configured or GSSAPI auth is not
  9347. * enabled.
  9348. */
  9349. if (ssh->gsslibs->nlibraries == 0)
  9350. return;
  9351. if (!conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
  9352. !conf_get_int(ssh->conf, CONF_try_gssapi_kex))
  9353. return;
  9354. /* Import server name and cache it */
  9355. if (ssh->gss_srv_name == GSS_C_NO_NAME) {
  9356. gss_stat = ssh->gsslib->import_name(ssh->gsslib,
  9357. ssh->fullhostname,
  9358. &ssh->gss_srv_name);
  9359. if (gss_stat != SSH_GSS_OK) {
  9360. if (gss_stat == SSH_GSS_BAD_HOST_NAME)
  9361. logevent("GSSAPI import name failed -"
  9362. " Bad service name; won't use GSS key exchange");
  9363. else
  9364. logevent("GSSAPI import name failed;"
  9365. " won't use GSS key exchange");
  9366. return;
  9367. }
  9368. }
  9369. /*
  9370. * Do we (still) have credentials? Capture the credential expiration when
  9371. * available
  9372. */
  9373. gss_stat = ssh->gsslib->acquire_cred(ssh->gsslib,
  9374. &gss_ctx,
  9375. &gss_cred_expiry);
  9376. if (gss_stat != SSH_GSS_OK)
  9377. return;
  9378. SSH_GSS_CLEAR_BUF(&gss_sndtok);
  9379. SSH_GSS_CLEAR_BUF(&gss_rcvtok);
  9380. /*
  9381. * When acquire_cred yields no useful expiration, get a proxy for the cred
  9382. * expiration from the context expiration.
  9383. */
  9384. gss_stat = ssh->gsslib->init_sec_context(
  9385. ssh->gsslib, &gss_ctx, ssh->gss_srv_name,
  9386. 0 /* don't delegate */, &gss_rcvtok, &gss_sndtok,
  9387. (gss_cred_expiry == GSS_NO_EXPIRATION ? &gss_cred_expiry : NULL),
  9388. &ssh->gss_ctxt_lifetime);
  9389. /* This context was for testing only. */
  9390. if (gss_ctx)
  9391. ssh->gsslib->release_cred(ssh->gsslib, &gss_ctx);
  9392. if (gss_stat != SSH_GSS_OK &&
  9393. gss_stat != SSH_GSS_S_CONTINUE_NEEDED) {
  9394. /*
  9395. * No point in verbosely interrupting the user to tell them we
  9396. * couldn't get GSS credentials, if this was only a check
  9397. * between key exchanges to see if fresh ones were available.
  9398. * When we do do a rekey, this message (if displayed) will
  9399. * appear among the standard rekey blurb, but when we're not,
  9400. * it shouldn't pop up all the time regardless.
  9401. */
  9402. if (definitely_rekeying)
  9403. logeventf(ssh, "No GSSAPI security context available");
  9404. return;
  9405. }
  9406. if (gss_sndtok.length)
  9407. ssh->gsslib->free_tok(ssh->gsslib, &gss_sndtok);
  9408. ssh->gss_status |= GSS_KEX_CAPABLE;
  9409. /*
  9410. * When rekeying to cascade, avoding doing this too close to the context
  9411. * expiration time, since the key exchange might fail.
  9412. */
  9413. if (ssh->gss_ctxt_lifetime < MIN_CTXT_LIFETIME)
  9414. ssh->gss_status |= GSS_CTXT_MAYFAIL;
  9415. /*
  9416. * If we're not delegating credentials, rekeying is not used to refresh
  9417. * them. We must avoid setting GSS_CRED_UPDATED or GSS_CTXT_EXPIRES when
  9418. * credential delegation is disabled.
  9419. */
  9420. if (conf_get_int(ssh->conf, CONF_gssapifwd) == 0)
  9421. return;
  9422. if (ssh->gss_cred_expiry != GSS_NO_EXPIRATION &&
  9423. difftime(gss_cred_expiry, ssh->gss_cred_expiry) > 0)
  9424. ssh->gss_status |= GSS_CRED_UPDATED;
  9425. mins = conf_get_int(ssh->conf, CONF_gssapirekey);
  9426. mins = rekey_mins(mins, GSS_DEF_REKEY_MINS);
  9427. if (mins > 0 && ssh->gss_ctxt_lifetime <= mins * 60)
  9428. ssh->gss_status |= GSS_CTXT_EXPIRES;
  9429. }
  9430. #endif
  9431. /*
  9432. * The rekey_time is zero except when re-configuring.
  9433. *
  9434. * We either schedule the next timer and return 0, or return 1 to run the
  9435. * callback now, which will call us again to re-schedule on completion.
  9436. */
  9437. static int ssh2_timer_update(Ssh ssh, unsigned long rekey_time)
  9438. {
  9439. unsigned long mins;
  9440. unsigned long ticks;
  9441. mins = conf_get_int(ssh->conf, CONF_ssh_rekey_time);
  9442. mins = rekey_mins(mins, 60);
  9443. ticks = mins * 60 * TICKSPERSEC;
  9444. /* Handle change from previous setting */
  9445. if (rekey_time != 0 && rekey_time != mins) {
  9446. unsigned long next;
  9447. unsigned long now = GETTICKCOUNT();
  9448. mins = rekey_time;
  9449. ticks = mins * 60 * TICKSPERSEC;
  9450. next = ssh->last_rekey + ticks;
  9451. /* If overdue, caller will rekey synchronously now */
  9452. if (now - ssh->last_rekey > ticks)
  9453. return 1;
  9454. ticks = next - now;
  9455. }
  9456. #ifndef NO_GSSAPI
  9457. if (ssh->gss_kex_used) {
  9458. /*
  9459. * If we've used GSSAPI key exchange, then we should
  9460. * periodically check whether we need to do another one to
  9461. * pass new credentials to the server.
  9462. */
  9463. unsigned long gssmins;
  9464. /* Check cascade conditions more frequently if configured */
  9465. gssmins = conf_get_int(ssh->conf, CONF_gssapirekey);
  9466. gssmins = rekey_mins(gssmins, GSS_DEF_REKEY_MINS);
  9467. if (gssmins > 0) {
  9468. if (gssmins < mins)
  9469. ticks = (mins = gssmins) * 60 * TICKSPERSEC;
  9470. if ((ssh->gss_status & GSS_KEX_CAPABLE) != 0) {
  9471. /*
  9472. * Run next timer even sooner if it would otherwise be too close
  9473. * to the context expiration time
  9474. */
  9475. if ((ssh->gss_status & GSS_CTXT_EXPIRES) == 0 &&
  9476. ssh->gss_ctxt_lifetime - mins * 60 < 2 * MIN_CTXT_LIFETIME)
  9477. ticks -= 2 * MIN_CTXT_LIFETIME * TICKSPERSEC;
  9478. }
  9479. }
  9480. }
  9481. #endif
  9482. /* Schedule the next timer */
  9483. ssh->next_rekey = schedule_timer(ticks, ssh2_timer, ssh);
  9484. return 0;
  9485. }
  9486. static void ssh2_timer(void *ctx, unsigned long now)
  9487. {
  9488. Ssh ssh = (Ssh)ctx;
  9489. unsigned long mins;
  9490. unsigned long ticks;
  9491. if (ssh->state == SSH_STATE_CLOSED ||
  9492. ssh->kex_in_progress ||
  9493. ssh->bare_connection ||
  9494. #ifdef MPEXT
  9495. // our call from call_ssh_timer() does not guarantee the `now` to be exactly as scheduled
  9496. now < ssh->next_rekey)
  9497. #else
  9498. now != ssh->next_rekey)
  9499. #endif
  9500. return;
  9501. mins = conf_get_int(ssh->conf, CONF_ssh_rekey_time);
  9502. mins = rekey_mins(mins, 60);
  9503. if (mins == 0)
  9504. return;
  9505. /* Rekey if enough time has elapsed */
  9506. ticks = mins * 60 * TICKSPERSEC;
  9507. if (now - ssh->last_rekey > ticks - 30*TICKSPERSEC) {
  9508. ssh->rekey_reason = "timeout";
  9509. ssh->rekey_class = RK_NORMAL;
  9510. queue_idempotent_callback(&ssh->ssh2_transport_icb);
  9511. return;
  9512. }
  9513. #ifndef NO_GSSAPI
  9514. /*
  9515. * Rekey now if we have a new cred or context expires this cycle, but not if
  9516. * this is unsafe.
  9517. */
  9518. if (conf_get_int(ssh->conf, CONF_gssapirekey)) {
  9519. ssh2_gss_update(ssh, FALSE);
  9520. if ((ssh->gss_status & GSS_KEX_CAPABLE) != 0 &&
  9521. (ssh->gss_status & GSS_CTXT_MAYFAIL) == 0 &&
  9522. (ssh->gss_status & (GSS_CRED_UPDATED|GSS_CTXT_EXPIRES)) != 0) {
  9523. ssh->rekey_reason = "GSS credentials updated";
  9524. ssh->rekey_class = RK_GSS_UPDATE;
  9525. queue_idempotent_callback(&ssh->ssh2_transport_icb);
  9526. return;
  9527. }
  9528. }
  9529. #endif
  9530. /* Try again later. */
  9531. (void) ssh2_timer_update(ssh, 0);
  9532. }
  9533. static void ssh2_general_packet_processing(Ssh ssh, PktIn *pktin)
  9534. {
  9535. ssh->incoming_data_size += pktin->encrypted_len;
  9536. if (!ssh->kex_in_progress &&
  9537. ssh->max_data_size != 0 &&
  9538. ssh->incoming_data_size > ssh->max_data_size) {
  9539. ssh->rekey_reason = "too much data received";
  9540. ssh->rekey_class = RK_NORMAL;
  9541. queue_idempotent_callback(&ssh->ssh2_transport_icb);
  9542. }
  9543. }
  9544. static void ssh_cache_conf_values(Ssh ssh)
  9545. {
  9546. ssh->pls.omit_passwords = conf_get_int(ssh->conf, CONF_logomitpass);
  9547. ssh->pls.omit_data = conf_get_int(ssh->conf, CONF_logomitdata);
  9548. }
  9549. /*
  9550. * Called to set up the connection.
  9551. *
  9552. * Returns an error message, or NULL on success.
  9553. */
  9554. static const char *ssh_init(Frontend *frontend, Backend **backend_handle,
  9555. Conf *conf,
  9556. const char *host, int port, char **realhost,
  9557. int nodelay, int keepalive)
  9558. {
  9559. const char *p;
  9560. Ssh ssh;
  9561. ssh = snew(struct ssh_tag);
  9562. ssh->conf = conf_copy(conf);
  9563. ssh_cache_conf_values(ssh);
  9564. ssh->version = 0; /* when not ready yet */
  9565. ssh->s = NULL;
  9566. ssh->kex = NULL;
  9567. ssh->kex_ctx = NULL;
  9568. ssh->hostkey_alg = NULL;
  9569. ssh->hostkey_str = NULL;
  9570. ssh->exitcode = -1;
  9571. ssh->close_expected = FALSE;
  9572. ssh->clean_exit = FALSE;
  9573. ssh->disconnect_message_seen = FALSE;
  9574. ssh->state = SSH_STATE_PREPACKET;
  9575. ssh->size_needed = FALSE;
  9576. ssh->eof_needed = FALSE;
  9577. ssh->ldisc = NULL;
  9578. ssh->logctx = NULL;
  9579. ssh->fallback_cmd = 0;
  9580. ssh->pls.kctx = SSH2_PKTCTX_NOKEX;
  9581. ssh->pls.actx = SSH2_PKTCTX_NOAUTH;
  9582. ssh->x11disp = NULL;
  9583. ssh->x11auth = NULL;
  9584. ssh->x11authtree = newtree234(x11_authcmp);
  9585. ssh->v2_cbc_ignore_workaround = FALSE;
  9586. ssh->bpp = NULL;
  9587. ssh->do_ssh1_connection_crstate = 0;
  9588. ssh->do_ssh_init_state = NULL;
  9589. ssh->do_ssh_connection_init_state = NULL;
  9590. ssh->do_ssh1_login_state = NULL;
  9591. ssh->do_ssh2_transport_state = NULL;
  9592. ssh->do_ssh2_userauth_state = NULL;
  9593. ssh->do_ssh2_connection_state = NULL;
  9594. bufchain_init(&ssh->incoming_data);
  9595. ssh->incoming_data_seen_eof = FALSE;
  9596. ssh->incoming_data_eof_message = NULL;
  9597. ssh->incoming_data_consumer.fn = ssh_process_incoming_data;
  9598. ssh->incoming_data_consumer.ctx = ssh;
  9599. ssh->incoming_data_consumer.queued = FALSE;
  9600. pq_init(&ssh->pq_full);
  9601. ssh->pq_full_consumer.fn = ssh_process_pq_full;
  9602. ssh->pq_full_consumer.ctx = ssh;
  9603. ssh->pq_full_consumer.queued = FALSE;
  9604. pq_init(&ssh->pq_ssh1_login);
  9605. ssh->ssh1_login_icb.fn = do_ssh1_login;
  9606. ssh->ssh1_login_icb.ctx = ssh;
  9607. ssh->ssh1_login_icb.queued = FALSE;
  9608. pq_init(&ssh->pq_ssh1_connection);
  9609. ssh->ssh1_connection_icb.fn = do_ssh1_connection;
  9610. ssh->ssh1_connection_icb.ctx = ssh;
  9611. ssh->ssh1_connection_icb.queued = FALSE;
  9612. pq_init(&ssh->pq_ssh2_transport);
  9613. ssh->ssh2_transport_icb.fn = do_ssh2_transport;
  9614. ssh->ssh2_transport_icb.ctx = ssh;
  9615. ssh->ssh2_transport_icb.queued = FALSE;
  9616. pq_init(&ssh->pq_ssh2_userauth);
  9617. ssh->ssh2_userauth_icb.fn = do_ssh2_userauth;
  9618. ssh->ssh2_userauth_icb.ctx = ssh;
  9619. ssh->ssh2_userauth_icb.queued = FALSE;
  9620. pq_init(&ssh->pq_ssh2_connection);
  9621. ssh->ssh2_connection_icb.fn = do_ssh2_connection;
  9622. ssh->ssh2_connection_icb.ctx = ssh;
  9623. ssh->ssh2_connection_icb.queued = FALSE;
  9624. bufchain_init(&ssh->user_input);
  9625. ssh->user_input_consumer.fn = ssh_process_user_input;
  9626. ssh->user_input_consumer.ctx = ssh;
  9627. ssh->user_input_consumer.queued = FALSE;
  9628. bufchain_init(&ssh->outgoing_data);
  9629. ssh->outgoing_data_sender.fn = ssh_send_outgoing_data;
  9630. ssh->outgoing_data_sender.ctx = ssh;
  9631. ssh->outgoing_data_sender.queued = FALSE;
  9632. ssh->current_user_input_fn = NULL;
  9633. ssh->rekey_reason = NULL;
  9634. ssh->rekey_class = RK_INITIAL;
  9635. ssh->v_c = NULL;
  9636. ssh->v_s = NULL;
  9637. ssh->mainchan = NULL;
  9638. ssh->throttled_all = 0;
  9639. ssh->v1_stdout_throttling = 0;
  9640. ssh->queue = NULL;
  9641. ssh->queuelen = ssh->queuesize = 0;
  9642. ssh->queueing = FALSE;
  9643. ssh->qhead = ssh->qtail = NULL;
  9644. ssh->deferred_rekey_reason = NULL;
  9645. ssh->frozen = FALSE;
  9646. ssh->username = NULL;
  9647. ssh->sent_console_eof = FALSE;
  9648. ssh->got_pty = FALSE;
  9649. ssh->bare_connection = FALSE;
  9650. ssh->X11_fwd_enabled = FALSE;
  9651. ssh->connshare = NULL;
  9652. ssh->attempting_connshare = FALSE;
  9653. ssh->session_started = FALSE;
  9654. ssh->specials = NULL;
  9655. ssh->n_uncert_hostkeys = 0;
  9656. ssh->cross_certifying = FALSE;
  9657. #ifndef NO_GSSAPI
  9658. ssh->gss_cred_expiry = GSS_NO_EXPIRATION;
  9659. ssh->gss_srv_name = GSS_C_NO_NAME;
  9660. ssh->gss_ctx = NULL;
  9661. ssh_init_transient_hostkey_store(ssh);
  9662. #endif
  9663. ssh->gss_kex_used = FALSE;
  9664. ssh->backend.vt = &ssh_backend;
  9665. *backend_handle = &ssh->backend;
  9666. ssh->frontend = frontend;
  9667. ssh->term_width = conf_get_int(ssh->conf, CONF_width);
  9668. ssh->term_height = conf_get_int(ssh->conf, CONF_height);
  9669. ssh->channels = NULL;
  9670. ssh->rportfwds = NULL;
  9671. ssh->portfwds = NULL;
  9672. ssh->send_ok = 0;
  9673. ssh->editing = 0;
  9674. ssh->echoing = 0;
  9675. ssh->conn_throttle_count = 0;
  9676. ssh->overall_bufsize = 0;
  9677. ssh->fallback_cmd = 0;
  9678. ssh->general_packet_processing = NULL;
  9679. ssh->pinger = NULL;
  9680. ssh->incoming_data_size = ssh->outgoing_data_size = 0L;
  9681. ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
  9682. CONF_ssh_rekey_data));
  9683. ssh->kex_in_progress = FALSE;
  9684. ssh->auth_agent_query = NULL;
  9685. #ifndef NO_GSSAPI
  9686. ssh->gsslibs = NULL;
  9687. #endif
  9688. random_ref(); /* do this now - may be needed by sharing setup code */
  9689. ssh->need_random_unref = TRUE;
  9690. p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
  9691. if (p != NULL) {
  9692. /* Call random_unref now instead of waiting until the caller
  9693. * frees this useless Ssh object, in case the caller is
  9694. * impatient and just exits without bothering, in which case
  9695. * the random seed won't be re-saved. */
  9696. ssh->need_random_unref = FALSE;
  9697. random_unref();
  9698. return p;
  9699. }
  9700. return NULL;
  9701. }
  9702. static void ssh_free(Backend *be)
  9703. {
  9704. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  9705. struct ssh_channel *c;
  9706. struct ssh_rportfwd *pf;
  9707. struct X11FakeAuth *auth;
  9708. int need_random_unref;
  9709. if (ssh->kex_ctx)
  9710. dh_cleanup(ssh->kex_ctx);
  9711. sfree(ssh->savedhost);
  9712. while (ssh->queuelen-- > 0)
  9713. ssh_free_pktout(ssh->queue[ssh->queuelen]);
  9714. sfree(ssh->queue);
  9715. while (ssh->qhead) {
  9716. struct queued_handler *qh = ssh->qhead;
  9717. ssh->qhead = qh->next;
  9718. sfree(qh);
  9719. }
  9720. ssh->qhead = ssh->qtail = NULL;
  9721. if (ssh->channels) {
  9722. while ((c = delpos234(ssh->channels, 0)) != NULL) {
  9723. ssh_channel_close_local(c, NULL);
  9724. if (ssh->version == 2) {
  9725. struct outstanding_channel_request *ocr, *nocr;
  9726. ocr = c->v.v2.chanreq_head;
  9727. while (ocr) {
  9728. ocr->handler(c, NULL, ocr->ctx);
  9729. nocr = ocr->next;
  9730. sfree(ocr);
  9731. ocr = nocr;
  9732. }
  9733. bufchain_clear(&c->v.v2.outbuffer);
  9734. }
  9735. sfree(c);
  9736. }
  9737. freetree234(ssh->channels);
  9738. ssh->channels = NULL;
  9739. }
  9740. if (ssh->connshare) {
  9741. sharestate_free(ssh->connshare);
  9742. ssh->connshare = NULL;
  9743. }
  9744. if (ssh->rportfwds) {
  9745. while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
  9746. free_rportfwd(pf);
  9747. freetree234(ssh->rportfwds);
  9748. ssh->rportfwds = NULL;
  9749. }
  9750. if (ssh->x11disp)
  9751. x11_free_display(ssh->x11disp);
  9752. while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
  9753. x11_free_fake_auth(auth);
  9754. if (ssh->bpp)
  9755. ssh_bpp_free(ssh->bpp);
  9756. freetree234(ssh->x11authtree);
  9757. sfree(ssh->do_ssh_init_state);
  9758. sfree(ssh->do_ssh1_login_state);
  9759. sfree(ssh->do_ssh2_transport_state);
  9760. sfree(ssh->do_ssh2_userauth_state);
  9761. sfree(ssh->do_ssh2_connection_state);
  9762. bufchain_clear(&ssh->incoming_data);
  9763. bufchain_clear(&ssh->outgoing_data);
  9764. sfree(ssh->incoming_data_eof_message);
  9765. pq_clear(&ssh->pq_full);
  9766. pq_clear(&ssh->pq_ssh1_login);
  9767. pq_clear(&ssh->pq_ssh1_connection);
  9768. pq_clear(&ssh->pq_ssh2_transport);
  9769. pq_clear(&ssh->pq_ssh2_userauth);
  9770. pq_clear(&ssh->pq_ssh2_connection);
  9771. bufchain_clear(&ssh->user_input);
  9772. sfree(ssh->v_c);
  9773. sfree(ssh->v_s);
  9774. sfree(ssh->fullhostname);
  9775. sfree(ssh->hostkey_str);
  9776. sfree(ssh->specials);
  9777. if (ssh->s)
  9778. ssh_do_close(ssh, TRUE);
  9779. expire_timer_context(ssh);
  9780. if (ssh->pinger)
  9781. pinger_free(ssh->pinger);
  9782. sfree(ssh->username);
  9783. conf_free(ssh->conf);
  9784. if (ssh->auth_agent_query)
  9785. agent_cancel_query(ssh->auth_agent_query);
  9786. #ifndef NO_GSSAPI
  9787. if (ssh->gss_srv_name)
  9788. ssh->gsslib->release_name(ssh->gsslib, &ssh->gss_srv_name);
  9789. if (ssh->gss_ctx != NULL)
  9790. ssh->gsslib->release_cred(ssh->gsslib, &ssh->gss_ctx);
  9791. if (ssh->gsslibs)
  9792. ssh_gss_cleanup(ssh->gsslibs);
  9793. ssh_cleanup_transient_hostkey_store(ssh);
  9794. #endif
  9795. need_random_unref = ssh->need_random_unref;
  9796. sfree(ssh);
  9797. if (need_random_unref)
  9798. random_unref();
  9799. }
  9800. /*
  9801. * Reconfigure the SSH backend.
  9802. */
  9803. static void ssh_reconfig(Backend *be, Conf *conf)
  9804. {
  9805. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  9806. const char *rekeying = NULL;
  9807. int rekey_mandatory = FALSE;
  9808. unsigned long old_max_data_size;
  9809. int i, rekey_time;
  9810. pinger_reconfig(ssh->pinger, ssh->conf, conf);
  9811. if (ssh->portfwds)
  9812. ssh_setup_portfwd(ssh, conf);
  9813. rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
  9814. if (ssh2_timer_update(ssh, rekey_mins(rekey_time, 60)))
  9815. rekeying = "timeout shortened";
  9816. old_max_data_size = ssh->max_data_size;
  9817. ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
  9818. CONF_ssh_rekey_data));
  9819. if (old_max_data_size != ssh->max_data_size &&
  9820. ssh->max_data_size != 0) {
  9821. if (ssh->outgoing_data_size > ssh->max_data_size ||
  9822. ssh->incoming_data_size > ssh->max_data_size)
  9823. rekeying = "data limit lowered";
  9824. }
  9825. if (conf_get_int(ssh->conf, CONF_compression) !=
  9826. conf_get_int(conf, CONF_compression)) {
  9827. rekeying = "compression setting changed";
  9828. rekey_mandatory = TRUE;
  9829. }
  9830. for (i = 0; i < CIPHER_MAX; i++)
  9831. if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
  9832. conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
  9833. rekeying = "cipher settings changed";
  9834. rekey_mandatory = TRUE;
  9835. }
  9836. if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
  9837. conf_get_int(conf, CONF_ssh2_des_cbc)) {
  9838. rekeying = "cipher settings changed";
  9839. rekey_mandatory = TRUE;
  9840. }
  9841. conf_free(ssh->conf);
  9842. ssh->conf = conf_copy(conf);
  9843. ssh_cache_conf_values(ssh);
  9844. if (!ssh->bare_connection && rekeying) {
  9845. if (!ssh->kex_in_progress) {
  9846. ssh->rekey_reason = rekeying;
  9847. ssh->rekey_class = RK_NORMAL;
  9848. queue_idempotent_callback(&ssh->ssh2_transport_icb);
  9849. } else if (rekey_mandatory) {
  9850. ssh->deferred_rekey_reason = rekeying;
  9851. }
  9852. }
  9853. }
  9854. /*
  9855. * Called to send data down the SSH connection.
  9856. */
  9857. static int ssh_send(Backend *be, const char *buf, int len)
  9858. {
  9859. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  9860. if (ssh == NULL || ssh->s == NULL)
  9861. return 0;
  9862. bufchain_add(&ssh->user_input, buf, len);
  9863. queue_idempotent_callback(&ssh->user_input_consumer);
  9864. return backend_sendbuffer(&ssh->backend);
  9865. }
  9866. /*
  9867. * Called to query the current amount of buffered stdin data.
  9868. */
  9869. static int ssh_sendbuffer(Backend *be)
  9870. {
  9871. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  9872. int override_value;
  9873. if (ssh == NULL || ssh->s == NULL)
  9874. return 0;
  9875. /*
  9876. * If the SSH socket itself has backed up, add the total backup
  9877. * size on that to any individual buffer on the stdin channel.
  9878. */
  9879. override_value = 0;
  9880. if (ssh->throttled_all)
  9881. override_value = ssh->overall_bufsize;
  9882. if (ssh->version == 1) {
  9883. return override_value;
  9884. } else if (ssh->version == 2) {
  9885. if (!ssh->mainchan)
  9886. return override_value;
  9887. else
  9888. return (override_value +
  9889. bufchain_size(&ssh->mainchan->v.v2.outbuffer));
  9890. }
  9891. return 0;
  9892. }
  9893. /*
  9894. * Called to set the size of the window from SSH's POV.
  9895. */
  9896. static void ssh_size(Backend *be, int width, int height)
  9897. {
  9898. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  9899. PktOut *pktout;
  9900. ssh->term_width = width;
  9901. ssh->term_height = height;
  9902. switch (ssh->state) {
  9903. case SSH_STATE_BEFORE_SIZE:
  9904. case SSH_STATE_PREPACKET:
  9905. case SSH_STATE_CLOSED:
  9906. break; /* do nothing */
  9907. case SSH_STATE_INTERMED:
  9908. ssh->size_needed = TRUE; /* buffer for later */
  9909. break;
  9910. case SSH_STATE_SESSION:
  9911. if (!conf_get_int(ssh->conf, CONF_nopty)) {
  9912. if (ssh->version == 1) {
  9913. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_WINDOW_SIZE);
  9914. put_uint32(pktout, ssh->term_height);
  9915. put_uint32(pktout, ssh->term_width);
  9916. put_uint32(pktout, 0);
  9917. put_uint32(pktout, 0);
  9918. ssh_pkt_write(ssh, pktout);
  9919. } else if (ssh->mainchan) {
  9920. pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
  9921. NULL, NULL);
  9922. put_uint32(pktout, ssh->term_width);
  9923. put_uint32(pktout, ssh->term_height);
  9924. put_uint32(pktout, 0);
  9925. put_uint32(pktout, 0);
  9926. ssh2_pkt_send(ssh, pktout);
  9927. }
  9928. }
  9929. break;
  9930. }
  9931. }
  9932. /*
  9933. * Return a list of the special codes that make sense in this
  9934. * protocol.
  9935. */
  9936. static const struct telnet_special *ssh_get_specials(Backend *be)
  9937. {
  9938. static const struct telnet_special ssh1_ignore_special[] = {
  9939. {"IGNORE message", TS_NOP}
  9940. };
  9941. static const struct telnet_special ssh2_ignore_special[] = {
  9942. {"IGNORE message", TS_NOP},
  9943. };
  9944. static const struct telnet_special ssh2_rekey_special[] = {
  9945. {"Repeat key exchange", TS_REKEY},
  9946. };
  9947. static const struct telnet_special ssh2_session_specials[] = {
  9948. {NULL, TS_SEP},
  9949. {"Break", TS_BRK},
  9950. /* These are the signal names defined by RFC 4254.
  9951. * They include all the ISO C signals, but are a subset of the POSIX
  9952. * required signals. */
  9953. {"SIGINT (Interrupt)", TS_SIGINT},
  9954. {"SIGTERM (Terminate)", TS_SIGTERM},
  9955. {"SIGKILL (Kill)", TS_SIGKILL},
  9956. {"SIGQUIT (Quit)", TS_SIGQUIT},
  9957. {"SIGHUP (Hangup)", TS_SIGHUP},
  9958. {"More signals", TS_SUBMENU},
  9959. {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
  9960. {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
  9961. {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
  9962. {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
  9963. {NULL, TS_EXITMENU}
  9964. };
  9965. static const struct telnet_special specials_end[] = {
  9966. {NULL, TS_EXITMENU}
  9967. };
  9968. struct telnet_special *specials = NULL;
  9969. int nspecials = 0, specialsize = 0;
  9970. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  9971. sfree(ssh->specials);
  9972. #define ADD_SPECIALS(name) do \
  9973. { \
  9974. int len = lenof(name); \
  9975. if (nspecials + len > specialsize) { \
  9976. specialsize = (nspecials + len) * 5 / 4 + 32; \
  9977. specials = sresize(specials, specialsize, struct telnet_special); \
  9978. } \
  9979. memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
  9980. nspecials += len; \
  9981. } while (0)
  9982. if (ssh->version == 1) {
  9983. /* Don't bother offering IGNORE if we've decided the remote
  9984. * won't cope with it, since we wouldn't bother sending it if
  9985. * asked anyway. */
  9986. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
  9987. ADD_SPECIALS(ssh1_ignore_special);
  9988. } else if (ssh->version == 2) {
  9989. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
  9990. ADD_SPECIALS(ssh2_ignore_special);
  9991. if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
  9992. ADD_SPECIALS(ssh2_rekey_special);
  9993. if (ssh->mainchan)
  9994. ADD_SPECIALS(ssh2_session_specials);
  9995. if (ssh->n_uncert_hostkeys) {
  9996. static const struct telnet_special uncert_start[] = {
  9997. {NULL, TS_SEP},
  9998. {"Cache new host key type", TS_SUBMENU},
  9999. };
  10000. static const struct telnet_special uncert_end[] = {
  10001. {NULL, TS_EXITMENU},
  10002. };
  10003. int i;
  10004. ADD_SPECIALS(uncert_start);
  10005. for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
  10006. struct telnet_special uncert[1];
  10007. const ssh_keyalg *alg =
  10008. hostkey_algs[ssh->uncert_hostkeys[i]].alg;
  10009. uncert[0].name = alg->ssh_id;
  10010. uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
  10011. ADD_SPECIALS(uncert);
  10012. }
  10013. ADD_SPECIALS(uncert_end);
  10014. }
  10015. } /* else we're not ready yet */
  10016. if (nspecials)
  10017. ADD_SPECIALS(specials_end);
  10018. ssh->specials = specials;
  10019. if (nspecials) {
  10020. return specials;
  10021. } else {
  10022. return NULL;
  10023. }
  10024. #undef ADD_SPECIALS
  10025. }
  10026. /*
  10027. * Send special codes. TS_EOF is useful for `plink', so you
  10028. * can send an EOF and collect resulting output (e.g. `plink
  10029. * hostname sort').
  10030. */
  10031. static void ssh_special(Backend *be, Telnet_Special code)
  10032. {
  10033. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10034. PktOut *pktout;
  10035. if (code == TS_EOF) {
  10036. if (ssh->state != SSH_STATE_SESSION) {
  10037. /*
  10038. * Buffer the EOF in case we are pre-SESSION, so we can
  10039. * send it as soon as we reach SESSION.
  10040. */
  10041. if (code == TS_EOF)
  10042. ssh->eof_needed = TRUE;
  10043. return;
  10044. }
  10045. if (ssh->version == 1) {
  10046. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH1_CMSG_EOF);
  10047. ssh_pkt_write(ssh, pktout);
  10048. } else if (ssh->mainchan) {
  10049. sshfwd_write_eof(ssh->mainchan);
  10050. ssh->send_ok = 0; /* now stop trying to read from stdin */
  10051. }
  10052. logevent("Sent EOF message");
  10053. } else if (code == TS_PING || code == TS_NOP) {
  10054. if (ssh->state == SSH_STATE_CLOSED
  10055. || ssh->state == SSH_STATE_PREPACKET) return;
  10056. if (ssh->version == 1) {
  10057. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
  10058. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH1_MSG_IGNORE);
  10059. put_stringz(pktout, "");
  10060. ssh_pkt_write(ssh, pktout);
  10061. }
  10062. } else {
  10063. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
  10064. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH2_MSG_IGNORE);
  10065. put_stringz(pktout, "");
  10066. ssh_pkt_write(ssh, pktout);
  10067. }
  10068. }
  10069. } else if (code == TS_REKEY) {
  10070. if (!ssh->kex_in_progress && !ssh->bare_connection &&
  10071. ssh->version == 2) {
  10072. ssh->rekey_reason = "at user request";
  10073. ssh->rekey_class = RK_NORMAL;
  10074. queue_idempotent_callback(&ssh->ssh2_transport_icb);
  10075. }
  10076. } else if (code >= TS_LOCALSTART) {
  10077. ssh->hostkey_alg = hostkey_algs[code - TS_LOCALSTART].alg;
  10078. ssh->cross_certifying = TRUE;
  10079. if (!ssh->kex_in_progress && !ssh->bare_connection &&
  10080. ssh->version == 2) {
  10081. ssh->rekey_reason = "cross-certifying new host key";
  10082. ssh->rekey_class = RK_NORMAL;
  10083. queue_idempotent_callback(&ssh->ssh2_transport_icb);
  10084. }
  10085. } else if (code == TS_BRK) {
  10086. if (ssh->state == SSH_STATE_CLOSED
  10087. || ssh->state == SSH_STATE_PREPACKET) return;
  10088. if (ssh->version == 1) {
  10089. logevent("Unable to send BREAK signal in SSH-1");
  10090. } else if (ssh->mainchan) {
  10091. pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
  10092. put_uint32(pktout, 0); /* default break length */
  10093. ssh2_pkt_send(ssh, pktout);
  10094. }
  10095. } else {
  10096. /* Is is a POSIX signal? */
  10097. const char *signame = NULL;
  10098. if (code == TS_SIGABRT) signame = "ABRT";
  10099. if (code == TS_SIGALRM) signame = "ALRM";
  10100. if (code == TS_SIGFPE) signame = "FPE";
  10101. if (code == TS_SIGHUP) signame = "HUP";
  10102. if (code == TS_SIGILL) signame = "ILL";
  10103. if (code == TS_SIGINT) signame = "INT";
  10104. if (code == TS_SIGKILL) signame = "KILL";
  10105. if (code == TS_SIGPIPE) signame = "PIPE";
  10106. if (code == TS_SIGQUIT) signame = "QUIT";
  10107. if (code == TS_SIGSEGV) signame = "SEGV";
  10108. if (code == TS_SIGTERM) signame = "TERM";
  10109. if (code == TS_SIGUSR1) signame = "USR1";
  10110. if (code == TS_SIGUSR2) signame = "USR2";
  10111. /* The SSH-2 protocol does in principle support arbitrary named
  10112. * signals, including signame@domain, but we don't support those. */
  10113. if (signame) {
  10114. /* It's a signal. */
  10115. if (ssh->version == 2 && ssh->mainchan) {
  10116. pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
  10117. put_stringz(pktout, signame);
  10118. ssh2_pkt_send(ssh, pktout);
  10119. logeventf(ssh, "Sent signal SIG%s", signame);
  10120. }
  10121. } else {
  10122. /* Never heard of it. Do nothing */
  10123. }
  10124. }
  10125. }
  10126. unsigned ssh_alloc_sharing_channel(Ssh ssh, ssh_sharing_connstate *connstate)
  10127. {
  10128. struct ssh_channel *c;
  10129. c = snew(struct ssh_channel);
  10130. c->ssh = ssh;
  10131. ssh_channel_init(c);
  10132. c->chan = NULL;
  10133. c->sharectx = connstate;
  10134. return c->localid;
  10135. }
  10136. void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
  10137. {
  10138. struct ssh_channel *c;
  10139. c = find234(ssh->channels, &localid, ssh_channelfind);
  10140. if (c)
  10141. ssh_channel_destroy(c);
  10142. }
  10143. void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
  10144. const void *data, int datalen,
  10145. const char *additional_log_text)
  10146. {
  10147. PktOut *pkt;
  10148. pkt = ssh_bpp_new_pktout(ssh->bpp, type);
  10149. pkt->downstream_id = id;
  10150. pkt->additional_log_text = additional_log_text;
  10151. put_data(pkt, data, datalen);
  10152. ssh2_pkt_send(ssh, pkt);
  10153. }
  10154. /*
  10155. * This is called when stdout/stderr (the entity to which
  10156. * from_backend sends data) manages to clear some backlog.
  10157. */
  10158. static void ssh_unthrottle(Backend *be, int bufsize)
  10159. {
  10160. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10161. if (ssh->version == 1) {
  10162. if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
  10163. ssh->v1_stdout_throttling = 0;
  10164. ssh_throttle_conn(ssh, -1);
  10165. }
  10166. } else {
  10167. if (ssh->mainchan)
  10168. ssh_channel_unthrottle(ssh->mainchan, bufsize);
  10169. }
  10170. /*
  10171. * Now process any SSH connection data that was stashed in our
  10172. * queue while we were frozen.
  10173. */
  10174. queue_idempotent_callback(&ssh->incoming_data_consumer);
  10175. }
  10176. struct ssh_channel *ssh_send_port_open(Ssh ssh, const char *hostname, int port,
  10177. const char *org, Channel *chan)
  10178. {
  10179. struct ssh_channel *c = snew(struct ssh_channel);
  10180. PktOut *pktout;
  10181. c->ssh = ssh;
  10182. ssh_channel_init(c);
  10183. c->halfopen = TRUE;
  10184. c->chan = chan;
  10185. logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
  10186. if (ssh->version == 1) {
  10187. pktout = ssh_bpp_new_pktout(ssh->bpp, SSH1_MSG_PORT_OPEN);
  10188. put_uint32(pktout, c->localid);
  10189. put_stringz(pktout, hostname);
  10190. put_uint32(pktout, port);
  10191. /* originator string would go here, but we didn't specify
  10192. * SSH_PROTOFLAG_HOST_IN_FWD_OPEN */
  10193. ssh_pkt_write(ssh, pktout);
  10194. } else {
  10195. pktout = ssh2_chanopen_init(c, "direct-tcpip");
  10196. {
  10197. char *trimmed_host = host_strduptrim(hostname);
  10198. put_stringz(pktout, trimmed_host);
  10199. sfree(trimmed_host);
  10200. }
  10201. put_uint32(pktout, port);
  10202. /*
  10203. * We make up values for the originator data; partly it's
  10204. * too much hassle to keep track, and partly I'm not
  10205. * convinced the server should be told details like that
  10206. * about my local network configuration.
  10207. * The "originator IP address" is syntactically a numeric
  10208. * IP address, and some servers (e.g., Tectia) get upset
  10209. * if it doesn't match this syntax.
  10210. */
  10211. put_stringz(pktout, "0.0.0.0");
  10212. put_uint32(pktout, 0);
  10213. ssh2_pkt_send(ssh, pktout);
  10214. }
  10215. return c;
  10216. }
  10217. static int ssh_connected(Backend *be)
  10218. {
  10219. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10220. return ssh->s != NULL;
  10221. }
  10222. static int ssh_sendok(Backend *be)
  10223. {
  10224. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10225. return ssh->send_ok;
  10226. }
  10227. static int ssh_ldisc(Backend *be, int option)
  10228. {
  10229. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10230. if (option == LD_ECHO)
  10231. return ssh->echoing;
  10232. if (option == LD_EDIT)
  10233. return ssh->editing;
  10234. return FALSE;
  10235. }
  10236. static void ssh_provide_ldisc(Backend *be, Ldisc *ldisc)
  10237. {
  10238. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10239. ssh->ldisc = ldisc;
  10240. }
  10241. static void ssh_provide_logctx(Backend *be, LogContext *logctx)
  10242. {
  10243. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10244. ssh->logctx = logctx;
  10245. }
  10246. static int ssh_return_exitcode(Backend *be)
  10247. {
  10248. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10249. if (ssh->s != NULL)
  10250. return -1;
  10251. else
  10252. return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
  10253. }
  10254. /*
  10255. * cfg_info for SSH is the protocol running in this session.
  10256. * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
  10257. * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
  10258. */
  10259. static int ssh_cfg_info(Backend *be)
  10260. {
  10261. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10262. if (ssh->version == 0)
  10263. return 0; /* don't know yet */
  10264. else if (ssh->bare_connection)
  10265. return -1;
  10266. else
  10267. return ssh->version;
  10268. }
  10269. /*
  10270. * Gross hack: pscp will try to start SFTP but fall back to scp1 if
  10271. * that fails. This variable is the means by which scp.c can reach
  10272. * into the SSH code and find out which one it got.
  10273. */
  10274. extern int ssh_fallback_cmd(Backend *be)
  10275. {
  10276. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10277. return ssh->fallback_cmd;
  10278. }
  10279. const struct Backend_vtable ssh_backend = {
  10280. ssh_init,
  10281. ssh_free,
  10282. ssh_reconfig,
  10283. ssh_send,
  10284. ssh_sendbuffer,
  10285. ssh_size,
  10286. ssh_special,
  10287. ssh_get_specials,
  10288. ssh_connected,
  10289. ssh_return_exitcode,
  10290. ssh_sendok,
  10291. ssh_ldisc,
  10292. ssh_provide_ldisc,
  10293. ssh_provide_logctx,
  10294. ssh_unthrottle,
  10295. ssh_cfg_info,
  10296. ssh_test_for_upstream,
  10297. "ssh",
  10298. PROT_SSH,
  10299. 22
  10300. };
  10301. #ifdef MPEXT
  10302. #include "puttyexp.h"
  10303. int is_ssh(Plug plug)
  10304. {
  10305. return (*plug)->closing == ssh_closing;
  10306. }
  10307. void call_ssh_timer(Backend * be)
  10308. {
  10309. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10310. if (ssh->version == 2)
  10311. {
  10312. ssh2_timer(ssh, GETTICKCOUNT());
  10313. }
  10314. }
  10315. int get_ssh_version(Backend * be)
  10316. {
  10317. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10318. return ssh->version;
  10319. }
  10320. void * get_ssh_frontend(Plug plug)
  10321. {
  10322. return FROMFIELD(plug, struct ssh_tag, plugvt)->frontend;
  10323. }
  10324. int get_ssh1_compressing(Backend * be)
  10325. {
  10326. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10327. return ssh1_bpp_get_compressing(ssh->bpp);
  10328. }
  10329. const struct ssh_cipher * get_cipher(Backend * be)
  10330. {
  10331. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10332. return ssh1_bpp_get_cipher(ssh->bpp);
  10333. }
  10334. const struct ssh2_cipher * get_cscipher(Backend * be)
  10335. {
  10336. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10337. return ssh2_bpp_get_cscipher(ssh->bpp);
  10338. }
  10339. const struct ssh2_cipher * get_sccipher(Backend * be)
  10340. {
  10341. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10342. return ssh2_bpp_get_sccipher(ssh->bpp);
  10343. }
  10344. const struct ssh_compress * get_cscomp(Backend * be)
  10345. {
  10346. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10347. return ssh2_bpp_get_cscomp(ssh->bpp);
  10348. }
  10349. const struct ssh_compress * get_sccomp(Backend * be)
  10350. {
  10351. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10352. return ssh2_bpp_get_sccomp(ssh->bpp);
  10353. }
  10354. int get_ssh_state_closed(Backend * be)
  10355. {
  10356. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10357. return ssh->state == SSH_STATE_CLOSED;
  10358. }
  10359. int get_ssh_state_session(Backend * be)
  10360. {
  10361. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10362. return ssh->state == SSH_STATE_SESSION;
  10363. }
  10364. const unsigned int * ssh2_remmaxpkt(Backend * be)
  10365. {
  10366. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10367. return &ssh->mainchan->v.v2.remmaxpkt;
  10368. }
  10369. const unsigned int * ssh2_remwindow(Backend * be)
  10370. {
  10371. Ssh ssh = FROMFIELD(be, struct ssh_tag, backend);
  10372. return &ssh->mainchan->v.v2.remwindow;
  10373. }
  10374. void md5checksum(const char * buffer, int len, unsigned char output[16])
  10375. {
  10376. MD5Simple(buffer, len, output);
  10377. }
  10378. void get_hostkey_algs(int * count, cp_ssh_keyalg * SignKeys)
  10379. {
  10380. int i;
  10381. assert(lenof(hostkey_algs) <= *count);
  10382. *count = lenof(hostkey_algs);
  10383. for (i = 0; i < *count; i++)
  10384. {
  10385. *(SignKeys + i) = hostkey_algs[i].alg;
  10386. }
  10387. }
  10388. void get_macs(int * count, const struct ssh_mac *** amacs)
  10389. {
  10390. *amacs = macs;
  10391. *count = lenof(macs);
  10392. }
  10393. #endif