ssh.c 384 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227
  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 "ssh.h"
  15. #ifndef NO_GSSAPI
  16. #include "sshgssc.h"
  17. #include "sshgss.h"
  18. #endif
  19. #ifndef FALSE
  20. #define FALSE 0
  21. #endif
  22. #ifndef TRUE
  23. #define TRUE 1
  24. #endif
  25. /*
  26. * Packet type contexts, so that ssh2_pkt_type can correctly decode
  27. * the ambiguous type numbers back into the correct type strings.
  28. */
  29. typedef enum {
  30. SSH2_PKTCTX_NOKEX,
  31. SSH2_PKTCTX_DHGROUP,
  32. SSH2_PKTCTX_DHGEX,
  33. SSH2_PKTCTX_ECDHKEX,
  34. SSH2_PKTCTX_RSAKEX
  35. } Pkt_KCtx;
  36. typedef enum {
  37. SSH2_PKTCTX_NOAUTH,
  38. SSH2_PKTCTX_PUBLICKEY,
  39. SSH2_PKTCTX_PASSWORD,
  40. SSH2_PKTCTX_GSSAPI,
  41. SSH2_PKTCTX_KBDINTER
  42. } Pkt_ACtx;
  43. static const char *const ssh2_disconnect_reasons[] = {
  44. NULL,
  45. "host not allowed to connect",
  46. "protocol error",
  47. "key exchange failed",
  48. "host authentication failed",
  49. "MAC error",
  50. "compression error",
  51. "service not available",
  52. "protocol version not supported",
  53. "host key not verifiable",
  54. "connection lost",
  55. "by application",
  56. "too many connections",
  57. "auth cancelled by user",
  58. "no more auth methods available",
  59. "illegal user name",
  60. };
  61. /*
  62. * Various remote-bug flags.
  63. */
  64. #define BUG_CHOKES_ON_SSH1_IGNORE 1
  65. #define BUG_SSH2_HMAC 2
  66. #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
  67. #define BUG_CHOKES_ON_RSA 8
  68. #define BUG_SSH2_RSA_PADDING 16
  69. #define BUG_SSH2_DERIVEKEY 32
  70. #define BUG_SSH2_REKEY 64
  71. #define BUG_SSH2_PK_SESSIONID 128
  72. #define BUG_SSH2_MAXPKT 256
  73. #define BUG_CHOKES_ON_SSH2_IGNORE 512
  74. #define BUG_CHOKES_ON_WINADJ 1024
  75. #define BUG_SENDS_LATE_REQUEST_REPLY 2048
  76. #define BUG_SSH2_OLDGEX 4096
  77. #define DH_MIN_SIZE 1024
  78. #define DH_MAX_SIZE 8192
  79. /*
  80. * Codes for terminal modes.
  81. * Most of these are the same in SSH-1 and SSH-2.
  82. * This list is derived from RFC 4254 and
  83. * SSH-1 RFC-1.2.31.
  84. */
  85. static const struct ssh_ttymode {
  86. const char* const mode;
  87. int opcode;
  88. enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
  89. } ssh_ttymodes[] = {
  90. /* "V" prefix discarded for special characters relative to SSH specs */
  91. { "INTR", 1, TTY_OP_CHAR },
  92. { "QUIT", 2, TTY_OP_CHAR },
  93. { "ERASE", 3, TTY_OP_CHAR },
  94. { "KILL", 4, TTY_OP_CHAR },
  95. { "EOF", 5, TTY_OP_CHAR },
  96. { "EOL", 6, TTY_OP_CHAR },
  97. { "EOL2", 7, TTY_OP_CHAR },
  98. { "START", 8, TTY_OP_CHAR },
  99. { "STOP", 9, TTY_OP_CHAR },
  100. { "SUSP", 10, TTY_OP_CHAR },
  101. { "DSUSP", 11, TTY_OP_CHAR },
  102. { "REPRINT", 12, TTY_OP_CHAR },
  103. { "WERASE", 13, TTY_OP_CHAR },
  104. { "LNEXT", 14, TTY_OP_CHAR },
  105. { "FLUSH", 15, TTY_OP_CHAR },
  106. { "SWTCH", 16, TTY_OP_CHAR },
  107. { "STATUS", 17, TTY_OP_CHAR },
  108. { "DISCARD", 18, TTY_OP_CHAR },
  109. { "IGNPAR", 30, TTY_OP_BOOL },
  110. { "PARMRK", 31, TTY_OP_BOOL },
  111. { "INPCK", 32, TTY_OP_BOOL },
  112. { "ISTRIP", 33, TTY_OP_BOOL },
  113. { "INLCR", 34, TTY_OP_BOOL },
  114. { "IGNCR", 35, TTY_OP_BOOL },
  115. { "ICRNL", 36, TTY_OP_BOOL },
  116. { "IUCLC", 37, TTY_OP_BOOL },
  117. { "IXON", 38, TTY_OP_BOOL },
  118. { "IXANY", 39, TTY_OP_BOOL },
  119. { "IXOFF", 40, TTY_OP_BOOL },
  120. { "IMAXBEL", 41, TTY_OP_BOOL },
  121. { "IUTF8", 42, TTY_OP_BOOL },
  122. { "ISIG", 50, TTY_OP_BOOL },
  123. { "ICANON", 51, TTY_OP_BOOL },
  124. { "XCASE", 52, TTY_OP_BOOL },
  125. { "ECHO", 53, TTY_OP_BOOL },
  126. { "ECHOE", 54, TTY_OP_BOOL },
  127. { "ECHOK", 55, TTY_OP_BOOL },
  128. { "ECHONL", 56, TTY_OP_BOOL },
  129. { "NOFLSH", 57, TTY_OP_BOOL },
  130. { "TOSTOP", 58, TTY_OP_BOOL },
  131. { "IEXTEN", 59, TTY_OP_BOOL },
  132. { "ECHOCTL", 60, TTY_OP_BOOL },
  133. { "ECHOKE", 61, TTY_OP_BOOL },
  134. { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
  135. { "OPOST", 70, TTY_OP_BOOL },
  136. { "OLCUC", 71, TTY_OP_BOOL },
  137. { "ONLCR", 72, TTY_OP_BOOL },
  138. { "OCRNL", 73, TTY_OP_BOOL },
  139. { "ONOCR", 74, TTY_OP_BOOL },
  140. { "ONLRET", 75, TTY_OP_BOOL },
  141. { "CS7", 90, TTY_OP_BOOL },
  142. { "CS8", 91, TTY_OP_BOOL },
  143. { "PARENB", 92, TTY_OP_BOOL },
  144. { "PARODD", 93, TTY_OP_BOOL }
  145. };
  146. /* Miscellaneous other tty-related constants. */
  147. #define SSH_TTY_OP_END 0
  148. /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
  149. #define SSH1_TTY_OP_ISPEED 192
  150. #define SSH1_TTY_OP_OSPEED 193
  151. #define SSH2_TTY_OP_ISPEED 128
  152. #define SSH2_TTY_OP_OSPEED 129
  153. /* Helper functions for parsing tty-related config. */
  154. static unsigned int ssh_tty_parse_specchar(char *s)
  155. {
  156. unsigned int ret;
  157. if (*s) {
  158. char *next = NULL;
  159. ret = ctrlparse(s, &next);
  160. if (!next) ret = s[0];
  161. } else {
  162. ret = 255; /* special value meaning "don't set" */
  163. }
  164. return ret;
  165. }
  166. static unsigned int ssh_tty_parse_boolean(char *s)
  167. {
  168. if (stricmp(s, "yes") == 0 ||
  169. stricmp(s, "on") == 0 ||
  170. stricmp(s, "true") == 0 ||
  171. stricmp(s, "+") == 0)
  172. return 1; /* true */
  173. else if (stricmp(s, "no") == 0 ||
  174. stricmp(s, "off") == 0 ||
  175. stricmp(s, "false") == 0 ||
  176. stricmp(s, "-") == 0)
  177. return 0; /* false */
  178. else
  179. return (atoi(s) != 0);
  180. }
  181. #define translate(x) if (type == x) return #x
  182. #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
  183. #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
  184. static const char *ssh1_pkt_type(int type)
  185. {
  186. translate(SSH1_MSG_DISCONNECT);
  187. translate(SSH1_SMSG_PUBLIC_KEY);
  188. translate(SSH1_CMSG_SESSION_KEY);
  189. translate(SSH1_CMSG_USER);
  190. translate(SSH1_CMSG_AUTH_RSA);
  191. translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
  192. translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
  193. translate(SSH1_CMSG_AUTH_PASSWORD);
  194. translate(SSH1_CMSG_REQUEST_PTY);
  195. translate(SSH1_CMSG_WINDOW_SIZE);
  196. translate(SSH1_CMSG_EXEC_SHELL);
  197. translate(SSH1_CMSG_EXEC_CMD);
  198. translate(SSH1_SMSG_SUCCESS);
  199. translate(SSH1_SMSG_FAILURE);
  200. translate(SSH1_CMSG_STDIN_DATA);
  201. translate(SSH1_SMSG_STDOUT_DATA);
  202. translate(SSH1_SMSG_STDERR_DATA);
  203. translate(SSH1_CMSG_EOF);
  204. translate(SSH1_SMSG_EXIT_STATUS);
  205. translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
  206. translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
  207. translate(SSH1_MSG_CHANNEL_DATA);
  208. translate(SSH1_MSG_CHANNEL_CLOSE);
  209. translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
  210. translate(SSH1_SMSG_X11_OPEN);
  211. translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
  212. translate(SSH1_MSG_PORT_OPEN);
  213. translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
  214. translate(SSH1_SMSG_AGENT_OPEN);
  215. translate(SSH1_MSG_IGNORE);
  216. translate(SSH1_CMSG_EXIT_CONFIRMATION);
  217. translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
  218. translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
  219. translate(SSH1_MSG_DEBUG);
  220. translate(SSH1_CMSG_REQUEST_COMPRESSION);
  221. translate(SSH1_CMSG_AUTH_TIS);
  222. translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
  223. translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
  224. translate(SSH1_CMSG_AUTH_CCARD);
  225. translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
  226. translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
  227. return "unknown";
  228. }
  229. static const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx,
  230. int type)
  231. {
  232. translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
  233. translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
  234. translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
  235. translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
  236. translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
  237. translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
  238. translate(SSH2_MSG_DISCONNECT);
  239. translate(SSH2_MSG_IGNORE);
  240. translate(SSH2_MSG_UNIMPLEMENTED);
  241. translate(SSH2_MSG_DEBUG);
  242. translate(SSH2_MSG_SERVICE_REQUEST);
  243. translate(SSH2_MSG_SERVICE_ACCEPT);
  244. translate(SSH2_MSG_KEXINIT);
  245. translate(SSH2_MSG_NEWKEYS);
  246. translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
  247. translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
  248. translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
  249. translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
  250. translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
  251. translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
  252. translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
  253. translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
  254. translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
  255. translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
  256. translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
  257. translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
  258. translate(SSH2_MSG_USERAUTH_REQUEST);
  259. translate(SSH2_MSG_USERAUTH_FAILURE);
  260. translate(SSH2_MSG_USERAUTH_SUCCESS);
  261. translate(SSH2_MSG_USERAUTH_BANNER);
  262. translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
  263. translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
  264. translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
  265. translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
  266. translate(SSH2_MSG_GLOBAL_REQUEST);
  267. translate(SSH2_MSG_REQUEST_SUCCESS);
  268. translate(SSH2_MSG_REQUEST_FAILURE);
  269. translate(SSH2_MSG_CHANNEL_OPEN);
  270. translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
  271. translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
  272. translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  273. translate(SSH2_MSG_CHANNEL_DATA);
  274. translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
  275. translate(SSH2_MSG_CHANNEL_EOF);
  276. translate(SSH2_MSG_CHANNEL_CLOSE);
  277. translate(SSH2_MSG_CHANNEL_REQUEST);
  278. translate(SSH2_MSG_CHANNEL_SUCCESS);
  279. translate(SSH2_MSG_CHANNEL_FAILURE);
  280. return "unknown";
  281. }
  282. #undef translate
  283. #undef translatec
  284. /* Enumeration values for fields in SSH-1 packets */
  285. enum {
  286. PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
  287. };
  288. /*
  289. * Coroutine mechanics for the sillier bits of the code. If these
  290. * macros look impenetrable to you, you might find it helpful to
  291. * read
  292. *
  293. * https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
  294. *
  295. * which explains the theory behind these macros.
  296. *
  297. * In particular, if you are getting `case expression not constant'
  298. * errors when building with MS Visual Studio, this is because MS's
  299. * Edit and Continue debugging feature causes their compiler to
  300. * violate ANSI C. To disable Edit and Continue debugging:
  301. *
  302. * - right-click ssh.c in the FileView
  303. * - click Settings
  304. * - select the C/C++ tab and the General category
  305. * - under `Debug info:', select anything _other_ than `Program
  306. * Database for Edit and Continue'.
  307. */
  308. #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
  309. #define crBeginState crBegin(s->crLine)
  310. #define crStateP(t, v) \
  311. struct t *s; \
  312. if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
  313. s = (v);
  314. #define crState(t) crStateP(t, ssh->t)
  315. #define crFinish(z) } *crLine = 0; return (z); }
  316. #define crFinishV } *crLine = 0; return; }
  317. #define crFinishFree(z) } sfree(s); return (z); }
  318. #define crFinishFreeV } sfree(s); return; }
  319. #define crReturn(z) \
  320. do {\
  321. *crLine =__LINE__; return (z); case __LINE__:;\
  322. } while (0)
  323. #define crReturnV \
  324. do {\
  325. *crLine=__LINE__; return; case __LINE__:;\
  326. } while (0)
  327. #define crStop(z) do{ *crLine = 0; return (z); }while(0)
  328. #define crStopV do{ *crLine = 0; return; }while(0)
  329. #define crWaitUntil(c) do { crReturn(0); } while (!(c))
  330. #define crWaitUntilV(c) do { crReturnV; } while (!(c))
  331. struct Packet;
  332. static struct Packet *ssh1_pkt_init(int pkt_type);
  333. static struct Packet *ssh2_pkt_init(int pkt_type);
  334. static void ssh_pkt_ensure(struct Packet *, int length);
  335. static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
  336. static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
  337. static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
  338. static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
  339. static void ssh_pkt_addstring_start(struct Packet *);
  340. static void ssh_pkt_addstring_str(struct Packet *, const char *data);
  341. static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
  342. static void ssh_pkt_addstring(struct Packet *, const char *data);
  343. static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
  344. static void ssh1_pkt_addmp(struct Packet *, Bignum b);
  345. static void ssh2_pkt_addmp(struct Packet *, Bignum b);
  346. static int ssh2_pkt_construct(Ssh, struct Packet *);
  347. static void ssh2_pkt_send(Ssh, struct Packet *);
  348. static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
  349. static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
  350. struct Packet *pktin);
  351. static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
  352. struct Packet *pktin);
  353. static void ssh_channel_init(struct ssh_channel *c);
  354. static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin);
  355. static void ssh_channel_got_eof(struct ssh_channel *c);
  356. static void ssh2_channel_check_close(struct ssh_channel *c);
  357. static void ssh_channel_close_local(struct ssh_channel *c, char const *reason);
  358. static void ssh_channel_destroy(struct ssh_channel *c);
  359. static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize);
  360. static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
  361. /*
  362. * Buffer management constants. There are several of these for
  363. * various different purposes:
  364. *
  365. * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
  366. * on a local data stream before we throttle the whole SSH
  367. * connection (in SSH-1 only). Throttling the whole connection is
  368. * pretty drastic so we set this high in the hope it won't
  369. * happen very often.
  370. *
  371. * - SSH_MAX_BACKLOG is the amount of backlog that must build up
  372. * on the SSH connection itself before we defensively throttle
  373. * _all_ local data streams. This is pretty drastic too (though
  374. * thankfully unlikely in SSH-2 since the window mechanism should
  375. * ensure that the server never has any need to throttle its end
  376. * of the connection), so we set this high as well.
  377. *
  378. * - OUR_V2_WINSIZE is the default window size we present on SSH-2
  379. * channels.
  380. *
  381. * - OUR_V2_BIGWIN is the window size we advertise for the only
  382. * channel in a simple connection. It must be <= INT_MAX.
  383. *
  384. * - OUR_V2_MAXPKT is the official "maximum packet size" we send
  385. * to the remote side. This actually has nothing to do with the
  386. * size of the _packet_, but is instead a limit on the amount
  387. * of data we're willing to receive in a single SSH2 channel
  388. * data message.
  389. *
  390. * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
  391. * _packet_ we're prepared to cope with. It must be a multiple
  392. * of the cipher block size, and must be at least 35000.
  393. */
  394. #define SSH1_BUFFER_LIMIT 32768
  395. #define SSH_MAX_BACKLOG 32768
  396. #define OUR_V2_WINSIZE 16384
  397. #define OUR_V2_BIGWIN 0x7fffffff
  398. #define OUR_V2_MAXPKT 0x4000UL
  399. #define OUR_V2_PACKETLIMIT 0x9000UL
  400. struct ssh_signkey_with_user_pref_id {
  401. const struct ssh_signkey *alg;
  402. int id;
  403. };
  404. const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
  405. { &ssh_ecdsa_ed25519, HK_ED25519 },
  406. { &ssh_ecdsa_nistp256, HK_ECDSA },
  407. { &ssh_ecdsa_nistp384, HK_ECDSA },
  408. { &ssh_ecdsa_nistp521, HK_ECDSA },
  409. { &ssh_dss, HK_DSA },
  410. { &ssh_rsa, HK_RSA },
  411. };
  412. const static struct ssh_mac *const macs[] = {
  413. &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
  414. };
  415. const static struct ssh_mac *const buggymacs[] = {
  416. &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
  417. };
  418. static void *ssh_comp_none_init(void)
  419. {
  420. return NULL;
  421. }
  422. static void ssh_comp_none_cleanup(void *handle)
  423. {
  424. }
  425. static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
  426. unsigned char **outblock, int *outlen)
  427. {
  428. return 0;
  429. }
  430. static int ssh_comp_none_disable(void *handle)
  431. {
  432. return 0;
  433. }
  434. const static struct ssh_compress ssh_comp_none = {
  435. "none", NULL,
  436. ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
  437. ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
  438. ssh_comp_none_disable, NULL
  439. };
  440. extern const struct ssh_compress ssh_zlib;
  441. const static struct ssh_compress *const compressions[] = {
  442. &ssh_zlib, &ssh_comp_none
  443. };
  444. enum { /* channel types */
  445. CHAN_MAINSESSION,
  446. CHAN_X11,
  447. CHAN_AGENT,
  448. CHAN_SOCKDATA,
  449. /*
  450. * CHAN_SHARING indicates a channel which is tracked here on
  451. * behalf of a connection-sharing downstream. We do almost nothing
  452. * with these channels ourselves: all messages relating to them
  453. * get thrown straight to sshshare.c and passed on almost
  454. * unmodified to downstream.
  455. */
  456. CHAN_SHARING,
  457. /*
  458. * CHAN_ZOMBIE is used to indicate a channel for which we've
  459. * already destroyed the local data source: for instance, if a
  460. * forwarded port experiences a socket error on the local side, we
  461. * immediately destroy its local socket and turn the SSH channel
  462. * into CHAN_ZOMBIE.
  463. */
  464. CHAN_ZOMBIE
  465. };
  466. typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
  467. typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
  468. typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
  469. /*
  470. * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
  471. * handlers.
  472. */
  473. struct outstanding_channel_request {
  474. cchandler_fn_t handler;
  475. void *ctx;
  476. struct outstanding_channel_request *next;
  477. };
  478. /*
  479. * 2-3-4 tree storing channels.
  480. */
  481. struct ssh_channel {
  482. Ssh ssh; /* pointer back to main context */
  483. unsigned remoteid, localid;
  484. int type;
  485. /* True if we opened this channel but server hasn't confirmed. */
  486. int halfopen;
  487. /*
  488. * In SSH-1, this value contains four bits:
  489. *
  490. * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
  491. * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
  492. * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
  493. * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
  494. *
  495. * A channel is completely finished with when all four bits are set.
  496. *
  497. * In SSH-2, the four bits mean:
  498. *
  499. * 1 We have sent SSH2_MSG_CHANNEL_EOF.
  500. * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
  501. * 4 We have received SSH2_MSG_CHANNEL_EOF.
  502. * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
  503. *
  504. * A channel is completely finished with when we have both sent
  505. * and received CLOSE.
  506. *
  507. * The symbolic constants below use the SSH-2 terminology, which
  508. * is a bit confusing in SSH-1, but we have to use _something_.
  509. */
  510. #define CLOSES_SENT_EOF 1
  511. #define CLOSES_SENT_CLOSE 2
  512. #define CLOSES_RCVD_EOF 4
  513. #define CLOSES_RCVD_CLOSE 8
  514. int closes;
  515. /*
  516. * This flag indicates that an EOF is pending on the outgoing side
  517. * of the channel: that is, wherever we're getting the data for
  518. * this channel has sent us some data followed by EOF. We can't
  519. * actually send the EOF until we've finished sending the data, so
  520. * we set this flag instead to remind us to do so once our buffer
  521. * is clear.
  522. */
  523. int pending_eof;
  524. /*
  525. * True if this channel is causing the underlying connection to be
  526. * throttled.
  527. */
  528. int throttling_conn;
  529. union {
  530. struct ssh2_data_channel {
  531. bufchain outbuffer;
  532. unsigned remwindow, remmaxpkt;
  533. /* locwindow is signed so we can cope with excess data. */
  534. int locwindow, locmaxwin;
  535. /*
  536. * remlocwin is the amount of local window that we think
  537. * the remote end had available to it after it sent the
  538. * last data packet or window adjust ack.
  539. */
  540. int remlocwin;
  541. /*
  542. * These store the list of channel requests that haven't
  543. * been acked.
  544. */
  545. struct outstanding_channel_request *chanreq_head, *chanreq_tail;
  546. enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
  547. } v2;
  548. } v;
  549. union {
  550. struct ssh_agent_channel {
  551. bufchain inbuffer;
  552. agent_pending_query *pending;
  553. } a;
  554. struct ssh_x11_channel {
  555. struct X11Connection *xconn;
  556. int initial;
  557. } x11;
  558. struct ssh_pfd_channel {
  559. struct PortForwarding *pf;
  560. } pfd;
  561. struct ssh_sharing_channel {
  562. void *ctx;
  563. } sharing;
  564. } u;
  565. };
  566. /*
  567. * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
  568. * use this structure in different ways, reflecting SSH-2's
  569. * altogether saner approach to port forwarding.
  570. *
  571. * In SSH-1, you arrange a remote forwarding by sending the server
  572. * the remote port number, and the local destination host:port.
  573. * When a connection comes in, the server sends you back that
  574. * host:port pair, and you connect to it. This is a ready-made
  575. * security hole if you're not on the ball: a malicious server
  576. * could send you back _any_ host:port pair, so if you trustingly
  577. * connect to the address it gives you then you've just opened the
  578. * entire inside of your corporate network just by connecting
  579. * through it to a dodgy SSH server. Hence, we must store a list of
  580. * host:port pairs we _are_ trying to forward to, and reject a
  581. * connection request from the server if it's not in the list.
  582. *
  583. * In SSH-2, each side of the connection minds its own business and
  584. * doesn't send unnecessary information to the other. You arrange a
  585. * remote forwarding by sending the server just the remote port
  586. * number. When a connection comes in, the server tells you which
  587. * of its ports was connected to; and _you_ have to remember what
  588. * local host:port pair went with that port number.
  589. *
  590. * Hence, in SSH-1 this structure is indexed by destination
  591. * host:port pair, whereas in SSH-2 it is indexed by source port.
  592. */
  593. struct ssh_portfwd; /* forward declaration */
  594. struct ssh_rportfwd {
  595. unsigned sport, dport;
  596. char *shost, *dhost;
  597. char *sportdesc;
  598. void *share_ctx;
  599. struct ssh_portfwd *pfrec;
  600. };
  601. static void free_rportfwd(struct ssh_rportfwd *pf)
  602. {
  603. if (pf) {
  604. sfree(pf->sportdesc);
  605. sfree(pf->shost);
  606. sfree(pf->dhost);
  607. sfree(pf);
  608. }
  609. }
  610. /*
  611. * Separately to the rportfwd tree (which is for looking up port
  612. * open requests from the server), a tree of _these_ structures is
  613. * used to keep track of all the currently open port forwardings,
  614. * so that we can reconfigure in mid-session if the user requests
  615. * it.
  616. */
  617. struct ssh_portfwd {
  618. enum { DESTROY, KEEP, CREATE } status;
  619. int type;
  620. unsigned sport, dport;
  621. char *saddr, *daddr;
  622. char *sserv, *dserv;
  623. struct ssh_rportfwd *remote;
  624. int addressfamily;
  625. struct PortListener *local;
  626. };
  627. #define free_portfwd(pf) ( \
  628. ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
  629. sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
  630. struct Packet {
  631. long length; /* length of packet: see below */
  632. long forcepad; /* SSH-2: force padding to at least this length */
  633. int type; /* only used for incoming packets */
  634. unsigned long sequence; /* SSH-2 incoming sequence number */
  635. unsigned char *data; /* allocated storage */
  636. unsigned char *body; /* offset of payload within `data' */
  637. long savedpos; /* dual-purpose saved packet position: see below */
  638. long maxlen; /* amount of storage allocated for `data' */
  639. long encrypted_len; /* for SSH-2 total-size counting */
  640. /*
  641. * A note on the 'length' and 'savedpos' fields above.
  642. *
  643. * Incoming packets are set up so that pkt->length is measured
  644. * relative to pkt->body, which itself points to a few bytes after
  645. * pkt->data (skipping some uninteresting header fields including
  646. * the packet type code). The ssh_pkt_get* functions all expect
  647. * this setup, and they also use pkt->savedpos to indicate how far
  648. * through the packet being decoded they've got - and that, too,
  649. * is an offset from pkt->body rather than pkt->data.
  650. *
  651. * During construction of an outgoing packet, however, pkt->length
  652. * is measured relative to the base pointer pkt->data, and
  653. * pkt->body is not really used for anything until the packet is
  654. * ready for sending. In this mode, pkt->savedpos is reused as a
  655. * temporary variable by the addstring functions, which write out
  656. * a string length field and then keep going back and updating it
  657. * as more data is appended to the subsequent string data field;
  658. * pkt->savedpos stores the offset (again relative to pkt->data)
  659. * of the start of the string data field.
  660. */
  661. /* Extra metadata used in SSH packet logging mode, allowing us to
  662. * log in the packet header line that the packet came from a
  663. * connection-sharing downstream and what if anything unusual was
  664. * done to it. The additional_log_text field is expected to be a
  665. * static string - it will not be freed. */
  666. unsigned downstream_id;
  667. const char *additional_log_text;
  668. };
  669. static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
  670. struct Packet *pktin);
  671. static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
  672. struct Packet *pktin);
  673. static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
  674. struct Packet *pktin);
  675. static void ssh1_protocol_setup(Ssh ssh);
  676. static void ssh2_protocol_setup(Ssh ssh);
  677. static void ssh2_bare_connection_protocol_setup(Ssh ssh);
  678. static void ssh_size(void *handle, int width, int height);
  679. static void ssh_special(void *handle, Telnet_Special);
  680. static int ssh2_try_send(struct ssh_channel *c);
  681. static int ssh_send_channel_data(struct ssh_channel *c,
  682. const char *buf, int len);
  683. static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
  684. static void ssh2_set_window(struct ssh_channel *c, int newwin);
  685. static int ssh_sendbuffer(void *handle);
  686. static int ssh_do_close(Ssh ssh, int notify_exit);
  687. static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
  688. static int ssh2_pkt_getbool(struct Packet *pkt);
  689. static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
  690. static void ssh2_timer(void *ctx, unsigned long now);
  691. static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
  692. struct Packet *pktin);
  693. static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
  694. struct rdpkt1_state_tag {
  695. long len, pad, biglen, to_read;
  696. unsigned long realcrc, gotcrc;
  697. unsigned char *p;
  698. int i;
  699. int chunk;
  700. struct Packet *pktin;
  701. };
  702. struct rdpkt2_state_tag {
  703. long len, pad, payload, packetlen, maclen;
  704. int i;
  705. int cipherblk;
  706. unsigned long incoming_sequence;
  707. struct Packet *pktin;
  708. };
  709. struct rdpkt2_bare_state_tag {
  710. char length[4];
  711. long packetlen;
  712. int i;
  713. unsigned long incoming_sequence;
  714. struct Packet *pktin;
  715. };
  716. struct queued_handler;
  717. struct queued_handler {
  718. int msg1, msg2;
  719. chandler_fn_t handler;
  720. void *ctx;
  721. struct queued_handler *next;
  722. };
  723. struct ssh_tag {
  724. const struct plug_function_table *fn;
  725. /* the above field _must_ be first in the structure */
  726. char *v_c, *v_s;
  727. void *exhash;
  728. Socket s;
  729. void *ldisc;
  730. void *logctx;
  731. unsigned char session_key[32];
  732. int v1_compressing;
  733. int v1_remote_protoflags;
  734. int v1_local_protoflags;
  735. int agentfwd_enabled;
  736. int X11_fwd_enabled;
  737. int remote_bugs;
  738. const struct ssh_cipher *cipher;
  739. void *v1_cipher_ctx;
  740. void *crcda_ctx;
  741. const struct ssh2_cipher *cscipher, *sccipher;
  742. void *cs_cipher_ctx, *sc_cipher_ctx;
  743. const struct ssh_mac *csmac, *scmac;
  744. int csmac_etm, scmac_etm;
  745. void *cs_mac_ctx, *sc_mac_ctx;
  746. const struct ssh_compress *cscomp, *sccomp;
  747. void *cs_comp_ctx, *sc_comp_ctx;
  748. const struct ssh_kex *kex;
  749. const struct ssh_signkey *hostkey;
  750. char *hostkey_str; /* string representation, for easy checking in rekeys */
  751. unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
  752. int v2_session_id_len;
  753. void *kex_ctx;
  754. int bare_connection;
  755. int attempting_connshare;
  756. void *connshare;
  757. char *savedhost;
  758. int savedport;
  759. int send_ok;
  760. int echoing, editing;
  761. int session_started;
  762. void *frontend;
  763. int ospeed, ispeed; /* temporaries */
  764. int term_width, term_height;
  765. tree234 *channels; /* indexed by local id */
  766. struct ssh_channel *mainchan; /* primary session channel */
  767. int ncmode; /* is primary channel direct-tcpip? */
  768. int exitcode;
  769. int close_expected;
  770. int clean_exit;
  771. tree234 *rportfwds, *portfwds;
  772. enum {
  773. SSH_STATE_PREPACKET,
  774. SSH_STATE_BEFORE_SIZE,
  775. SSH_STATE_INTERMED,
  776. SSH_STATE_SESSION,
  777. SSH_STATE_CLOSED
  778. } state;
  779. int size_needed, eof_needed;
  780. int sent_console_eof;
  781. int got_pty; /* affects EOF behaviour on main channel */
  782. struct Packet **queue;
  783. int queuelen, queuesize;
  784. int queueing;
  785. unsigned char *deferred_send_data;
  786. int deferred_len, deferred_size;
  787. /*
  788. * Gross hack: pscp will try to start SFTP but fall back to
  789. * scp1 if that fails. This variable is the means by which
  790. * scp.c can reach into the SSH code and find out which one it
  791. * got.
  792. */
  793. int fallback_cmd;
  794. bufchain banner; /* accumulates banners during do_ssh2_authconn */
  795. Pkt_KCtx pkt_kctx;
  796. Pkt_ACtx pkt_actx;
  797. struct X11Display *x11disp;
  798. struct X11FakeAuth *x11auth;
  799. tree234 *x11authtree;
  800. int version;
  801. int conn_throttle_count;
  802. int overall_bufsize;
  803. int throttled_all;
  804. int v1_stdout_throttling;
  805. unsigned long v2_outgoing_sequence;
  806. int ssh1_rdpkt_crstate;
  807. int ssh2_rdpkt_crstate;
  808. int ssh2_bare_rdpkt_crstate;
  809. int ssh_gotdata_crstate;
  810. int do_ssh1_connection_crstate;
  811. void *do_ssh_init_state;
  812. void *do_ssh1_login_state;
  813. void *do_ssh2_transport_state;
  814. void *do_ssh2_authconn_state;
  815. void *do_ssh_connection_init_state;
  816. struct rdpkt1_state_tag rdpkt1_state;
  817. struct rdpkt2_state_tag rdpkt2_state;
  818. struct rdpkt2_bare_state_tag rdpkt2_bare_state;
  819. /* SSH-1 and SSH-2 use this for different things, but both use it */
  820. int protocol_initial_phase_done;
  821. void (*protocol) (Ssh ssh, const void *vin, int inlen,
  822. struct Packet *pkt);
  823. struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
  824. int *datalen);
  825. int (*do_ssh_init)(Ssh ssh, unsigned char c);
  826. /*
  827. * We maintain our own copy of a Conf structure here. That way,
  828. * when we're passed a new one for reconfiguration, we can check
  829. * the differences and potentially reconfigure port forwardings
  830. * etc in mid-session.
  831. */
  832. Conf *conf;
  833. /*
  834. * Values cached out of conf so as to avoid the tree234 lookup
  835. * cost every time they're used.
  836. */
  837. int logomitdata;
  838. /*
  839. * Dynamically allocated username string created during SSH
  840. * login. Stored in here rather than in the coroutine state so
  841. * that it'll be reliably freed if we shut down the SSH session
  842. * at some unexpected moment.
  843. */
  844. char *username;
  845. /*
  846. * Used to transfer data back from async callbacks.
  847. */
  848. void *agent_response;
  849. int agent_response_len;
  850. int user_response;
  851. /*
  852. * The SSH connection can be set as `frozen', meaning we are
  853. * not currently accepting incoming data from the network. This
  854. * is slightly more serious than setting the _socket_ as
  855. * frozen, because we may already have had data passed to us
  856. * from the network which we need to delay processing until
  857. * after the freeze is lifted, so we also need a bufchain to
  858. * store that data.
  859. */
  860. int frozen;
  861. bufchain queued_incoming_data;
  862. /*
  863. * Dispatch table for packet types that we may have to deal
  864. * with at any time.
  865. */
  866. handler_fn_t packet_dispatch[256];
  867. /*
  868. * Queues of one-off handler functions for success/failure
  869. * indications from a request.
  870. */
  871. struct queued_handler *qhead, *qtail;
  872. handler_fn_t q_saved_handler1, q_saved_handler2;
  873. /*
  874. * This module deals with sending keepalives.
  875. */
  876. Pinger pinger;
  877. /*
  878. * Track incoming and outgoing data sizes and time, for
  879. * size-based rekeys.
  880. */
  881. unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
  882. unsigned long max_data_size;
  883. int kex_in_progress;
  884. unsigned long next_rekey, last_rekey;
  885. const char *deferred_rekey_reason;
  886. /*
  887. * Fully qualified host name, which we need if doing GSSAPI.
  888. */
  889. char *fullhostname;
  890. #ifndef NO_GSSAPI
  891. /*
  892. * GSSAPI libraries for this session.
  893. */
  894. struct ssh_gss_liblist *gsslibs;
  895. #endif
  896. /*
  897. * The last list returned from get_specials.
  898. */
  899. struct telnet_special *specials;
  900. /*
  901. * List of host key algorithms for which we _don't_ have a stored
  902. * host key. These are indices into the main hostkey_algs[] array
  903. */
  904. int uncert_hostkeys[lenof(hostkey_algs)];
  905. int n_uncert_hostkeys;
  906. /*
  907. * Flag indicating that the current rekey is intended to finish
  908. * with a newly cross-certified host key.
  909. */
  910. int cross_certifying;
  911. /*
  912. * Any asynchronous query to our SSH agent that we might have in
  913. * flight from the main authentication loop. (Queries from
  914. * agent-forwarding channels live in their channel structure.)
  915. */
  916. agent_pending_query *auth_agent_query;
  917. };
  918. static const char *ssh_pkt_type(Ssh ssh, int type)
  919. {
  920. if (ssh->version == 1)
  921. return ssh1_pkt_type(type);
  922. else
  923. return ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, type);
  924. }
  925. #define logevent(s) logevent(ssh->frontend, s)
  926. /* logevent, only printf-formatted. */
  927. static void logeventf(Ssh ssh, const char *fmt, ...)
  928. {
  929. va_list ap;
  930. char *buf;
  931. va_start(ap, fmt);
  932. buf = dupvprintf(fmt, ap);
  933. va_end(ap);
  934. logevent(buf);
  935. sfree(buf);
  936. }
  937. static void bomb_out(Ssh ssh, char *text)
  938. {
  939. ssh_do_close(ssh, FALSE);
  940. logevent(text);
  941. connection_fatal(ssh->frontend, "%s", text);
  942. sfree(text);
  943. }
  944. #define bombout(msg) bomb_out(ssh, dupprintf msg)
  945. /* Helper function for common bits of parsing ttymodes. */
  946. static void parse_ttymodes(Ssh ssh,
  947. void (*do_mode)(void *data,
  948. const struct ssh_ttymode *mode,
  949. char *val),
  950. void *data)
  951. {
  952. int i;
  953. const struct ssh_ttymode *mode;
  954. char *val;
  955. for (i = 0; i < lenof(ssh_ttymodes); i++) {
  956. mode = ssh_ttymodes + i;
  957. /* Every mode known to the current version of the code should be
  958. * mentioned; this was ensured when settings were loaded. */
  959. val = conf_get_str_str(ssh->conf, CONF_ttymodes, mode->mode);
  960. /*
  961. * val[0] can be
  962. * - 'V', indicating that an explicit value follows it;
  963. * - 'A', indicating that we should pass the value through from
  964. * the local environment via get_ttymode; or
  965. * - 'N', indicating that we should explicitly not send this
  966. * mode.
  967. */
  968. if (val[0] == 'A') {
  969. val = get_ttymode(ssh->frontend, mode->mode);
  970. if (val) {
  971. do_mode(data, mode, val);
  972. sfree(val);
  973. }
  974. } else if (val[0] == 'V') {
  975. do_mode(data, mode, val + 1); /* skip the 'V' */
  976. } /* else 'N', or something from the future we don't understand */
  977. }
  978. }
  979. static int ssh_channelcmp(void *av, void *bv)
  980. {
  981. struct ssh_channel *a = (struct ssh_channel *) av;
  982. struct ssh_channel *b = (struct ssh_channel *) bv;
  983. if (a->localid < b->localid)
  984. return -1;
  985. if (a->localid > b->localid)
  986. return +1;
  987. return 0;
  988. }
  989. static int ssh_channelfind(void *av, void *bv)
  990. {
  991. unsigned *a = (unsigned *) av;
  992. struct ssh_channel *b = (struct ssh_channel *) bv;
  993. if (*a < b->localid)
  994. return -1;
  995. if (*a > b->localid)
  996. return +1;
  997. return 0;
  998. }
  999. static int ssh_rportcmp_ssh1(void *av, void *bv)
  1000. {
  1001. struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
  1002. struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
  1003. int i;
  1004. if ( (i = strcmp(a->dhost, b->dhost)) != 0)
  1005. return i < 0 ? -1 : +1;
  1006. if (a->dport > b->dport)
  1007. return +1;
  1008. if (a->dport < b->dport)
  1009. return -1;
  1010. return 0;
  1011. }
  1012. static int ssh_rportcmp_ssh2(void *av, void *bv)
  1013. {
  1014. struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
  1015. struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
  1016. int i;
  1017. if ( (i = strcmp(a->shost, b->shost)) != 0)
  1018. return i < 0 ? -1 : +1;
  1019. if (a->sport > b->sport)
  1020. return +1;
  1021. if (a->sport < b->sport)
  1022. return -1;
  1023. return 0;
  1024. }
  1025. /*
  1026. * Special form of strcmp which can cope with NULL inputs. NULL is
  1027. * defined to sort before even the empty string.
  1028. */
  1029. static int nullstrcmp(const char *a, const char *b)
  1030. {
  1031. if (a == NULL && b == NULL)
  1032. return 0;
  1033. if (a == NULL)
  1034. return -1;
  1035. if (b == NULL)
  1036. return +1;
  1037. return strcmp(a, b);
  1038. }
  1039. static int ssh_portcmp(void *av, void *bv)
  1040. {
  1041. struct ssh_portfwd *a = (struct ssh_portfwd *) av;
  1042. struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
  1043. int i;
  1044. if (a->type > b->type)
  1045. return +1;
  1046. if (a->type < b->type)
  1047. return -1;
  1048. if (a->addressfamily > b->addressfamily)
  1049. return +1;
  1050. if (a->addressfamily < b->addressfamily)
  1051. return -1;
  1052. if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
  1053. return i < 0 ? -1 : +1;
  1054. if (a->sport > b->sport)
  1055. return +1;
  1056. if (a->sport < b->sport)
  1057. return -1;
  1058. if (a->type != 'D') {
  1059. if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
  1060. return i < 0 ? -1 : +1;
  1061. if (a->dport > b->dport)
  1062. return +1;
  1063. if (a->dport < b->dport)
  1064. return -1;
  1065. }
  1066. return 0;
  1067. }
  1068. static int alloc_channel_id(Ssh ssh)
  1069. {
  1070. const unsigned CHANNEL_NUMBER_OFFSET = 256;
  1071. unsigned low, high, mid;
  1072. int tsize;
  1073. struct ssh_channel *c;
  1074. /*
  1075. * First-fit allocation of channel numbers: always pick the
  1076. * lowest unused one. To do this, binary-search using the
  1077. * counted B-tree to find the largest channel ID which is in a
  1078. * contiguous sequence from the beginning. (Precisely
  1079. * everything in that sequence must have ID equal to its tree
  1080. * index plus CHANNEL_NUMBER_OFFSET.)
  1081. */
  1082. tsize = count234(ssh->channels);
  1083. low = -1;
  1084. high = tsize;
  1085. while (high - low > 1) {
  1086. mid = (high + low) / 2;
  1087. c = index234(ssh->channels, mid);
  1088. if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
  1089. low = mid; /* this one is fine */
  1090. else
  1091. high = mid; /* this one is past it */
  1092. }
  1093. /*
  1094. * Now low points to either -1, or the tree index of the
  1095. * largest ID in the initial sequence.
  1096. */
  1097. {
  1098. unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
  1099. assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
  1100. }
  1101. return low + 1 + CHANNEL_NUMBER_OFFSET;
  1102. }
  1103. static void c_write_stderr(int trusted, const char *buf, int len)
  1104. {
  1105. int i;
  1106. for (i = 0; i < len; i++)
  1107. if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
  1108. fputc(buf[i], stderr);
  1109. }
  1110. static void c_write(Ssh ssh, const char *buf, int len)
  1111. {
  1112. if (flags & FLAG_STDERR)
  1113. c_write_stderr(1, buf, len);
  1114. else
  1115. #ifdef MPEXT
  1116. from_backend(ssh->frontend, -1, buf, len);
  1117. #else
  1118. from_backend(ssh->frontend, 1, buf, len);
  1119. #endif
  1120. }
  1121. static void c_write_untrusted(Ssh ssh, const char *buf, int len)
  1122. {
  1123. if (flags & FLAG_STDERR)
  1124. c_write_stderr(0, buf, len);
  1125. else
  1126. from_backend_untrusted(ssh->frontend, buf, len);
  1127. }
  1128. static void c_write_str(Ssh ssh, const char *buf)
  1129. {
  1130. c_write(ssh, buf, strlen(buf));
  1131. }
  1132. static void ssh_free_packet(struct Packet *pkt)
  1133. {
  1134. sfree(pkt->data);
  1135. sfree(pkt);
  1136. }
  1137. static struct Packet *ssh_new_packet(void)
  1138. {
  1139. struct Packet *pkt = snew(struct Packet);
  1140. pkt->body = pkt->data = NULL;
  1141. pkt->maxlen = 0;
  1142. return pkt;
  1143. }
  1144. static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
  1145. {
  1146. int nblanks = 0;
  1147. struct logblank_t blanks[4];
  1148. char *str;
  1149. int slen;
  1150. pkt->savedpos = 0;
  1151. if (ssh->logomitdata &&
  1152. (pkt->type == SSH1_SMSG_STDOUT_DATA ||
  1153. pkt->type == SSH1_SMSG_STDERR_DATA ||
  1154. pkt->type == SSH1_MSG_CHANNEL_DATA)) {
  1155. /* "Session data" packets - omit the data string. */
  1156. if (pkt->type == SSH1_MSG_CHANNEL_DATA)
  1157. ssh_pkt_getuint32(pkt); /* skip channel id */
  1158. blanks[nblanks].offset = pkt->savedpos + 4;
  1159. blanks[nblanks].type = PKTLOG_OMIT;
  1160. ssh_pkt_getstring(pkt, &str, &slen);
  1161. if (str) {
  1162. blanks[nblanks].len = slen;
  1163. nblanks++;
  1164. }
  1165. }
  1166. log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
  1167. ssh1_pkt_type(pkt->type),
  1168. pkt->body, pkt->length, nblanks, blanks, NULL,
  1169. 0, NULL);
  1170. }
  1171. static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
  1172. {
  1173. int nblanks = 0;
  1174. struct logblank_t blanks[4];
  1175. char *str;
  1176. int slen;
  1177. /*
  1178. * For outgoing packets, pkt->length represents the length of the
  1179. * whole packet starting at pkt->data (including some header), and
  1180. * pkt->body refers to the point within that where the log-worthy
  1181. * payload begins. However, incoming packets expect pkt->length to
  1182. * represent only the payload length (that is, it's measured from
  1183. * pkt->body not from pkt->data). Temporarily adjust our outgoing
  1184. * packet to conform to the incoming-packet semantics, so that we
  1185. * can analyse it with the ssh_pkt_get functions.
  1186. */
  1187. pkt->length -= (pkt->body - pkt->data);
  1188. pkt->savedpos = 0;
  1189. if (ssh->logomitdata &&
  1190. (pkt->type == SSH1_CMSG_STDIN_DATA ||
  1191. pkt->type == SSH1_MSG_CHANNEL_DATA)) {
  1192. /* "Session data" packets - omit the data string. */
  1193. if (pkt->type == SSH1_MSG_CHANNEL_DATA)
  1194. ssh_pkt_getuint32(pkt); /* skip channel id */
  1195. blanks[nblanks].offset = pkt->savedpos + 4;
  1196. blanks[nblanks].type = PKTLOG_OMIT;
  1197. ssh_pkt_getstring(pkt, &str, &slen);
  1198. if (str) {
  1199. blanks[nblanks].len = slen;
  1200. nblanks++;
  1201. }
  1202. }
  1203. if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
  1204. pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
  1205. pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
  1206. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1207. /* If this is a password or similar packet, blank the password(s). */
  1208. blanks[nblanks].offset = 0;
  1209. blanks[nblanks].len = pkt->length;
  1210. blanks[nblanks].type = PKTLOG_BLANK;
  1211. nblanks++;
  1212. } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
  1213. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1214. /*
  1215. * If this is an X forwarding request packet, blank the fake
  1216. * auth data.
  1217. *
  1218. * Note that while we blank the X authentication data here, we
  1219. * don't take any special action to blank the start of an X11
  1220. * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
  1221. * an X connection without having session blanking enabled is
  1222. * likely to leak your cookie into the log.
  1223. */
  1224. pkt->savedpos = 0;
  1225. ssh_pkt_getstring(pkt, &str, &slen);
  1226. blanks[nblanks].offset = pkt->savedpos;
  1227. blanks[nblanks].type = PKTLOG_BLANK;
  1228. ssh_pkt_getstring(pkt, &str, &slen);
  1229. if (str) {
  1230. blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
  1231. nblanks++;
  1232. }
  1233. }
  1234. log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
  1235. ssh1_pkt_type(pkt->data[12]),
  1236. pkt->body, pkt->length,
  1237. nblanks, blanks, NULL, 0, NULL);
  1238. /*
  1239. * Undo the above adjustment of pkt->length, to put the packet
  1240. * back in the state we found it.
  1241. */
  1242. pkt->length += (pkt->body - pkt->data);
  1243. }
  1244. /*
  1245. * Collect incoming data in the incoming packet buffer.
  1246. * Decipher and verify the packet when it is completely read.
  1247. * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
  1248. * Update the *data and *datalen variables.
  1249. * Return a Packet structure when a packet is completed.
  1250. */
  1251. static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
  1252. int *datalen)
  1253. {
  1254. struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
  1255. crBegin(ssh->ssh1_rdpkt_crstate);
  1256. st->pktin = ssh_new_packet();
  1257. st->pktin->type = 0;
  1258. st->pktin->length = 0;
  1259. for (st->i = st->len = 0; st->i < 4; st->i++) {
  1260. while ((*datalen) == 0)
  1261. crReturn(NULL);
  1262. st->len = (st->len << 8) + **data;
  1263. (*data)++, (*datalen)--;
  1264. }
  1265. st->pad = 8 - (st->len % 8);
  1266. st->biglen = st->len + st->pad;
  1267. st->pktin->length = st->len - 5;
  1268. if (st->biglen < 0) {
  1269. bombout(("Extremely large packet length from server suggests"
  1270. " data stream corruption"));
  1271. ssh_free_packet(st->pktin);
  1272. crStop(NULL);
  1273. }
  1274. st->pktin->maxlen = st->biglen;
  1275. st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
  1276. st->to_read = st->biglen;
  1277. st->p = st->pktin->data;
  1278. while (st->to_read > 0) {
  1279. st->chunk = st->to_read;
  1280. while ((*datalen) == 0)
  1281. crReturn(NULL);
  1282. if (st->chunk > (*datalen))
  1283. st->chunk = (*datalen);
  1284. memcpy(st->p, *data, st->chunk);
  1285. *data += st->chunk;
  1286. *datalen -= st->chunk;
  1287. st->p += st->chunk;
  1288. st->to_read -= st->chunk;
  1289. }
  1290. if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
  1291. st->biglen, NULL)) {
  1292. bombout(("Network attack (CRC compensation) detected!"));
  1293. ssh_free_packet(st->pktin);
  1294. crStop(NULL);
  1295. }
  1296. if (ssh->cipher)
  1297. ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
  1298. st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
  1299. st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
  1300. if (st->gotcrc != st->realcrc) {
  1301. bombout(("Incorrect CRC received on packet"));
  1302. ssh_free_packet(st->pktin);
  1303. crStop(NULL);
  1304. }
  1305. st->pktin->body = st->pktin->data + st->pad + 1;
  1306. if (ssh->v1_compressing) {
  1307. unsigned char *decompblk;
  1308. int decomplen;
  1309. if (!zlib_decompress_block(ssh->sc_comp_ctx,
  1310. st->pktin->body - 1, st->pktin->length + 1,
  1311. &decompblk, &decomplen)) {
  1312. bombout(("Zlib decompression encountered invalid data"));
  1313. ssh_free_packet(st->pktin);
  1314. crStop(NULL);
  1315. }
  1316. if (st->pktin->maxlen < st->pad + decomplen) {
  1317. st->pktin->maxlen = st->pad + decomplen;
  1318. st->pktin->data = sresize(st->pktin->data,
  1319. st->pktin->maxlen + APIEXTRA,
  1320. unsigned char);
  1321. st->pktin->body = st->pktin->data + st->pad + 1;
  1322. }
  1323. memcpy(st->pktin->body - 1, decompblk, decomplen);
  1324. sfree(decompblk);
  1325. st->pktin->length = decomplen - 1;
  1326. }
  1327. st->pktin->type = st->pktin->body[-1];
  1328. /*
  1329. * Now pktin->body and pktin->length identify the semantic content
  1330. * of the packet, excluding the initial type byte.
  1331. */
  1332. if (ssh->logctx)
  1333. ssh1_log_incoming_packet(ssh, st->pktin);
  1334. st->pktin->savedpos = 0;
  1335. crFinish(st->pktin);
  1336. }
  1337. static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
  1338. {
  1339. int nblanks = 0;
  1340. struct logblank_t blanks[4];
  1341. char *str;
  1342. int slen;
  1343. pkt->savedpos = 0;
  1344. if (ssh->logomitdata &&
  1345. (pkt->type == SSH2_MSG_CHANNEL_DATA ||
  1346. pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
  1347. /* "Session data" packets - omit the data string. */
  1348. ssh_pkt_getuint32(pkt); /* skip channel id */
  1349. if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
  1350. ssh_pkt_getuint32(pkt); /* skip extended data type */
  1351. blanks[nblanks].offset = pkt->savedpos + 4;
  1352. blanks[nblanks].type = PKTLOG_OMIT;
  1353. ssh_pkt_getstring(pkt, &str, &slen);
  1354. if (str) {
  1355. blanks[nblanks].len = slen;
  1356. nblanks++;
  1357. }
  1358. }
  1359. log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
  1360. ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
  1361. pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
  1362. 0, NULL);
  1363. }
  1364. static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
  1365. {
  1366. int nblanks = 0;
  1367. struct logblank_t blanks[4];
  1368. char *str;
  1369. int slen;
  1370. /*
  1371. * For outgoing packets, pkt->length represents the length of the
  1372. * whole packet starting at pkt->data (including some header), and
  1373. * pkt->body refers to the point within that where the log-worthy
  1374. * payload begins. However, incoming packets expect pkt->length to
  1375. * represent only the payload length (that is, it's measured from
  1376. * pkt->body not from pkt->data). Temporarily adjust our outgoing
  1377. * packet to conform to the incoming-packet semantics, so that we
  1378. * can analyse it with the ssh_pkt_get functions.
  1379. */
  1380. pkt->length -= (pkt->body - pkt->data);
  1381. pkt->savedpos = 0;
  1382. if (ssh->logomitdata &&
  1383. (pkt->type == SSH2_MSG_CHANNEL_DATA ||
  1384. pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
  1385. /* "Session data" packets - omit the data string. */
  1386. ssh_pkt_getuint32(pkt); /* skip channel id */
  1387. if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
  1388. ssh_pkt_getuint32(pkt); /* skip extended data type */
  1389. blanks[nblanks].offset = pkt->savedpos + 4;
  1390. blanks[nblanks].type = PKTLOG_OMIT;
  1391. ssh_pkt_getstring(pkt, &str, &slen);
  1392. if (str) {
  1393. blanks[nblanks].len = slen;
  1394. nblanks++;
  1395. }
  1396. }
  1397. if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
  1398. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1399. /* If this is a password packet, blank the password(s). */
  1400. pkt->savedpos = 0;
  1401. ssh_pkt_getstring(pkt, &str, &slen);
  1402. ssh_pkt_getstring(pkt, &str, &slen);
  1403. ssh_pkt_getstring(pkt, &str, &slen);
  1404. if (slen == 8 && !memcmp(str, "password", 8)) {
  1405. ssh2_pkt_getbool(pkt);
  1406. /* Blank the password field. */
  1407. blanks[nblanks].offset = pkt->savedpos;
  1408. blanks[nblanks].type = PKTLOG_BLANK;
  1409. ssh_pkt_getstring(pkt, &str, &slen);
  1410. if (str) {
  1411. blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
  1412. nblanks++;
  1413. /* If there's another password field beyond it (change of
  1414. * password), blank that too. */
  1415. ssh_pkt_getstring(pkt, &str, &slen);
  1416. if (str)
  1417. blanks[nblanks-1].len =
  1418. pkt->savedpos - blanks[nblanks].offset;
  1419. }
  1420. }
  1421. } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
  1422. pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
  1423. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1424. /* If this is a keyboard-interactive response packet, blank
  1425. * the responses. */
  1426. pkt->savedpos = 0;
  1427. ssh_pkt_getuint32(pkt);
  1428. blanks[nblanks].offset = pkt->savedpos;
  1429. blanks[nblanks].type = PKTLOG_BLANK;
  1430. while (1) {
  1431. ssh_pkt_getstring(pkt, &str, &slen);
  1432. if (!str)
  1433. break;
  1434. }
  1435. blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
  1436. nblanks++;
  1437. } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
  1438. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1439. /*
  1440. * If this is an X forwarding request packet, blank the fake
  1441. * auth data.
  1442. *
  1443. * Note that while we blank the X authentication data here, we
  1444. * don't take any special action to blank the start of an X11
  1445. * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
  1446. * an X connection without having session blanking enabled is
  1447. * likely to leak your cookie into the log.
  1448. */
  1449. pkt->savedpos = 0;
  1450. ssh_pkt_getuint32(pkt);
  1451. ssh_pkt_getstring(pkt, &str, &slen);
  1452. if (slen == 7 && !memcmp(str, "x11-req", 0)) {
  1453. ssh2_pkt_getbool(pkt);
  1454. ssh2_pkt_getbool(pkt);
  1455. ssh_pkt_getstring(pkt, &str, &slen);
  1456. blanks[nblanks].offset = pkt->savedpos;
  1457. blanks[nblanks].type = PKTLOG_BLANK;
  1458. ssh_pkt_getstring(pkt, &str, &slen);
  1459. if (str) {
  1460. blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
  1461. nblanks++;
  1462. }
  1463. }
  1464. }
  1465. log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
  1466. ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
  1467. pkt->body, pkt->length, nblanks, blanks,
  1468. &ssh->v2_outgoing_sequence,
  1469. pkt->downstream_id, pkt->additional_log_text);
  1470. /*
  1471. * Undo the above adjustment of pkt->length, to put the packet
  1472. * back in the state we found it.
  1473. */
  1474. pkt->length += (pkt->body - pkt->data);
  1475. }
  1476. static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
  1477. int *datalen)
  1478. {
  1479. struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
  1480. crBegin(ssh->ssh2_rdpkt_crstate);
  1481. st->pktin = ssh_new_packet();
  1482. st->pktin->type = 0;
  1483. st->pktin->length = 0;
  1484. if (ssh->sccipher)
  1485. st->cipherblk = ssh->sccipher->blksize;
  1486. else
  1487. st->cipherblk = 8;
  1488. if (st->cipherblk < 8)
  1489. st->cipherblk = 8;
  1490. st->maclen = ssh->scmac ? ssh->scmac->len : 0;
  1491. if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
  1492. ssh->scmac && !ssh->scmac_etm) {
  1493. /*
  1494. * When dealing with a CBC-mode cipher, we want to avoid the
  1495. * possibility of an attacker's tweaking the ciphertext stream
  1496. * so as to cause us to feed the same block to the block
  1497. * cipher more than once and thus leak information
  1498. * (VU#958563). The way we do this is not to take any
  1499. * decisions on the basis of anything we've decrypted until
  1500. * we've verified it with a MAC. That includes the packet
  1501. * length, so we just read data and check the MAC repeatedly,
  1502. * and when the MAC passes, see if the length we've got is
  1503. * plausible.
  1504. *
  1505. * This defence is unnecessary in OpenSSH ETM mode, because
  1506. * the whole point of ETM mode is that the attacker can't
  1507. * tweak the ciphertext stream at all without the MAC
  1508. * detecting it before we decrypt anything.
  1509. */
  1510. /* May as well allocate the whole lot now. */
  1511. st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
  1512. unsigned char);
  1513. /* Read an amount corresponding to the MAC. */
  1514. for (st->i = 0; st->i < st->maclen; st->i++) {
  1515. while ((*datalen) == 0)
  1516. crReturn(NULL);
  1517. st->pktin->data[st->i] = *(*data)++;
  1518. (*datalen)--;
  1519. }
  1520. st->packetlen = 0;
  1521. {
  1522. unsigned char seq[4];
  1523. ssh->scmac->start(ssh->sc_mac_ctx);
  1524. PUT_32BIT(seq, st->incoming_sequence);
  1525. ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
  1526. }
  1527. for (;;) { /* Once around this loop per cipher block. */
  1528. /* Read another cipher-block's worth, and tack it onto the end. */
  1529. for (st->i = 0; st->i < st->cipherblk; st->i++) {
  1530. while ((*datalen) == 0)
  1531. crReturn(NULL);
  1532. st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
  1533. (*datalen)--;
  1534. }
  1535. /* Decrypt one more block (a little further back in the stream). */
  1536. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  1537. st->pktin->data + st->packetlen,
  1538. st->cipherblk);
  1539. /* Feed that block to the MAC. */
  1540. ssh->scmac->bytes(ssh->sc_mac_ctx,
  1541. st->pktin->data + st->packetlen, st->cipherblk);
  1542. st->packetlen += st->cipherblk;
  1543. /* See if that gives us a valid packet. */
  1544. if (ssh->scmac->verresult(ssh->sc_mac_ctx,
  1545. st->pktin->data + st->packetlen) &&
  1546. ((st->len = toint(GET_32BIT(st->pktin->data))) ==
  1547. st->packetlen-4))
  1548. break;
  1549. if (st->packetlen >= OUR_V2_PACKETLIMIT) {
  1550. bombout(("No valid incoming packet found"));
  1551. ssh_free_packet(st->pktin);
  1552. crStop(NULL);
  1553. }
  1554. }
  1555. st->pktin->maxlen = st->packetlen + st->maclen;
  1556. st->pktin->data = sresize(st->pktin->data,
  1557. st->pktin->maxlen + APIEXTRA,
  1558. unsigned char);
  1559. } else if (ssh->scmac && ssh->scmac_etm) {
  1560. st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
  1561. /*
  1562. * OpenSSH encrypt-then-MAC mode: the packet length is
  1563. * unencrypted, unless the cipher supports length encryption.
  1564. */
  1565. for (st->i = st->len = 0; st->i < 4; st->i++) {
  1566. while ((*datalen) == 0)
  1567. crReturn(NULL);
  1568. st->pktin->data[st->i] = *(*data)++;
  1569. (*datalen)--;
  1570. }
  1571. /* Cipher supports length decryption, so do it */
  1572. if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
  1573. /* Keep the packet the same though, so the MAC passes */
  1574. unsigned char len[4];
  1575. memcpy(len, st->pktin->data, 4);
  1576. ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
  1577. st->len = toint(GET_32BIT(len));
  1578. } else {
  1579. st->len = toint(GET_32BIT(st->pktin->data));
  1580. }
  1581. /*
  1582. * _Completely_ silly lengths should be stomped on before they
  1583. * do us any more damage.
  1584. */
  1585. if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
  1586. st->len % st->cipherblk != 0) {
  1587. bombout(("Incoming packet length field was garbled"));
  1588. ssh_free_packet(st->pktin);
  1589. crStop(NULL);
  1590. }
  1591. /*
  1592. * So now we can work out the total packet length.
  1593. */
  1594. st->packetlen = st->len + 4;
  1595. /*
  1596. * Allocate memory for the rest of the packet.
  1597. */
  1598. st->pktin->maxlen = st->packetlen + st->maclen;
  1599. st->pktin->data = sresize(st->pktin->data,
  1600. st->pktin->maxlen + APIEXTRA,
  1601. unsigned char);
  1602. /*
  1603. * Read the remainder of the packet.
  1604. */
  1605. for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
  1606. while ((*datalen) == 0)
  1607. crReturn(NULL);
  1608. st->pktin->data[st->i] = *(*data)++;
  1609. (*datalen)--;
  1610. }
  1611. /*
  1612. * Check the MAC.
  1613. */
  1614. if (ssh->scmac
  1615. && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
  1616. st->len + 4, st->incoming_sequence)) {
  1617. bombout(("Incorrect MAC received on packet"));
  1618. ssh_free_packet(st->pktin);
  1619. crStop(NULL);
  1620. }
  1621. /* Decrypt everything between the length field and the MAC. */
  1622. if (ssh->sccipher)
  1623. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  1624. st->pktin->data + 4,
  1625. st->packetlen - 4);
  1626. } else {
  1627. st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
  1628. /*
  1629. * Acquire and decrypt the first block of the packet. This will
  1630. * contain the length and padding details.
  1631. */
  1632. for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
  1633. while ((*datalen) == 0)
  1634. crReturn(NULL);
  1635. st->pktin->data[st->i] = *(*data)++;
  1636. (*datalen)--;
  1637. }
  1638. if (ssh->sccipher)
  1639. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  1640. st->pktin->data, st->cipherblk);
  1641. /*
  1642. * Now get the length figure.
  1643. */
  1644. st->len = toint(GET_32BIT(st->pktin->data));
  1645. /*
  1646. * _Completely_ silly lengths should be stomped on before they
  1647. * do us any more damage.
  1648. */
  1649. if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
  1650. (st->len + 4) % st->cipherblk != 0) {
  1651. bombout(("Incoming packet was garbled on decryption"));
  1652. ssh_free_packet(st->pktin);
  1653. crStop(NULL);
  1654. }
  1655. /*
  1656. * So now we can work out the total packet length.
  1657. */
  1658. st->packetlen = st->len + 4;
  1659. /*
  1660. * Allocate memory for the rest of the packet.
  1661. */
  1662. st->pktin->maxlen = st->packetlen + st->maclen;
  1663. st->pktin->data = sresize(st->pktin->data,
  1664. st->pktin->maxlen + APIEXTRA,
  1665. unsigned char);
  1666. /*
  1667. * Read and decrypt the remainder of the packet.
  1668. */
  1669. for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
  1670. st->i++) {
  1671. while ((*datalen) == 0)
  1672. crReturn(NULL);
  1673. st->pktin->data[st->i] = *(*data)++;
  1674. (*datalen)--;
  1675. }
  1676. /* Decrypt everything _except_ the MAC. */
  1677. if (ssh->sccipher)
  1678. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  1679. st->pktin->data + st->cipherblk,
  1680. st->packetlen - st->cipherblk);
  1681. /*
  1682. * Check the MAC.
  1683. */
  1684. if (ssh->scmac
  1685. && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
  1686. st->len + 4, st->incoming_sequence)) {
  1687. bombout(("Incorrect MAC received on packet"));
  1688. ssh_free_packet(st->pktin);
  1689. crStop(NULL);
  1690. }
  1691. }
  1692. /* Get and sanity-check the amount of random padding. */
  1693. st->pad = st->pktin->data[4];
  1694. if (st->pad < 4 || st->len - st->pad < 1) {
  1695. bombout(("Invalid padding length on received packet"));
  1696. ssh_free_packet(st->pktin);
  1697. crStop(NULL);
  1698. }
  1699. /*
  1700. * This enables us to deduce the payload length.
  1701. */
  1702. st->payload = st->len - st->pad - 1;
  1703. st->pktin->length = st->payload + 5;
  1704. st->pktin->encrypted_len = st->packetlen;
  1705. st->pktin->sequence = st->incoming_sequence++;
  1706. st->pktin->length = st->packetlen - st->pad;
  1707. assert(st->pktin->length >= 0);
  1708. /*
  1709. * Decompress packet payload.
  1710. */
  1711. {
  1712. unsigned char *newpayload;
  1713. int newlen;
  1714. if (ssh->sccomp &&
  1715. ssh->sccomp->decompress(ssh->sc_comp_ctx,
  1716. st->pktin->data + 5, st->pktin->length - 5,
  1717. &newpayload, &newlen)) {
  1718. if (st->pktin->maxlen < newlen + 5) {
  1719. st->pktin->maxlen = newlen + 5;
  1720. st->pktin->data = sresize(st->pktin->data,
  1721. st->pktin->maxlen + APIEXTRA,
  1722. unsigned char);
  1723. }
  1724. st->pktin->length = 5 + newlen;
  1725. memcpy(st->pktin->data + 5, newpayload, newlen);
  1726. sfree(newpayload);
  1727. }
  1728. }
  1729. /*
  1730. * RFC 4253 doesn't explicitly say that completely empty packets
  1731. * with no type byte are forbidden, so treat them as deserving
  1732. * an SSH_MSG_UNIMPLEMENTED.
  1733. */
  1734. if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
  1735. ssh2_msg_something_unimplemented(ssh, st->pktin);
  1736. crStop(NULL);
  1737. }
  1738. /*
  1739. * pktin->body and pktin->length should identify the semantic
  1740. * content of the packet, excluding the initial type byte.
  1741. */
  1742. st->pktin->type = st->pktin->data[5];
  1743. st->pktin->body = st->pktin->data + 6;
  1744. st->pktin->length -= 6;
  1745. assert(st->pktin->length >= 0); /* one last double-check */
  1746. if (ssh->logctx)
  1747. ssh2_log_incoming_packet(ssh, st->pktin);
  1748. st->pktin->savedpos = 0;
  1749. crFinish(st->pktin);
  1750. }
  1751. static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
  1752. const unsigned char **data,
  1753. int *datalen)
  1754. {
  1755. struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
  1756. crBegin(ssh->ssh2_bare_rdpkt_crstate);
  1757. /*
  1758. * Read the packet length field.
  1759. */
  1760. for (st->i = 0; st->i < 4; st->i++) {
  1761. while ((*datalen) == 0)
  1762. crReturn(NULL);
  1763. st->length[st->i] = *(*data)++;
  1764. (*datalen)--;
  1765. }
  1766. st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
  1767. if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
  1768. bombout(("Invalid packet length received"));
  1769. crStop(NULL);
  1770. }
  1771. st->pktin = ssh_new_packet();
  1772. st->pktin->data = snewn(st->packetlen, unsigned char);
  1773. st->pktin->encrypted_len = st->packetlen;
  1774. st->pktin->sequence = st->incoming_sequence++;
  1775. /*
  1776. * Read the remainder of the packet.
  1777. */
  1778. for (st->i = 0; st->i < st->packetlen; st->i++) {
  1779. while ((*datalen) == 0)
  1780. crReturn(NULL);
  1781. st->pktin->data[st->i] = *(*data)++;
  1782. (*datalen)--;
  1783. }
  1784. /*
  1785. * pktin->body and pktin->length should identify the semantic
  1786. * content of the packet, excluding the initial type byte.
  1787. */
  1788. st->pktin->type = st->pktin->data[0];
  1789. st->pktin->body = st->pktin->data + 1;
  1790. st->pktin->length = st->packetlen - 1;
  1791. /*
  1792. * Log incoming packet, possibly omitting sensitive fields.
  1793. */
  1794. if (ssh->logctx)
  1795. ssh2_log_incoming_packet(ssh, st->pktin);
  1796. st->pktin->savedpos = 0;
  1797. crFinish(st->pktin);
  1798. }
  1799. static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
  1800. {
  1801. int pad, biglen, i, pktoffs;
  1802. unsigned long crc;
  1803. #ifdef __SC__
  1804. /*
  1805. * XXX various versions of SC (including 8.8.4) screw up the
  1806. * register allocation in this function and use the same register
  1807. * (D6) for len and as a temporary, with predictable results. The
  1808. * following sledgehammer prevents this.
  1809. */
  1810. volatile
  1811. #endif
  1812. int len;
  1813. if (ssh->logctx)
  1814. ssh1_log_outgoing_packet(ssh, pkt);
  1815. if (ssh->v1_compressing) {
  1816. unsigned char *compblk;
  1817. int complen;
  1818. zlib_compress_block(ssh->cs_comp_ctx,
  1819. pkt->data + 12, pkt->length - 12,
  1820. &compblk, &complen);
  1821. ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
  1822. memcpy(pkt->data + 12, compblk, complen);
  1823. sfree(compblk);
  1824. pkt->length = complen + 12;
  1825. }
  1826. ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
  1827. pkt->length += 4;
  1828. len = pkt->length - 4 - 8; /* len(type+data+CRC) */
  1829. pad = 8 - (len % 8);
  1830. pktoffs = 8 - pad;
  1831. biglen = len + pad; /* len(padding+type+data+CRC) */
  1832. for (i = pktoffs; i < 4+8; i++)
  1833. pkt->data[i] = random_byte();
  1834. crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
  1835. PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
  1836. PUT_32BIT(pkt->data + pktoffs, len);
  1837. if (ssh->cipher)
  1838. ssh->cipher->encrypt(ssh->v1_cipher_ctx,
  1839. pkt->data + pktoffs + 4, biglen);
  1840. if (offset_p) *offset_p = pktoffs;
  1841. return biglen + 4; /* len(length+padding+type+data+CRC) */
  1842. }
  1843. static int s_write(Ssh ssh, void *data, int len)
  1844. {
  1845. if (ssh->logctx)
  1846. log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
  1847. 0, NULL, NULL, 0, NULL);
  1848. if (!ssh->s)
  1849. return 0;
  1850. return sk_write(ssh->s, (char *)data, len);
  1851. }
  1852. static void s_wrpkt(Ssh ssh, struct Packet *pkt)
  1853. {
  1854. int len, backlog, offset;
  1855. len = s_wrpkt_prepare(ssh, pkt, &offset);
  1856. backlog = s_write(ssh, pkt->data + offset, len);
  1857. if (backlog > SSH_MAX_BACKLOG)
  1858. {
  1859. ssh_throttle_all(ssh, 1, backlog);
  1860. }
  1861. ssh_free_packet(pkt);
  1862. }
  1863. static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
  1864. {
  1865. int len, offset;
  1866. len = s_wrpkt_prepare(ssh, pkt, &offset);
  1867. if (ssh->deferred_len + len > ssh->deferred_size) {
  1868. ssh->deferred_size = ssh->deferred_len + len + 128;
  1869. ssh->deferred_send_data = sresize(ssh->deferred_send_data,
  1870. ssh->deferred_size,
  1871. unsigned char);
  1872. }
  1873. memcpy(ssh->deferred_send_data + ssh->deferred_len,
  1874. pkt->data + offset, len);
  1875. ssh->deferred_len += len;
  1876. ssh_free_packet(pkt);
  1877. }
  1878. /*
  1879. * Construct a SSH-1 packet with the specified contents.
  1880. * (This all-at-once interface used to be the only one, but now SSH-1
  1881. * packets can also be constructed incrementally.)
  1882. */
  1883. static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
  1884. {
  1885. int argtype;
  1886. Bignum bn;
  1887. struct Packet *pkt;
  1888. pkt = ssh1_pkt_init(pkttype);
  1889. while ((argtype = va_arg(ap, int)) != PKT_END) {
  1890. unsigned char *argp, argchar;
  1891. char *sargp;
  1892. unsigned long argint;
  1893. int arglen;
  1894. switch (argtype) {
  1895. /* Actual fields in the packet */
  1896. case PKT_INT:
  1897. argint = va_arg(ap, int);
  1898. ssh_pkt_adduint32(pkt, argint);
  1899. break;
  1900. case PKT_CHAR:
  1901. argchar = (unsigned char) va_arg(ap, int);
  1902. ssh_pkt_addbyte(pkt, argchar);
  1903. break;
  1904. case PKT_DATA:
  1905. argp = va_arg(ap, unsigned char *);
  1906. arglen = va_arg(ap, int);
  1907. ssh_pkt_adddata(pkt, argp, arglen);
  1908. break;
  1909. case PKT_STR:
  1910. sargp = va_arg(ap, char *);
  1911. ssh_pkt_addstring(pkt, sargp);
  1912. break;
  1913. case PKT_BIGNUM:
  1914. bn = va_arg(ap, Bignum);
  1915. ssh1_pkt_addmp(pkt, bn);
  1916. break;
  1917. }
  1918. }
  1919. return pkt;
  1920. }
  1921. static void send_packet(Ssh ssh, int pkttype, ...)
  1922. {
  1923. struct Packet *pkt;
  1924. va_list ap;
  1925. va_start(ap, pkttype);
  1926. pkt = construct_packet(ssh, pkttype, ap);
  1927. va_end(ap);
  1928. s_wrpkt(ssh, pkt);
  1929. }
  1930. static void defer_packet(Ssh ssh, int pkttype, ...)
  1931. {
  1932. struct Packet *pkt;
  1933. va_list ap;
  1934. va_start(ap, pkttype);
  1935. pkt = construct_packet(ssh, pkttype, ap);
  1936. va_end(ap);
  1937. s_wrpkt_defer(ssh, pkt);
  1938. }
  1939. static int ssh_versioncmp(const char *a, const char *b)
  1940. {
  1941. char *ae, *be;
  1942. unsigned long av, bv;
  1943. av = strtoul(a, &ae, 10);
  1944. bv = strtoul(b, &be, 10);
  1945. if (av != bv)
  1946. return (av < bv ? -1 : +1);
  1947. if (*ae == '.')
  1948. ae++;
  1949. if (*be == '.')
  1950. be++;
  1951. av = strtoul(ae, &ae, 10);
  1952. bv = strtoul(be, &be, 10);
  1953. if (av != bv)
  1954. return (av < bv ? -1 : +1);
  1955. return 0;
  1956. }
  1957. /*
  1958. * Utility routines for putting an SSH-protocol `string' and
  1959. * `uint32' into a hash state.
  1960. */
  1961. static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
  1962. {
  1963. unsigned char lenblk[4];
  1964. PUT_32BIT(lenblk, len);
  1965. h->bytes(s, lenblk, 4);
  1966. h->bytes(s, str, len);
  1967. }
  1968. static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
  1969. {
  1970. unsigned char intblk[4];
  1971. PUT_32BIT(intblk, i);
  1972. h->bytes(s, intblk, 4);
  1973. }
  1974. /*
  1975. * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
  1976. */
  1977. static void ssh_pkt_ensure(struct Packet *pkt, int length)
  1978. {
  1979. if (pkt->maxlen < length) {
  1980. unsigned char *body = pkt->body;
  1981. int offset = body ? body - pkt->data : 0;
  1982. pkt->maxlen = length + 256;
  1983. pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
  1984. if (body) pkt->body = pkt->data + offset;
  1985. }
  1986. }
  1987. static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
  1988. {
  1989. pkt->length += len;
  1990. ssh_pkt_ensure(pkt, pkt->length);
  1991. memcpy(pkt->data + pkt->length - len, data, len);
  1992. }
  1993. static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
  1994. {
  1995. ssh_pkt_adddata(pkt, &byte, 1);
  1996. }
  1997. static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
  1998. {
  1999. ssh_pkt_adddata(pkt, &value, 1);
  2000. }
  2001. static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
  2002. {
  2003. unsigned char x[4];
  2004. PUT_32BIT(x, value);
  2005. ssh_pkt_adddata(pkt, x, 4);
  2006. }
  2007. static void ssh_pkt_addstring_start(struct Packet *pkt)
  2008. {
  2009. ssh_pkt_adduint32(pkt, 0);
  2010. pkt->savedpos = pkt->length;
  2011. }
  2012. static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
  2013. int len)
  2014. {
  2015. ssh_pkt_adddata(pkt, data, len);
  2016. PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
  2017. }
  2018. static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
  2019. {
  2020. ssh_pkt_addstring_data(pkt, data, strlen(data));
  2021. }
  2022. static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
  2023. {
  2024. ssh_pkt_addstring_start(pkt);
  2025. ssh_pkt_addstring_str(pkt, data);
  2026. }
  2027. static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
  2028. {
  2029. int len = ssh1_bignum_length(b);
  2030. unsigned char *data = snewn(len, unsigned char);
  2031. (void) ssh1_write_bignum(data, b);
  2032. ssh_pkt_adddata(pkt, data, len);
  2033. sfree(data);
  2034. }
  2035. static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
  2036. {
  2037. unsigned char *p;
  2038. int i, n = (bignum_bitcount(b) + 7) / 8;
  2039. p = snewn(n + 1, unsigned char);
  2040. p[0] = 0;
  2041. for (i = 1; i <= n; i++)
  2042. p[i] = bignum_byte(b, n - i);
  2043. i = 0;
  2044. while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
  2045. i++;
  2046. memmove(p, p + i, n + 1 - i);
  2047. *len = n + 1 - i;
  2048. return p;
  2049. }
  2050. static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
  2051. {
  2052. unsigned char *p;
  2053. int len;
  2054. p = ssh2_mpint_fmt(b, &len);
  2055. ssh_pkt_addstring_start(pkt);
  2056. ssh_pkt_addstring_data(pkt, (char *)p, len);
  2057. sfree(p);
  2058. }
  2059. static struct Packet *ssh1_pkt_init(int pkt_type)
  2060. {
  2061. struct Packet *pkt = ssh_new_packet();
  2062. pkt->length = 4 + 8; /* space for length + max padding */
  2063. ssh_pkt_addbyte(pkt, pkt_type);
  2064. pkt->body = pkt->data + pkt->length;
  2065. pkt->type = pkt_type;
  2066. pkt->downstream_id = 0;
  2067. pkt->additional_log_text = NULL;
  2068. return pkt;
  2069. }
  2070. /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
  2071. #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
  2072. #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
  2073. #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
  2074. #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
  2075. #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
  2076. #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
  2077. #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
  2078. #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
  2079. static struct Packet *ssh2_pkt_init(int pkt_type)
  2080. {
  2081. struct Packet *pkt = ssh_new_packet();
  2082. pkt->length = 5; /* space for packet length + padding length */
  2083. pkt->forcepad = 0;
  2084. pkt->type = pkt_type;
  2085. ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
  2086. pkt->body = pkt->data + pkt->length; /* after packet type */
  2087. pkt->downstream_id = 0;
  2088. pkt->additional_log_text = NULL;
  2089. return pkt;
  2090. }
  2091. /*
  2092. * Construct an SSH-2 final-form packet: compress it, encrypt it,
  2093. * put the MAC on it. Final packet, ready to be sent, is stored in
  2094. * pkt->data. Total length is returned.
  2095. */
  2096. static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
  2097. {
  2098. int cipherblk, maclen, padding, unencrypted_prefix, i;
  2099. if (ssh->logctx)
  2100. ssh2_log_outgoing_packet(ssh, pkt);
  2101. if (ssh->bare_connection) {
  2102. /*
  2103. * Trivial packet construction for the bare connection
  2104. * protocol.
  2105. */
  2106. PUT_32BIT(pkt->data + 1, pkt->length - 5);
  2107. pkt->body = pkt->data + 1;
  2108. ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
  2109. return pkt->length - 1;
  2110. }
  2111. /*
  2112. * Compress packet payload.
  2113. */
  2114. {
  2115. unsigned char *newpayload;
  2116. int newlen;
  2117. if (ssh->cscomp &&
  2118. ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
  2119. pkt->length - 5,
  2120. &newpayload, &newlen)) {
  2121. pkt->length = 5;
  2122. ssh2_pkt_adddata(pkt, newpayload, newlen);
  2123. sfree(newpayload);
  2124. }
  2125. }
  2126. /*
  2127. * Add padding. At least four bytes, and must also bring total
  2128. * length (minus MAC) up to a multiple of the block size.
  2129. * If pkt->forcepad is set, make sure the packet is at least that size
  2130. * after padding.
  2131. */
  2132. cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
  2133. cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
  2134. padding = 4;
  2135. unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
  2136. if (pkt->length + padding < pkt->forcepad)
  2137. padding = pkt->forcepad - pkt->length;
  2138. padding +=
  2139. (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
  2140. % cipherblk;
  2141. assert(padding <= 255);
  2142. maclen = ssh->csmac ? ssh->csmac->len : 0;
  2143. ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
  2144. pkt->data[4] = padding;
  2145. for (i = 0; i < padding; i++)
  2146. pkt->data[pkt->length + i] = random_byte();
  2147. PUT_32BIT(pkt->data, pkt->length + padding - 4);
  2148. /* Encrypt length if the scheme requires it */
  2149. if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
  2150. ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
  2151. ssh->v2_outgoing_sequence);
  2152. }
  2153. if (ssh->csmac && ssh->csmac_etm) {
  2154. /*
  2155. * OpenSSH-defined encrypt-then-MAC protocol.
  2156. */
  2157. if (ssh->cscipher)
  2158. ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
  2159. pkt->data + 4, pkt->length + padding - 4);
  2160. ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
  2161. pkt->length + padding,
  2162. ssh->v2_outgoing_sequence);
  2163. } else {
  2164. /*
  2165. * SSH-2 standard protocol.
  2166. */
  2167. if (ssh->csmac)
  2168. ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
  2169. pkt->length + padding,
  2170. ssh->v2_outgoing_sequence);
  2171. if (ssh->cscipher)
  2172. ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
  2173. pkt->data, pkt->length + padding);
  2174. }
  2175. ssh->v2_outgoing_sequence++; /* whether or not we MACed */
  2176. pkt->encrypted_len = pkt->length + padding;
  2177. /* Ready-to-send packet starts at pkt->data. We return length. */
  2178. pkt->body = pkt->data;
  2179. return pkt->length + padding + maclen;
  2180. }
  2181. /*
  2182. * Routines called from the main SSH code to send packets. There
  2183. * are quite a few of these, because we have two separate
  2184. * mechanisms for delaying the sending of packets:
  2185. *
  2186. * - In order to send an IGNORE message and a password message in
  2187. * a single fixed-length blob, we require the ability to
  2188. * concatenate the encrypted forms of those two packets _into_ a
  2189. * single blob and then pass it to our <network.h> transport
  2190. * layer in one go. Hence, there's a deferment mechanism which
  2191. * works after packet encryption.
  2192. *
  2193. * - In order to avoid sending any connection-layer messages
  2194. * during repeat key exchange, we have to queue up any such
  2195. * outgoing messages _before_ they are encrypted (and in
  2196. * particular before they're allocated sequence numbers), and
  2197. * then send them once we've finished.
  2198. *
  2199. * I call these mechanisms `defer' and `queue' respectively, so as
  2200. * to distinguish them reasonably easily.
  2201. *
  2202. * The functions send_noqueue() and defer_noqueue() free the packet
  2203. * structure they are passed. Every outgoing packet goes through
  2204. * precisely one of these functions in its life; packets passed to
  2205. * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
  2206. * these or get queued, and then when the queue is later emptied
  2207. * the packets are all passed to defer_noqueue().
  2208. *
  2209. * When using a CBC-mode cipher, it's necessary to ensure that an
  2210. * attacker can't provide data to be encrypted using an IV that they
  2211. * know. We ensure this by prefixing each packet that might contain
  2212. * user data with an SSH_MSG_IGNORE. This is done using the deferral
  2213. * mechanism, so in this case send_noqueue() ends up redirecting to
  2214. * defer_noqueue(). If you don't like this inefficiency, don't use
  2215. * CBC.
  2216. */
  2217. static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
  2218. static void ssh_pkt_defersend(Ssh);
  2219. /*
  2220. * Send an SSH-2 packet immediately, without queuing or deferring.
  2221. */
  2222. static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
  2223. {
  2224. int len;
  2225. int backlog;
  2226. if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
  2227. /* We need to send two packets, so use the deferral mechanism. */
  2228. ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
  2229. ssh_pkt_defersend(ssh);
  2230. return;
  2231. }
  2232. len = ssh2_pkt_construct(ssh, pkt);
  2233. backlog = s_write(ssh, pkt->body, len);
  2234. if (backlog > SSH_MAX_BACKLOG)
  2235. {
  2236. ssh_throttle_all(ssh, 1, backlog);
  2237. }
  2238. ssh->outgoing_data_size += pkt->encrypted_len;
  2239. if (!ssh->kex_in_progress &&
  2240. !ssh->bare_connection &&
  2241. ssh->max_data_size != 0 &&
  2242. ssh->outgoing_data_size > ssh->max_data_size)
  2243. do_ssh2_transport(ssh, "too much data sent", -1, NULL);
  2244. ssh_free_packet(pkt);
  2245. }
  2246. /*
  2247. * Defer an SSH-2 packet.
  2248. */
  2249. static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
  2250. {
  2251. int len;
  2252. if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
  2253. ssh->deferred_len == 0 && !noignore &&
  2254. !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
  2255. /*
  2256. * Interpose an SSH_MSG_IGNORE to ensure that user data don't
  2257. * get encrypted with a known IV.
  2258. */
  2259. struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
  2260. ssh2_pkt_addstring_start(ipkt);
  2261. ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
  2262. }
  2263. len = ssh2_pkt_construct(ssh, pkt);
  2264. if (ssh->deferred_len + len > ssh->deferred_size) {
  2265. ssh->deferred_size = ssh->deferred_len + len + 128;
  2266. ssh->deferred_send_data = sresize(ssh->deferred_send_data,
  2267. ssh->deferred_size,
  2268. unsigned char);
  2269. }
  2270. memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
  2271. ssh->deferred_len += len;
  2272. ssh->deferred_data_size += pkt->encrypted_len;
  2273. ssh_free_packet(pkt);
  2274. }
  2275. /*
  2276. * Queue an SSH-2 packet.
  2277. */
  2278. static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
  2279. {
  2280. assert(ssh->queueing);
  2281. if (ssh->queuelen >= ssh->queuesize) {
  2282. ssh->queuesize = ssh->queuelen + 32;
  2283. ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
  2284. }
  2285. ssh->queue[ssh->queuelen++] = pkt;
  2286. }
  2287. /*
  2288. * Either queue or send a packet, depending on whether queueing is
  2289. * set.
  2290. */
  2291. static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
  2292. {
  2293. if (ssh->queueing)
  2294. ssh2_pkt_queue(ssh, pkt);
  2295. else
  2296. ssh2_pkt_send_noqueue(ssh, pkt);
  2297. }
  2298. /*
  2299. * Either queue or defer a packet, depending on whether queueing is
  2300. * set.
  2301. */
  2302. static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
  2303. {
  2304. if (ssh->queueing)
  2305. ssh2_pkt_queue(ssh, pkt);
  2306. else
  2307. ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
  2308. }
  2309. /*
  2310. * Send the whole deferred data block constructed by
  2311. * ssh2_pkt_defer() or SSH-1's defer_packet().
  2312. *
  2313. * The expected use of the defer mechanism is that you call
  2314. * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
  2315. * not currently queueing, this simply sets up deferred_send_data
  2316. * and then sends it. If we _are_ currently queueing, the calls to
  2317. * ssh2_pkt_defer() put the deferred packets on to the queue
  2318. * instead, and therefore ssh_pkt_defersend() has no deferred data
  2319. * to send. Hence, there's no need to make it conditional on
  2320. * ssh->queueing.
  2321. */
  2322. static void ssh_pkt_defersend(Ssh ssh)
  2323. {
  2324. int backlog;
  2325. backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
  2326. ssh->deferred_len = ssh->deferred_size = 0;
  2327. sfree(ssh->deferred_send_data);
  2328. ssh->deferred_send_data = NULL;
  2329. if (backlog > SSH_MAX_BACKLOG)
  2330. {
  2331. ssh_throttle_all(ssh, 1, backlog);
  2332. }
  2333. if (ssh->version == 2) {
  2334. ssh->outgoing_data_size += ssh->deferred_data_size;
  2335. ssh->deferred_data_size = 0;
  2336. if (!ssh->kex_in_progress &&
  2337. !ssh->bare_connection &&
  2338. ssh->max_data_size != 0 &&
  2339. ssh->outgoing_data_size > ssh->max_data_size)
  2340. do_ssh2_transport(ssh, "too much data sent", -1, NULL);
  2341. }
  2342. }
  2343. /*
  2344. * Send a packet whose length needs to be disguised (typically
  2345. * passwords or keyboard-interactive responses).
  2346. */
  2347. static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
  2348. int padsize)
  2349. {
  2350. #if 0
  2351. if (0) {
  2352. /*
  2353. * The simplest way to do this is to adjust the
  2354. * variable-length padding field in the outgoing packet.
  2355. *
  2356. * Currently compiled out, because some Cisco SSH servers
  2357. * don't like excessively padded packets (bah, why's it
  2358. * always Cisco?)
  2359. */
  2360. pkt->forcepad = padsize;
  2361. ssh2_pkt_send(ssh, pkt);
  2362. } else
  2363. #endif
  2364. {
  2365. /*
  2366. * If we can't do that, however, an alternative approach is
  2367. * to use the pkt_defer mechanism to bundle the packet
  2368. * tightly together with an SSH_MSG_IGNORE such that their
  2369. * combined length is a constant. So first we construct the
  2370. * final form of this packet and defer its sending.
  2371. */
  2372. ssh2_pkt_defer(ssh, pkt);
  2373. /*
  2374. * Now construct an SSH_MSG_IGNORE which includes a string
  2375. * that's an exact multiple of the cipher block size. (If
  2376. * the cipher is NULL so that the block size is
  2377. * unavailable, we don't do this trick at all, because we
  2378. * gain nothing by it.)
  2379. */
  2380. if (ssh->cscipher &&
  2381. !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
  2382. int stringlen, i;
  2383. stringlen = (256 - ssh->deferred_len);
  2384. stringlen += ssh->cscipher->blksize - 1;
  2385. stringlen -= (stringlen % ssh->cscipher->blksize);
  2386. if (ssh->cscomp) {
  2387. /*
  2388. * Temporarily disable actual compression, so we
  2389. * can guarantee to get this string exactly the
  2390. * length we want it. The compression-disabling
  2391. * routine should return an integer indicating how
  2392. * many bytes we should adjust our string length
  2393. * by.
  2394. */
  2395. stringlen -=
  2396. ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
  2397. }
  2398. pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
  2399. ssh2_pkt_addstring_start(pkt);
  2400. for (i = 0; i < stringlen; i++) {
  2401. char c = (char) random_byte();
  2402. ssh2_pkt_addstring_data(pkt, &c, 1);
  2403. }
  2404. ssh2_pkt_defer(ssh, pkt);
  2405. }
  2406. ssh_pkt_defersend(ssh);
  2407. }
  2408. }
  2409. /*
  2410. * Send all queued SSH-2 packets. We send them by means of
  2411. * ssh2_pkt_defer_noqueue(), in case they included a pair of
  2412. * packets that needed to be lumped together.
  2413. */
  2414. static void ssh2_pkt_queuesend(Ssh ssh)
  2415. {
  2416. int i;
  2417. assert(!ssh->queueing);
  2418. for (i = 0; i < ssh->queuelen; i++)
  2419. ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
  2420. ssh->queuelen = 0;
  2421. ssh_pkt_defersend(ssh);
  2422. }
  2423. #if 0
  2424. void bndebug(char *string, Bignum b)
  2425. {
  2426. unsigned char *p;
  2427. int i, len;
  2428. p = ssh2_mpint_fmt(b, &len);
  2429. debug(("%s", string));
  2430. for (i = 0; i < len; i++)
  2431. debug((" %02x", p[i]));
  2432. debug(("\n"));
  2433. sfree(p);
  2434. }
  2435. #endif
  2436. static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
  2437. {
  2438. unsigned char *p;
  2439. int len;
  2440. p = ssh2_mpint_fmt(b, &len);
  2441. hash_string(h, s, p, len);
  2442. sfree(p);
  2443. }
  2444. /*
  2445. * Packet decode functions for both SSH-1 and SSH-2.
  2446. */
  2447. static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
  2448. {
  2449. unsigned long value;
  2450. if (pkt->length - pkt->savedpos < 4)
  2451. return 0; /* arrgh, no way to decline (FIXME?) */
  2452. value = GET_32BIT(pkt->body + pkt->savedpos);
  2453. pkt->savedpos += 4;
  2454. return value;
  2455. }
  2456. static int ssh2_pkt_getbool(struct Packet *pkt)
  2457. {
  2458. unsigned long value;
  2459. if (pkt->length - pkt->savedpos < 1)
  2460. return 0; /* arrgh, no way to decline (FIXME?) */
  2461. value = pkt->body[pkt->savedpos] != 0;
  2462. pkt->savedpos++;
  2463. return value;
  2464. }
  2465. static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
  2466. {
  2467. int len;
  2468. *p = NULL;
  2469. *length = 0;
  2470. if (pkt->length - pkt->savedpos < 4)
  2471. return;
  2472. len = toint(GET_32BIT(pkt->body + pkt->savedpos));
  2473. if (len < 0)
  2474. return;
  2475. *length = len;
  2476. pkt->savedpos += 4;
  2477. if (pkt->length - pkt->savedpos < *length)
  2478. return;
  2479. *p = (char *)(pkt->body + pkt->savedpos);
  2480. pkt->savedpos += *length;
  2481. }
  2482. static void *ssh_pkt_getdata(struct Packet *pkt, int length)
  2483. {
  2484. if (pkt->length - pkt->savedpos < length)
  2485. return NULL;
  2486. pkt->savedpos += length;
  2487. return pkt->body + (pkt->savedpos - length);
  2488. }
  2489. static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
  2490. const unsigned char **keystr)
  2491. {
  2492. int j;
  2493. j = makekey(pkt->body + pkt->savedpos,
  2494. pkt->length - pkt->savedpos,
  2495. key, keystr, 0);
  2496. if (j < 0)
  2497. return FALSE;
  2498. pkt->savedpos += j;
  2499. assert(pkt->savedpos < pkt->length);
  2500. return TRUE;
  2501. }
  2502. static Bignum ssh1_pkt_getmp(struct Packet *pkt)
  2503. {
  2504. int j;
  2505. Bignum b;
  2506. j = ssh1_read_bignum(pkt->body + pkt->savedpos,
  2507. pkt->length - pkt->savedpos, &b);
  2508. if (j < 0)
  2509. return NULL;
  2510. pkt->savedpos += j;
  2511. return b;
  2512. }
  2513. static Bignum ssh2_pkt_getmp(struct Packet *pkt)
  2514. {
  2515. char *p;
  2516. int length;
  2517. Bignum b;
  2518. ssh_pkt_getstring(pkt, &p, &length);
  2519. if (!p)
  2520. return NULL;
  2521. if (p[0] & 0x80)
  2522. return NULL;
  2523. b = bignum_from_bytes((unsigned char *)p, length);
  2524. return b;
  2525. }
  2526. /*
  2527. * Helper function to add an SSH-2 signature blob to a packet.
  2528. * Expects to be shown the public key blob as well as the signature
  2529. * blob. Normally works just like ssh2_pkt_addstring, but will
  2530. * fiddle with the signature packet if necessary for
  2531. * BUG_SSH2_RSA_PADDING.
  2532. */
  2533. static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
  2534. void *pkblob_v, int pkblob_len,
  2535. void *sigblob_v, int sigblob_len)
  2536. {
  2537. unsigned char *pkblob = (unsigned char *)pkblob_v;
  2538. unsigned char *sigblob = (unsigned char *)sigblob_v;
  2539. /* dmemdump(pkblob, pkblob_len); */
  2540. /* dmemdump(sigblob, sigblob_len); */
  2541. /*
  2542. * See if this is in fact an ssh-rsa signature and a buggy
  2543. * server; otherwise we can just do this the easy way.
  2544. */
  2545. if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
  2546. (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
  2547. int pos, len, siglen;
  2548. /*
  2549. * Find the byte length of the modulus.
  2550. */
  2551. pos = 4+7; /* skip over "ssh-rsa" */
  2552. len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
  2553. if (len < 0 || len > pkblob_len - pos - 4)
  2554. goto give_up;
  2555. pos += 4 + len; /* skip over exponent */
  2556. if (pkblob_len - pos < 4)
  2557. goto give_up;
  2558. len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
  2559. if (len < 0 || len > pkblob_len - pos - 4)
  2560. goto give_up;
  2561. pos += 4; /* find modulus itself */
  2562. while (len > 0 && pkblob[pos] == 0)
  2563. len--, pos++;
  2564. /* debug(("modulus length is %d\n", len)); */
  2565. /*
  2566. * Now find the signature integer.
  2567. */
  2568. pos = 4+7; /* skip over "ssh-rsa" */
  2569. if (sigblob_len < pos+4)
  2570. goto give_up;
  2571. siglen = toint(GET_32BIT(sigblob+pos));
  2572. if (siglen != sigblob_len - pos - 4)
  2573. goto give_up;
  2574. /* debug(("signature length is %d\n", siglen)); */
  2575. if (len != siglen) {
  2576. unsigned char newlen[4];
  2577. ssh2_pkt_addstring_start(pkt);
  2578. ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
  2579. /* dmemdump(sigblob, pos); */
  2580. pos += 4; /* point to start of actual sig */
  2581. PUT_32BIT(newlen, len);
  2582. ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
  2583. /* dmemdump(newlen, 4); */
  2584. newlen[0] = 0;
  2585. while (len-- > siglen) {
  2586. ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
  2587. /* dmemdump(newlen, 1); */
  2588. }
  2589. ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
  2590. /* dmemdump(sigblob+pos, siglen); */
  2591. return;
  2592. }
  2593. /* Otherwise fall through and do it the easy way. We also come
  2594. * here as a fallback if we discover above that the key blob
  2595. * is misformatted in some way. */
  2596. give_up:;
  2597. }
  2598. ssh2_pkt_addstring_start(pkt);
  2599. ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
  2600. }
  2601. /*
  2602. * Examine the remote side's version string and compare it against
  2603. * a list of known buggy implementations.
  2604. */
  2605. static void ssh_detect_bugs(Ssh ssh, char *vstring)
  2606. {
  2607. char *imp; /* pointer to implementation part */
  2608. imp = vstring;
  2609. imp += strcspn(imp, "-");
  2610. if (*imp) imp++;
  2611. imp += strcspn(imp, "-");
  2612. if (*imp) imp++;
  2613. ssh->remote_bugs = 0;
  2614. /*
  2615. * General notes on server version strings:
  2616. * - Not all servers reporting "Cisco-1.25" have all the bugs listed
  2617. * here -- in particular, we've heard of one that's perfectly happy
  2618. * with SSH1_MSG_IGNOREs -- but this string never seems to change,
  2619. * so we can't distinguish them.
  2620. */
  2621. if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
  2622. (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
  2623. (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
  2624. !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
  2625. !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
  2626. !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
  2627. /*
  2628. * These versions don't support SSH1_MSG_IGNORE, so we have
  2629. * to use a different defence against password length
  2630. * sniffing.
  2631. */
  2632. ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
  2633. logevent("We believe remote version has SSH-1 ignore bug");
  2634. }
  2635. if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
  2636. (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
  2637. (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
  2638. /*
  2639. * These versions need a plain password sent; they can't
  2640. * handle having a null and a random length of data after
  2641. * the password.
  2642. */
  2643. ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
  2644. logevent("We believe remote version needs a plain SSH-1 password");
  2645. }
  2646. if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
  2647. (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
  2648. (!strcmp(imp, "Cisco-1.25")))) {
  2649. /*
  2650. * These versions apparently have no clue whatever about
  2651. * RSA authentication and will panic and die if they see
  2652. * an AUTH_RSA message.
  2653. */
  2654. ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
  2655. logevent("We believe remote version can't handle SSH-1 RSA authentication");
  2656. }
  2657. if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
  2658. (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
  2659. !wc_match("* VShell", imp) &&
  2660. (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
  2661. wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
  2662. wc_match("2.1 *", imp)))) {
  2663. /*
  2664. * These versions have the HMAC bug.
  2665. */
  2666. ssh->remote_bugs |= BUG_SSH2_HMAC;
  2667. logevent("We believe remote version has SSH-2 HMAC bug");
  2668. }
  2669. if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
  2670. (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
  2671. !wc_match("* VShell", imp) &&
  2672. (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
  2673. /*
  2674. * These versions have the key-derivation bug (failing to
  2675. * include the literal shared secret in the hashes that
  2676. * generate the keys).
  2677. */
  2678. ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
  2679. logevent("We believe remote version has SSH-2 key-derivation bug");
  2680. }
  2681. if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
  2682. (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
  2683. (wc_match("OpenSSH_2.[5-9]*", imp) ||
  2684. wc_match("OpenSSH_3.[0-2]*", imp) ||
  2685. wc_match("mod_sftp/0.[0-8]*", imp) ||
  2686. wc_match("mod_sftp/0.9.[0-8]", imp)))) {
  2687. /*
  2688. * These versions have the SSH-2 RSA padding bug.
  2689. */
  2690. ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
  2691. logevent("We believe remote version has SSH-2 RSA padding bug");
  2692. }
  2693. if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
  2694. (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
  2695. wc_match("OpenSSH_2.[0-2]*", imp))) {
  2696. /*
  2697. * These versions have the SSH-2 session-ID bug in
  2698. * public-key authentication.
  2699. */
  2700. ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
  2701. logevent("We believe remote version has SSH-2 public-key-session-ID bug");
  2702. }
  2703. if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
  2704. (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
  2705. (wc_match("DigiSSH_2.0", imp) ||
  2706. wc_match("OpenSSH_2.[0-4]*", imp) ||
  2707. wc_match("OpenSSH_2.5.[0-3]*", imp) ||
  2708. wc_match("Sun_SSH_1.0", imp) ||
  2709. wc_match("Sun_SSH_1.0.1", imp) ||
  2710. /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
  2711. wc_match("WeOnlyDo-*", imp)))) {
  2712. /*
  2713. * These versions have the SSH-2 rekey bug.
  2714. */
  2715. ssh->remote_bugs |= BUG_SSH2_REKEY;
  2716. logevent("We believe remote version has SSH-2 rekey bug");
  2717. }
  2718. if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
  2719. (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
  2720. (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
  2721. wc_match("1.36 sshlib: GlobalScape", imp)))) {
  2722. /*
  2723. * This version ignores our makpkt and needs to be throttled.
  2724. */
  2725. ssh->remote_bugs |= BUG_SSH2_MAXPKT;
  2726. logevent("We believe remote version ignores SSH-2 maximum packet size");
  2727. }
  2728. if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
  2729. /*
  2730. * Servers that don't support SSH2_MSG_IGNORE. Currently,
  2731. * none detected automatically.
  2732. */
  2733. ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
  2734. logevent("We believe remote version has SSH-2 ignore bug");
  2735. }
  2736. if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
  2737. (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
  2738. (wc_match("OpenSSH_2.[235]*", imp)))) {
  2739. /*
  2740. * These versions only support the original (pre-RFC4419)
  2741. * SSH-2 GEX request, and disconnect with a protocol error if
  2742. * we use the newer version.
  2743. */
  2744. ssh->remote_bugs |= BUG_SSH2_OLDGEX;
  2745. logevent("We believe remote version has outdated SSH-2 GEX");
  2746. }
  2747. if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
  2748. /*
  2749. * Servers that don't support our winadj request for one
  2750. * reason or another. Currently, none detected automatically.
  2751. */
  2752. ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
  2753. logevent("We believe remote version has winadj bug");
  2754. }
  2755. if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
  2756. (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
  2757. (wc_match("OpenSSH_[2-5].*", imp) ||
  2758. wc_match("OpenSSH_6.[0-6]*", imp) ||
  2759. wc_match("dropbear_0.[2-4][0-9]*", imp) ||
  2760. wc_match("dropbear_0.5[01]*", imp)))) {
  2761. /*
  2762. * These versions have the SSH-2 channel request bug.
  2763. * OpenSSH 6.7 and above do not:
  2764. * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
  2765. * dropbear_0.52 and above do not:
  2766. * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
  2767. */
  2768. ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
  2769. logevent("We believe remote version has SSH-2 channel request bug");
  2770. }
  2771. }
  2772. /*
  2773. * The `software version' part of an SSH version string is required
  2774. * to contain no spaces or minus signs.
  2775. */
  2776. static void ssh_fix_verstring(char *str)
  2777. {
  2778. /* Eat "<protoversion>-". */
  2779. while (*str && *str != '-') str++;
  2780. assert(*str == '-'); str++;
  2781. /* Convert minus signs and spaces in the remaining string into
  2782. * underscores. */
  2783. while (*str) {
  2784. if (*str == '-' || *str == ' ')
  2785. *str = '_';
  2786. str++;
  2787. }
  2788. }
  2789. /*
  2790. * Send an appropriate SSH version string.
  2791. */
  2792. static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
  2793. {
  2794. char *verstring;
  2795. if (ssh->version == 2) {
  2796. /*
  2797. * Construct a v2 version string.
  2798. */
  2799. verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
  2800. } else {
  2801. /*
  2802. * Construct a v1 version string.
  2803. */
  2804. assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
  2805. verstring = dupprintf("SSH-%s-%s\012",
  2806. (ssh_versioncmp(svers, "1.5") <= 0 ?
  2807. svers : "1.5"),
  2808. sshver);
  2809. }
  2810. ssh_fix_verstring(verstring + strlen(protoname));
  2811. #ifdef FUZZING
  2812. /* FUZZING make PuTTY insecure, so make live use difficult. */
  2813. verstring[0] = 'I';
  2814. #endif
  2815. if (ssh->version == 2) {
  2816. size_t len;
  2817. /*
  2818. * Record our version string.
  2819. */
  2820. len = strcspn(verstring, "\015\012");
  2821. ssh->v_c = snewn(len + 1, char);
  2822. memcpy(ssh->v_c, verstring, len);
  2823. ssh->v_c[len] = 0;
  2824. }
  2825. logeventf(ssh, "We claim version: %.*s",
  2826. strcspn(verstring, "\015\012"), verstring);
  2827. s_write(ssh, verstring, strlen(verstring));
  2828. sfree(verstring);
  2829. }
  2830. static int do_ssh_init(Ssh ssh, unsigned char c)
  2831. {
  2832. static const char protoname[] = "SSH-";
  2833. struct do_ssh_init_state {
  2834. int crLine;
  2835. int vslen;
  2836. char version[10];
  2837. char *vstring;
  2838. int vstrsize;
  2839. int i;
  2840. int proto1, proto2;
  2841. };
  2842. crState(do_ssh_init_state);
  2843. crBeginState;
  2844. /* Search for a line beginning with the protocol name prefix in
  2845. * the input. */
  2846. for (;;) {
  2847. for (s->i = 0; protoname[s->i]; s->i++) {
  2848. if ((char)c != protoname[s->i]) goto no;
  2849. crReturn(1);
  2850. }
  2851. break;
  2852. no:
  2853. while (c != '\012')
  2854. crReturn(1);
  2855. crReturn(1);
  2856. }
  2857. ssh->session_started = TRUE;
  2858. s->vstrsize = sizeof(protoname) + 16;
  2859. s->vstring = snewn(s->vstrsize, char);
  2860. strcpy(s->vstring, protoname);
  2861. s->vslen = strlen(protoname);
  2862. s->i = 0;
  2863. while (1) {
  2864. if (s->vslen >= s->vstrsize - 1) {
  2865. s->vstrsize += 16;
  2866. s->vstring = sresize(s->vstring, s->vstrsize, char);
  2867. }
  2868. s->vstring[s->vslen++] = c;
  2869. if (s->i >= 0) {
  2870. if (c == '-') {
  2871. s->version[s->i] = '\0';
  2872. s->i = -1;
  2873. } else if (s->i < sizeof(s->version) - 1)
  2874. s->version[s->i++] = c;
  2875. } else if (c == '\012')
  2876. break;
  2877. crReturn(1); /* get another char */
  2878. }
  2879. ssh->agentfwd_enabled = FALSE;
  2880. ssh->rdpkt2_state.incoming_sequence = 0;
  2881. s->vstring[s->vslen] = 0;
  2882. s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
  2883. logeventf(ssh, "Server version: %s", s->vstring);
  2884. ssh_detect_bugs(ssh, s->vstring);
  2885. /*
  2886. * Decide which SSH protocol version to support.
  2887. */
  2888. /* Anything strictly below "2.0" means protocol 1 is supported. */
  2889. s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
  2890. /* Anything greater or equal to "1.99" means protocol 2 is supported. */
  2891. s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
  2892. if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
  2893. if (!s->proto1) {
  2894. bombout(("SSH protocol version 1 required by our configuration "
  2895. "but not provided by server"));
  2896. crStop(0);
  2897. }
  2898. } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
  2899. if (!s->proto2) {
  2900. bombout(("SSH protocol version 2 required by our configuration "
  2901. "but server only provides (old, insecure) SSH-1"));
  2902. crStop(0);
  2903. }
  2904. } else {
  2905. /* No longer support values 1 or 2 for CONF_sshprot */
  2906. assert(!"Unexpected value for CONF_sshprot");
  2907. }
  2908. if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
  2909. ssh->version = 2;
  2910. else
  2911. ssh->version = 1;
  2912. logeventf(ssh, "Using SSH protocol version %d", ssh->version);
  2913. /* Send the version string, if we haven't already */
  2914. if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
  2915. ssh_send_verstring(ssh, protoname, s->version);
  2916. if (ssh->version == 2) {
  2917. size_t len;
  2918. /*
  2919. * Record their version string.
  2920. */
  2921. len = strcspn(s->vstring, "\015\012");
  2922. ssh->v_s = snewn(len + 1, char);
  2923. memcpy(ssh->v_s, s->vstring, len);
  2924. ssh->v_s[len] = 0;
  2925. /*
  2926. * Initialise SSH-2 protocol.
  2927. */
  2928. ssh->protocol = ssh2_protocol;
  2929. ssh2_protocol_setup(ssh);
  2930. ssh->s_rdpkt = ssh2_rdpkt;
  2931. } else {
  2932. /*
  2933. * Initialise SSH-1 protocol.
  2934. */
  2935. ssh->protocol = ssh1_protocol;
  2936. ssh1_protocol_setup(ssh);
  2937. ssh->s_rdpkt = ssh1_rdpkt;
  2938. }
  2939. if (ssh->version == 2)
  2940. do_ssh2_transport(ssh, NULL, -1, NULL);
  2941. update_specials_menu(ssh->frontend);
  2942. ssh->state = SSH_STATE_BEFORE_SIZE;
  2943. ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
  2944. sfree(s->vstring);
  2945. crFinish(0);
  2946. }
  2947. static int do_ssh_connection_init(Ssh ssh, unsigned char c)
  2948. {
  2949. /*
  2950. * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
  2951. * the ssh-connection part, extracted and given a trivial binary
  2952. * packet protocol, so we replace 'SSH-' at the start with a new
  2953. * name. In proper SSH style (though of course this part of the
  2954. * proper SSH protocol _isn't_ subject to this kind of
  2955. * DNS-domain-based extension), we define the new name in our
  2956. * extension space.
  2957. */
  2958. static const char protoname[] =
  2959. "[email protected]";
  2960. struct do_ssh_connection_init_state {
  2961. int crLine;
  2962. int vslen;
  2963. char version[10];
  2964. char *vstring;
  2965. int vstrsize;
  2966. int i;
  2967. };
  2968. crState(do_ssh_connection_init_state);
  2969. crBeginState;
  2970. /* Search for a line beginning with the protocol name prefix in
  2971. * the input. */
  2972. for (;;) {
  2973. for (s->i = 0; protoname[s->i]; s->i++) {
  2974. if ((char)c != protoname[s->i]) goto no;
  2975. crReturn(1);
  2976. }
  2977. break;
  2978. no:
  2979. while (c != '\012')
  2980. crReturn(1);
  2981. crReturn(1);
  2982. }
  2983. s->vstrsize = sizeof(protoname) + 16;
  2984. s->vstring = snewn(s->vstrsize, char);
  2985. strcpy(s->vstring, protoname);
  2986. s->vslen = strlen(protoname);
  2987. s->i = 0;
  2988. while (1) {
  2989. if (s->vslen >= s->vstrsize - 1) {
  2990. s->vstrsize += 16;
  2991. s->vstring = sresize(s->vstring, s->vstrsize, char);
  2992. }
  2993. s->vstring[s->vslen++] = c;
  2994. if (s->i >= 0) {
  2995. if (c == '-') {
  2996. s->version[s->i] = '\0';
  2997. s->i = -1;
  2998. } else if (s->i < sizeof(s->version) - 1)
  2999. s->version[s->i++] = c;
  3000. } else if (c == '\012')
  3001. break;
  3002. crReturn(1); /* get another char */
  3003. }
  3004. ssh->agentfwd_enabled = FALSE;
  3005. ssh->rdpkt2_bare_state.incoming_sequence = 0;
  3006. s->vstring[s->vslen] = 0;
  3007. s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
  3008. logeventf(ssh, "Server version: %s", s->vstring);
  3009. ssh_detect_bugs(ssh, s->vstring);
  3010. /*
  3011. * Decide which SSH protocol version to support. This is easy in
  3012. * bare ssh-connection mode: only 2.0 is legal.
  3013. */
  3014. if (ssh_versioncmp(s->version, "2.0") < 0) {
  3015. bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
  3016. crStop(0);
  3017. }
  3018. if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
  3019. bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
  3020. crStop(0);
  3021. }
  3022. ssh->version = 2;
  3023. logeventf(ssh, "Using bare ssh-connection protocol");
  3024. /* Send the version string, if we haven't already */
  3025. ssh_send_verstring(ssh, protoname, s->version);
  3026. /*
  3027. * Initialise bare connection protocol.
  3028. */
  3029. ssh->protocol = ssh2_bare_connection_protocol;
  3030. ssh2_bare_connection_protocol_setup(ssh);
  3031. ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
  3032. update_specials_menu(ssh->frontend);
  3033. ssh->state = SSH_STATE_BEFORE_SIZE;
  3034. ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
  3035. /*
  3036. * Get authconn (really just conn) under way.
  3037. */
  3038. do_ssh2_authconn(ssh, NULL, 0, NULL);
  3039. sfree(s->vstring);
  3040. crFinish(0);
  3041. }
  3042. static void ssh_process_incoming_data(Ssh ssh,
  3043. const unsigned char **data, int *datalen)
  3044. {
  3045. struct Packet *pktin;
  3046. pktin = ssh->s_rdpkt(ssh, data, datalen);
  3047. if (pktin) {
  3048. ssh->protocol(ssh, NULL, 0, pktin);
  3049. ssh_free_packet(pktin);
  3050. }
  3051. }
  3052. static void ssh_queue_incoming_data(Ssh ssh,
  3053. const unsigned char **data, int *datalen)
  3054. {
  3055. bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
  3056. *data += *datalen;
  3057. *datalen = 0;
  3058. }
  3059. static void ssh_process_queued_incoming_data(Ssh ssh)
  3060. {
  3061. void *vdata;
  3062. const unsigned char *data;
  3063. int len, origlen;
  3064. while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
  3065. bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
  3066. data = vdata;
  3067. origlen = len;
  3068. while (!ssh->frozen && len > 0)
  3069. ssh_process_incoming_data(ssh, &data, &len);
  3070. if (origlen > len)
  3071. bufchain_consume(&ssh->queued_incoming_data, origlen - len);
  3072. }
  3073. }
  3074. static void ssh_set_frozen(Ssh ssh, int frozen)
  3075. {
  3076. if (ssh->s)
  3077. sk_set_frozen(ssh->s, frozen);
  3078. ssh->frozen = frozen;
  3079. }
  3080. static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
  3081. {
  3082. /* Log raw data, if we're in that mode. */
  3083. if (ssh->logctx)
  3084. log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
  3085. 0, NULL, NULL, 0, NULL);
  3086. crBegin(ssh->ssh_gotdata_crstate);
  3087. /*
  3088. * To begin with, feed the characters one by one to the
  3089. * protocol initialisation / selection function do_ssh_init().
  3090. * When that returns 0, we're done with the initial greeting
  3091. * exchange and can move on to packet discipline.
  3092. */
  3093. while (1) {
  3094. int ret; /* need not be kept across crReturn */
  3095. if (datalen == 0)
  3096. crReturnV; /* more data please */
  3097. ret = ssh->do_ssh_init(ssh, *data);
  3098. data++;
  3099. datalen--;
  3100. if (ret == 0)
  3101. break;
  3102. }
  3103. /*
  3104. * We emerge from that loop when the initial negotiation is
  3105. * over and we have selected an s_rdpkt function. Now pass
  3106. * everything to s_rdpkt, and then pass the resulting packets
  3107. * to the proper protocol handler.
  3108. */
  3109. while (1) {
  3110. while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
  3111. if (ssh->frozen) {
  3112. ssh_queue_incoming_data(ssh, &data, &datalen);
  3113. /* This uses up all data and cannot cause anything interesting
  3114. * to happen; indeed, for anything to happen at all, we must
  3115. * return, so break out. */
  3116. break;
  3117. } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
  3118. /* This uses up some or all data, and may freeze the
  3119. * session. */
  3120. ssh_process_queued_incoming_data(ssh);
  3121. } else {
  3122. /* This uses up some or all data, and may freeze the
  3123. * session. */
  3124. ssh_process_incoming_data(ssh, &data, &datalen);
  3125. }
  3126. /* FIXME this is probably EBW. */
  3127. if (ssh->state == SSH_STATE_CLOSED)
  3128. return;
  3129. }
  3130. /* We're out of data. Go and get some more. */
  3131. crReturnV;
  3132. }
  3133. crFinishV;
  3134. }
  3135. static int ssh_do_close(Ssh ssh, int notify_exit)
  3136. {
  3137. int ret = 0;
  3138. struct ssh_channel *c;
  3139. ssh->state = SSH_STATE_CLOSED;
  3140. expire_timer_context(ssh);
  3141. if (ssh->s) {
  3142. sk_close(ssh->s);
  3143. ssh->s = NULL;
  3144. if (notify_exit)
  3145. notify_remote_exit(ssh->frontend);
  3146. else
  3147. ret = 1;
  3148. }
  3149. /*
  3150. * Now we must shut down any port- and X-forwarded channels going
  3151. * through this connection.
  3152. */
  3153. if (ssh->channels) {
  3154. while (NULL != (c = index234(ssh->channels, 0))) {
  3155. ssh_channel_close_local(c, NULL);
  3156. del234(ssh->channels, c); /* moving next one to index 0 */
  3157. if (ssh->version == 2)
  3158. bufchain_clear(&c->v.v2.outbuffer);
  3159. sfree(c);
  3160. }
  3161. }
  3162. /*
  3163. * Go through port-forwardings, and close any associated
  3164. * listening sockets.
  3165. */
  3166. if (ssh->portfwds) {
  3167. struct ssh_portfwd *pf;
  3168. while (NULL != (pf = index234(ssh->portfwds, 0))) {
  3169. /* Dispose of any listening socket. */
  3170. if (pf->local)
  3171. pfl_terminate(pf->local);
  3172. del234(ssh->portfwds, pf); /* moving next one to index 0 */
  3173. free_portfwd(pf);
  3174. }
  3175. freetree234(ssh->portfwds);
  3176. ssh->portfwds = NULL;
  3177. }
  3178. /*
  3179. * Also stop attempting to connection-share.
  3180. */
  3181. if (ssh->connshare) {
  3182. sharestate_free(ssh->connshare);
  3183. ssh->connshare = NULL;
  3184. }
  3185. return ret;
  3186. }
  3187. static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
  3188. const char *error_msg, int error_code)
  3189. {
  3190. Ssh ssh = (Ssh) plug;
  3191. /*
  3192. * While we're attempting connection sharing, don't loudly log
  3193. * everything that happens. Real TCP connections need to be logged
  3194. * when we _start_ trying to connect, because it might be ages
  3195. * before they respond if something goes wrong; but connection
  3196. * sharing is local and quick to respond, and it's sufficient to
  3197. * simply wait and see whether it worked afterwards.
  3198. */
  3199. if (!ssh->attempting_connshare)
  3200. backend_socket_log(ssh->frontend, type, addr, port,
  3201. error_msg, error_code, ssh->conf,
  3202. ssh->session_started);
  3203. }
  3204. void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
  3205. const char *ds_err, const char *us_err)
  3206. {
  3207. if (event == SHARE_NONE) {
  3208. /* In this case, 'logtext' is an error message indicating a
  3209. * reason why connection sharing couldn't be set up _at all_.
  3210. * Failing that, ds_err and us_err indicate why we couldn't be
  3211. * a downstream and an upstream respectively. */
  3212. if (logtext) {
  3213. logeventf(ssh, "Could not set up connection sharing: %s", logtext);
  3214. } else {
  3215. if (ds_err)
  3216. logeventf(ssh, "Could not set up connection sharing"
  3217. " as downstream: %s", ds_err);
  3218. if (us_err)
  3219. logeventf(ssh, "Could not set up connection sharing"
  3220. " as upstream: %s", us_err);
  3221. }
  3222. } else if (event == SHARE_DOWNSTREAM) {
  3223. /* In this case, 'logtext' is a local endpoint address */
  3224. logeventf(ssh, "Using existing shared connection at %s", logtext);
  3225. /* Also we should mention this in the console window to avoid
  3226. * confusing users as to why this window doesn't behave the
  3227. * usual way. */
  3228. if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
  3229. c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
  3230. }
  3231. } else if (event == SHARE_UPSTREAM) {
  3232. /* In this case, 'logtext' is a local endpoint address too */
  3233. logeventf(ssh, "Sharing this connection at %s", logtext);
  3234. }
  3235. }
  3236. static void ssh_closing(Plug plug, const char *error_msg, int error_code,
  3237. int calling_back)
  3238. {
  3239. Ssh ssh = (Ssh) plug;
  3240. int need_notify = ssh_do_close(ssh, FALSE);
  3241. if (!error_msg) {
  3242. if (!ssh->close_expected)
  3243. error_msg = "Server unexpectedly closed network connection";
  3244. else
  3245. error_msg = "Server closed network connection";
  3246. }
  3247. if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
  3248. ssh->exitcode = 0;
  3249. if (need_notify)
  3250. notify_remote_exit(ssh->frontend);
  3251. if (error_msg)
  3252. logevent(error_msg);
  3253. if (!ssh->close_expected || !ssh->clean_exit)
  3254. connection_fatal(ssh->frontend, "%s", error_msg);
  3255. }
  3256. static void ssh_receive(Plug plug, int urgent, char *data, int len)
  3257. {
  3258. Ssh ssh = (Ssh) plug;
  3259. ssh_gotdata(ssh, (unsigned char *)data, len);
  3260. if (ssh->state == SSH_STATE_CLOSED) {
  3261. ssh_do_close(ssh, TRUE);
  3262. }
  3263. }
  3264. static void ssh_sent(Plug plug, int bufsize)
  3265. {
  3266. Ssh ssh = (Ssh) plug;
  3267. /*
  3268. * If the send backlog on the SSH socket itself clears, we
  3269. * should unthrottle the whole world if it was throttled.
  3270. */
  3271. if (bufsize < SSH_MAX_BACKLOG)
  3272. {
  3273. ssh_throttle_all(ssh, 0, bufsize);
  3274. }
  3275. }
  3276. static void ssh_hostport_setup(const char *host, int port, Conf *conf,
  3277. char **savedhost, int *savedport,
  3278. char **loghost_ret)
  3279. {
  3280. char *loghost = conf_get_str(conf, CONF_loghost);
  3281. if (loghost_ret)
  3282. *loghost_ret = loghost;
  3283. if (*loghost) {
  3284. char *tmphost;
  3285. char *colon;
  3286. tmphost = dupstr(loghost);
  3287. *savedport = 22; /* default ssh port */
  3288. /*
  3289. * A colon suffix on the hostname string also lets us affect
  3290. * savedport. (Unless there are multiple colons, in which case
  3291. * we assume this is an unbracketed IPv6 literal.)
  3292. */
  3293. colon = host_strrchr(tmphost, ':');
  3294. if (colon && colon == host_strchr(tmphost, ':')) {
  3295. *colon++ = '\0';
  3296. if (*colon)
  3297. *savedport = atoi(colon);
  3298. }
  3299. *savedhost = host_strduptrim(tmphost);
  3300. sfree(tmphost);
  3301. } else {
  3302. *savedhost = host_strduptrim(host);
  3303. if (port < 0)
  3304. port = 22; /* default ssh port */
  3305. *savedport = port;
  3306. }
  3307. }
  3308. static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
  3309. {
  3310. char *savedhost;
  3311. int savedport;
  3312. int ret;
  3313. random_ref(); /* platform may need this to determine share socket name */
  3314. ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
  3315. ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
  3316. sfree(savedhost);
  3317. random_unref();
  3318. return ret;
  3319. }
  3320. /*
  3321. * Connect to specified host and port.
  3322. * Returns an error message, or NULL on success.
  3323. * Also places the canonical host name into `realhost'. It must be
  3324. * freed by the caller.
  3325. */
  3326. static const char *connect_to_host(Ssh ssh, const char *host, int port,
  3327. char **realhost, int nodelay, int keepalive)
  3328. {
  3329. static const struct plug_function_table fn_table = {
  3330. ssh_socket_log,
  3331. ssh_closing,
  3332. ssh_receive,
  3333. ssh_sent,
  3334. NULL
  3335. };
  3336. SockAddr addr;
  3337. const char *err;
  3338. char *loghost;
  3339. int addressfamily, sshprot;
  3340. ssh_hostport_setup(host, port, ssh->conf,
  3341. &ssh->savedhost, &ssh->savedport, &loghost);
  3342. #ifdef MPEXT
  3343. // make sure the field is initialized, in case lookup below fails
  3344. ssh->fullhostname = NULL;
  3345. #endif
  3346. ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
  3347. /*
  3348. * Try connection-sharing, in case that means we don't open a
  3349. * socket after all. ssh_connection_sharing_init will connect to a
  3350. * previously established upstream if it can, and failing that,
  3351. * establish a listening socket for _us_ to be the upstream. In
  3352. * the latter case it will return NULL just as if it had done
  3353. * nothing, because here we only need to care if we're a
  3354. * downstream and need to do our connection setup differently.
  3355. */
  3356. ssh->connshare = NULL;
  3357. ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
  3358. ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
  3359. ssh->conf, ssh, &ssh->connshare);
  3360. ssh->attempting_connshare = FALSE;
  3361. if (ssh->s != NULL) {
  3362. /*
  3363. * We are a downstream.
  3364. */
  3365. ssh->bare_connection = TRUE;
  3366. ssh->do_ssh_init = do_ssh_connection_init;
  3367. ssh->fullhostname = NULL;
  3368. *realhost = dupstr(host); /* best we can do */
  3369. } else {
  3370. /*
  3371. * We're not a downstream, so open a normal socket.
  3372. */
  3373. ssh->do_ssh_init = do_ssh_init;
  3374. /*
  3375. * Try to find host.
  3376. */
  3377. addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
  3378. addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
  3379. ssh->frontend, "SSH connection");
  3380. if ((err = sk_addr_error(addr)) != NULL) {
  3381. sk_addr_free(addr);
  3382. return err;
  3383. }
  3384. ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
  3385. ssh->s = new_connection(addr, *realhost, port,
  3386. 0, 1, nodelay, keepalive,
  3387. (Plug) ssh, ssh->conf);
  3388. if ((err = sk_socket_error(ssh->s)) != NULL) {
  3389. ssh->s = NULL;
  3390. notify_remote_exit(ssh->frontend);
  3391. return err;
  3392. }
  3393. }
  3394. /*
  3395. * The SSH version number is always fixed (since we no longer support
  3396. * fallback between versions), so set it now, and if it's SSH-2,
  3397. * send the version string now too.
  3398. */
  3399. sshprot = conf_get_int(ssh->conf, CONF_sshprot);
  3400. assert(sshprot == 0 || sshprot == 3);
  3401. if (sshprot == 0)
  3402. /* SSH-1 only */
  3403. ssh->version = 1;
  3404. if (sshprot == 3 && !ssh->bare_connection) {
  3405. /* SSH-2 only */
  3406. ssh->version = 2;
  3407. ssh_send_verstring(ssh, "SSH-", NULL);
  3408. }
  3409. /*
  3410. * loghost, if configured, overrides realhost.
  3411. */
  3412. if (*loghost) {
  3413. sfree(*realhost);
  3414. *realhost = dupstr(loghost);
  3415. }
  3416. return NULL;
  3417. }
  3418. /*
  3419. * Throttle or unthrottle the SSH connection.
  3420. */
  3421. static void ssh_throttle_conn(Ssh ssh, int adjust)
  3422. {
  3423. int old_count = ssh->conn_throttle_count;
  3424. ssh->conn_throttle_count += adjust;
  3425. assert(ssh->conn_throttle_count >= 0);
  3426. if (ssh->conn_throttle_count && !old_count) {
  3427. ssh_set_frozen(ssh, 1);
  3428. } else if (!ssh->conn_throttle_count && old_count) {
  3429. ssh_set_frozen(ssh, 0);
  3430. }
  3431. }
  3432. static void ssh_agentf_try_forward(struct ssh_channel *c);
  3433. /*
  3434. * Throttle or unthrottle _all_ local data streams (for when sends
  3435. * on the SSH connection itself back up).
  3436. */
  3437. static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
  3438. {
  3439. int i;
  3440. struct ssh_channel *c;
  3441. if (enable == ssh->throttled_all)
  3442. return;
  3443. ssh->throttled_all = enable;
  3444. ssh->overall_bufsize = bufsize;
  3445. if (!ssh->channels)
  3446. return;
  3447. for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
  3448. switch (c->type) {
  3449. case CHAN_MAINSESSION:
  3450. /*
  3451. * This is treated separately, outside the switch.
  3452. */
  3453. break;
  3454. case CHAN_X11:
  3455. x11_override_throttle(c->u.x11.xconn, enable);
  3456. break;
  3457. case CHAN_AGENT:
  3458. /* Agent forwarding channels are buffer-managed by
  3459. * checking ssh->throttled_all in ssh_agentf_try_forward.
  3460. * So at the moment we _un_throttle again, we must make an
  3461. * attempt to do something. */
  3462. if (!enable)
  3463. ssh_agentf_try_forward(c);
  3464. break;
  3465. case CHAN_SOCKDATA:
  3466. pfd_override_throttle(c->u.pfd.pf, enable);
  3467. break;
  3468. }
  3469. }
  3470. }
  3471. static void ssh_agent_callback(void *sshv, void *reply, int replylen)
  3472. {
  3473. Ssh ssh = (Ssh) sshv;
  3474. ssh->auth_agent_query = NULL;
  3475. ssh->agent_response = reply;
  3476. ssh->agent_response_len = replylen;
  3477. if (ssh->version == 1)
  3478. do_ssh1_login(ssh, NULL, -1, NULL);
  3479. else
  3480. do_ssh2_authconn(ssh, NULL, -1, NULL);
  3481. }
  3482. static void ssh_dialog_callback(void *sshv, int ret)
  3483. {
  3484. Ssh ssh = (Ssh) sshv;
  3485. ssh->user_response = ret;
  3486. if (ssh->version == 1)
  3487. do_ssh1_login(ssh, NULL, -1, NULL);
  3488. else
  3489. do_ssh2_transport(ssh, NULL, -1, NULL);
  3490. /*
  3491. * This may have unfrozen the SSH connection, so do a
  3492. * queued-data run.
  3493. */
  3494. ssh_process_queued_incoming_data(ssh);
  3495. }
  3496. static void ssh_agentf_got_response(struct ssh_channel *c,
  3497. void *reply, int replylen)
  3498. {
  3499. c->u.a.pending = NULL;
  3500. assert(!(c->closes & CLOSES_SENT_EOF));
  3501. if (!reply) {
  3502. /* The real agent didn't send any kind of reply at all for
  3503. * some reason, so fake an SSH_AGENT_FAILURE. */
  3504. reply = "\0\0\0\1\5";
  3505. replylen = 5;
  3506. }
  3507. ssh_send_channel_data(c, reply, replylen);
  3508. }
  3509. static void ssh_agentf_callback(void *cv, void *reply, int replylen);
  3510. static void ssh_agentf_try_forward(struct ssh_channel *c)
  3511. {
  3512. unsigned datalen, lengthfield, messagelen;
  3513. unsigned char *message;
  3514. unsigned char msglen[4];
  3515. void *reply;
  3516. int replylen;
  3517. /*
  3518. * Don't try to parallelise agent requests. Wait for each one to
  3519. * return before attempting the next.
  3520. */
  3521. if (c->u.a.pending)
  3522. return;
  3523. /*
  3524. * If the outgoing side of the channel connection is currently
  3525. * throttled (for any reason, either that channel's window size or
  3526. * the entire SSH connection being throttled), don't submit any
  3527. * new forwarded requests to the real agent. This causes the input
  3528. * side of the agent forwarding not to be emptied, exerting the
  3529. * required back-pressure on the remote client, and encouraging it
  3530. * to read our responses before sending too many more requests.
  3531. */
  3532. if (c->ssh->throttled_all ||
  3533. (c->ssh->version == 2 && c->v.v2.remwindow == 0))
  3534. return;
  3535. if (c->closes & CLOSES_SENT_EOF) {
  3536. /*
  3537. * If we've already sent outgoing EOF, there's nothing we can
  3538. * do with incoming data except consume it and throw it away.
  3539. */
  3540. bufchain_clear(&c->u.a.inbuffer);
  3541. return;
  3542. }
  3543. while (1) {
  3544. /*
  3545. * Try to extract a complete message from the input buffer.
  3546. */
  3547. datalen = bufchain_size(&c->u.a.inbuffer);
  3548. if (datalen < 4)
  3549. break; /* not even a length field available yet */
  3550. bufchain_fetch(&c->u.a.inbuffer, msglen, 4);
  3551. lengthfield = GET_32BIT(msglen);
  3552. if (lengthfield > AGENT_MAX_MSGLEN) {
  3553. /*
  3554. * If the remote has sent a message that's just _too_
  3555. * long, we should reject it in advance of seeing the rest
  3556. * of the incoming message, and also close the connection
  3557. * for good measure (which avoids us having to faff about
  3558. * with carefully ignoring just the right number of bytes
  3559. * from the overlong message).
  3560. */
  3561. ssh_agentf_got_response(c, NULL, 0);
  3562. sshfwd_write_eof(c);
  3563. return;
  3564. }
  3565. if (lengthfield > datalen - 4)
  3566. break; /* a whole message is not yet available */
  3567. messagelen = lengthfield + 4;
  3568. message = snewn(messagelen, unsigned char);
  3569. bufchain_fetch(&c->u.a.inbuffer, message, messagelen);
  3570. bufchain_consume(&c->u.a.inbuffer, messagelen);
  3571. c->u.a.pending = agent_query(
  3572. message, messagelen, &reply, &replylen, ssh_agentf_callback, c);
  3573. sfree(message);
  3574. if (c->u.a.pending)
  3575. return; /* agent_query promised to reply in due course */
  3576. /*
  3577. * If the agent gave us an answer immediately, pass it
  3578. * straight on and go round this loop again.
  3579. */
  3580. ssh_agentf_got_response(c, reply, replylen);
  3581. sfree(reply);
  3582. }
  3583. /*
  3584. * If we get here (i.e. we left the above while loop via 'break'
  3585. * rather than 'return'), that means we've determined that the
  3586. * input buffer for the agent forwarding connection doesn't
  3587. * contain a complete request.
  3588. *
  3589. * So if there's potentially more data to come, we can return now,
  3590. * and wait for the remote client to send it. But if the remote
  3591. * has sent EOF, it would be a mistake to do that, because we'd be
  3592. * waiting a long time. So this is the moment to check for EOF,
  3593. * and respond appropriately.
  3594. */
  3595. if (c->closes & CLOSES_RCVD_EOF)
  3596. sshfwd_write_eof(c);
  3597. }
  3598. static void ssh_agentf_callback(void *cv, void *reply, int replylen)
  3599. {
  3600. struct ssh_channel *c = (struct ssh_channel *)cv;
  3601. ssh_agentf_got_response(c, reply, replylen);
  3602. sfree(reply);
  3603. /*
  3604. * Now try to extract and send further messages from the channel's
  3605. * input-side buffer.
  3606. */
  3607. ssh_agentf_try_forward(c);
  3608. }
  3609. /*
  3610. * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
  3611. * non-NULL, otherwise just close the connection. `client_reason' == NULL
  3612. * => log `wire_reason'.
  3613. */
  3614. static void ssh_disconnect(Ssh ssh, const char *client_reason,
  3615. const char *wire_reason,
  3616. int code, int clean_exit)
  3617. {
  3618. char *error;
  3619. if (!client_reason)
  3620. client_reason = wire_reason;
  3621. if (client_reason)
  3622. error = dupprintf("Disconnected: %s", client_reason);
  3623. else
  3624. error = dupstr("Disconnected");
  3625. if (wire_reason) {
  3626. if (ssh->version == 1) {
  3627. send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
  3628. PKT_END);
  3629. } else if (ssh->version == 2) {
  3630. struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
  3631. ssh2_pkt_adduint32(pktout, code);
  3632. ssh2_pkt_addstring(pktout, wire_reason);
  3633. ssh2_pkt_addstring(pktout, "en"); /* language tag */
  3634. ssh2_pkt_send_noqueue(ssh, pktout);
  3635. }
  3636. }
  3637. ssh->close_expected = TRUE;
  3638. ssh->clean_exit = clean_exit;
  3639. ssh_closing((Plug)ssh, error, 0, 0);
  3640. sfree(error);
  3641. }
  3642. int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
  3643. const struct ssh_signkey *ssh2keytype,
  3644. void *ssh2keydata)
  3645. {
  3646. if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
  3647. return -1; /* no manual keys configured */
  3648. }
  3649. if (fingerprint) {
  3650. /*
  3651. * The fingerprint string we've been given will have things
  3652. * like 'ssh-rsa 2048' at the front of it. Strip those off and
  3653. * narrow down to just the colon-separated hex block at the
  3654. * end of the string.
  3655. */
  3656. const char *p = strrchr(fingerprint, ' ');
  3657. fingerprint = p ? p+1 : fingerprint;
  3658. /* Quick sanity checks, including making sure it's in lowercase */
  3659. assert(strlen(fingerprint) == 16*3 - 1);
  3660. assert(fingerprint[2] == ':');
  3661. assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
  3662. if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
  3663. fingerprint))
  3664. return 1; /* success */
  3665. }
  3666. if (ssh2keydata) {
  3667. /*
  3668. * Construct the base64-encoded public key blob and see if
  3669. * that's listed.
  3670. */
  3671. unsigned char *binblob;
  3672. char *base64blob;
  3673. int binlen, atoms, i;
  3674. binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
  3675. atoms = (binlen + 2) / 3;
  3676. base64blob = snewn(atoms * 4 + 1, char);
  3677. for (i = 0; i < atoms; i++)
  3678. base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
  3679. base64blob[atoms * 4] = '\0';
  3680. sfree(binblob);
  3681. if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
  3682. base64blob)) {
  3683. sfree(base64blob);
  3684. return 1; /* success */
  3685. }
  3686. sfree(base64blob);
  3687. }
  3688. return 0;
  3689. }
  3690. /*
  3691. * Handle the key exchange and user authentication phases.
  3692. */
  3693. static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
  3694. struct Packet *pktin)
  3695. {
  3696. int i, j, ret;
  3697. unsigned char cookie[8], *ptr;
  3698. struct MD5Context md5c;
  3699. struct do_ssh1_login_state {
  3700. int crLine;
  3701. int len;
  3702. unsigned char *rsabuf;
  3703. const unsigned char *keystr1, *keystr2;
  3704. unsigned long supported_ciphers_mask, supported_auths_mask;
  3705. int tried_publickey, tried_agent;
  3706. int tis_auth_refused, ccard_auth_refused;
  3707. unsigned char session_id[16];
  3708. int cipher_type;
  3709. void *publickey_blob;
  3710. int publickey_bloblen;
  3711. char *publickey_comment;
  3712. int privatekey_available, privatekey_encrypted;
  3713. prompts_t *cur_prompt;
  3714. char c;
  3715. int pwpkt_type;
  3716. unsigned char request[5], *response, *p;
  3717. int responselen;
  3718. int keyi, nkeys;
  3719. int authed;
  3720. struct RSAKey key;
  3721. Bignum challenge;
  3722. char *commentp;
  3723. int commentlen;
  3724. int dlgret;
  3725. Filename *keyfile;
  3726. struct RSAKey servkey, hostkey;
  3727. };
  3728. crState(do_ssh1_login_state);
  3729. crBeginState;
  3730. if (!pktin)
  3731. crWaitUntil(pktin);
  3732. if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
  3733. bombout(("Public key packet not received"));
  3734. crStop(0);
  3735. }
  3736. logevent("Received public keys");
  3737. ptr = ssh_pkt_getdata(pktin, 8);
  3738. if (!ptr) {
  3739. bombout(("SSH-1 public key packet stopped before random cookie"));
  3740. crStop(0);
  3741. }
  3742. memcpy(cookie, ptr, 8);
  3743. if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
  3744. !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
  3745. bombout(("Failed to read SSH-1 public keys from public key packet"));
  3746. crStop(0);
  3747. }
  3748. /*
  3749. * Log the host key fingerprint.
  3750. */
  3751. {
  3752. char logmsg[80];
  3753. logevent("Host key fingerprint is:");
  3754. strcpy(logmsg, " ");
  3755. s->hostkey.comment = NULL;
  3756. rsa_fingerprint(logmsg + strlen(logmsg),
  3757. sizeof(logmsg) - strlen(logmsg), &s->hostkey);
  3758. logevent(logmsg);
  3759. }
  3760. ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
  3761. s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
  3762. s->supported_auths_mask = ssh_pkt_getuint32(pktin);
  3763. if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
  3764. s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
  3765. ssh->v1_local_protoflags =
  3766. ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
  3767. ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
  3768. MD5Init(&md5c);
  3769. MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
  3770. MD5Update(&md5c, s->keystr1, s->servkey.bytes);
  3771. MD5Update(&md5c, cookie, 8);
  3772. MD5Final(s->session_id, &md5c);
  3773. for (i = 0; i < 32; i++)
  3774. ssh->session_key[i] = random_byte();
  3775. /*
  3776. * Verify that the `bits' and `bytes' parameters match.
  3777. */
  3778. if (s->hostkey.bits > s->hostkey.bytes * 8 ||
  3779. s->servkey.bits > s->servkey.bytes * 8) {
  3780. bombout(("SSH-1 public keys were badly formatted"));
  3781. crStop(0);
  3782. }
  3783. s->len = (s->hostkey.bytes > s->servkey.bytes ?
  3784. s->hostkey.bytes : s->servkey.bytes);
  3785. s->rsabuf = snewn(s->len, unsigned char);
  3786. /*
  3787. * Verify the host key.
  3788. */
  3789. {
  3790. /*
  3791. * First format the key into a string.
  3792. */
  3793. int len = rsastr_len(&s->hostkey);
  3794. char fingerprint[100];
  3795. char *keystr = snewn(len, char);
  3796. rsastr_fmt(keystr, &s->hostkey);
  3797. rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
  3798. /* First check against manually configured host keys. */
  3799. s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
  3800. if (s->dlgret == 0) { /* did not match */
  3801. bombout(("Host key did not appear in manually configured list"));
  3802. sfree(keystr);
  3803. crStop(0);
  3804. } else if (s->dlgret < 0) { /* none configured; use standard handling */
  3805. ssh_set_frozen(ssh, 1);
  3806. s->dlgret = verify_ssh_host_key(ssh->frontend,
  3807. ssh->savedhost, ssh->savedport,
  3808. "rsa", keystr, fingerprint,
  3809. ssh_dialog_callback, ssh);
  3810. sfree(keystr);
  3811. #ifdef FUZZING
  3812. s->dlgret = 1;
  3813. #endif
  3814. if (s->dlgret < 0) {
  3815. do {
  3816. crReturn(0);
  3817. if (pktin) {
  3818. bombout(("Unexpected data from server while waiting"
  3819. " for user host key response"));
  3820. crStop(0);
  3821. }
  3822. } while (pktin || inlen > 0);
  3823. s->dlgret = ssh->user_response;
  3824. }
  3825. ssh_set_frozen(ssh, 0);
  3826. if (s->dlgret == 0) {
  3827. ssh_disconnect(ssh, "User aborted at host key verification",
  3828. NULL, 0, TRUE);
  3829. crStop(0);
  3830. }
  3831. } else {
  3832. sfree(keystr);
  3833. }
  3834. }
  3835. for (i = 0; i < 32; i++) {
  3836. s->rsabuf[i] = ssh->session_key[i];
  3837. if (i < 16)
  3838. s->rsabuf[i] ^= s->session_id[i];
  3839. }
  3840. if (s->hostkey.bytes > s->servkey.bytes) {
  3841. ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
  3842. if (ret)
  3843. ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
  3844. } else {
  3845. ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
  3846. if (ret)
  3847. ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
  3848. }
  3849. if (!ret) {
  3850. bombout(("SSH-1 public key encryptions failed due to bad formatting"));
  3851. crStop(0);
  3852. }
  3853. logevent("Encrypted session key");
  3854. {
  3855. int cipher_chosen = 0, warn = 0;
  3856. const char *cipher_string = NULL;
  3857. int i;
  3858. for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
  3859. int next_cipher = conf_get_int_int(ssh->conf,
  3860. CONF_ssh_cipherlist, i);
  3861. if (next_cipher == CIPHER_WARN) {
  3862. /* If/when we choose a cipher, warn about it */
  3863. warn = 1;
  3864. } else if (next_cipher == CIPHER_AES) {
  3865. /* XXX Probably don't need to mention this. */
  3866. logevent("AES not supported in SSH-1, skipping");
  3867. } else {
  3868. switch (next_cipher) {
  3869. case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
  3870. cipher_string = "3DES"; break;
  3871. case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
  3872. cipher_string = "Blowfish"; break;
  3873. case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
  3874. cipher_string = "single-DES"; break;
  3875. }
  3876. if (s->supported_ciphers_mask & (1 << s->cipher_type))
  3877. cipher_chosen = 1;
  3878. }
  3879. }
  3880. if (!cipher_chosen) {
  3881. if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
  3882. bombout(("Server violates SSH-1 protocol by not "
  3883. "supporting 3DES encryption"));
  3884. else
  3885. /* shouldn't happen */
  3886. bombout(("No supported ciphers found"));
  3887. crStop(0);
  3888. }
  3889. /* Warn about chosen cipher if necessary. */
  3890. if (warn) {
  3891. ssh_set_frozen(ssh, 1);
  3892. s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
  3893. ssh_dialog_callback, ssh);
  3894. if (s->dlgret < 0) {
  3895. do {
  3896. crReturn(0);
  3897. if (pktin) {
  3898. bombout(("Unexpected data from server while waiting"
  3899. " for user response"));
  3900. crStop(0);
  3901. }
  3902. } while (pktin || inlen > 0);
  3903. s->dlgret = ssh->user_response;
  3904. }
  3905. ssh_set_frozen(ssh, 0);
  3906. if (s->dlgret == 0) {
  3907. ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
  3908. 0, TRUE);
  3909. crStop(0);
  3910. }
  3911. }
  3912. }
  3913. switch (s->cipher_type) {
  3914. case SSH_CIPHER_3DES:
  3915. logevent("Using 3DES encryption");
  3916. break;
  3917. case SSH_CIPHER_DES:
  3918. logevent("Using single-DES encryption");
  3919. break;
  3920. case SSH_CIPHER_BLOWFISH:
  3921. logevent("Using Blowfish encryption");
  3922. break;
  3923. }
  3924. send_packet(ssh, SSH1_CMSG_SESSION_KEY,
  3925. PKT_CHAR, s->cipher_type,
  3926. PKT_DATA, cookie, 8,
  3927. PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
  3928. PKT_DATA, s->rsabuf, s->len,
  3929. PKT_INT, ssh->v1_local_protoflags, PKT_END);
  3930. logevent("Trying to enable encryption...");
  3931. sfree(s->rsabuf);
  3932. ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
  3933. s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
  3934. &ssh_3des);
  3935. ssh->v1_cipher_ctx = ssh->cipher->make_context();
  3936. ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
  3937. logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
  3938. ssh->crcda_ctx = crcda_make_context();
  3939. logevent("Installing CRC compensation attack detector");
  3940. if (s->servkey.modulus) {
  3941. sfree(s->servkey.modulus);
  3942. s->servkey.modulus = NULL;
  3943. }
  3944. if (s->servkey.exponent) {
  3945. sfree(s->servkey.exponent);
  3946. s->servkey.exponent = NULL;
  3947. }
  3948. if (s->hostkey.modulus) {
  3949. sfree(s->hostkey.modulus);
  3950. s->hostkey.modulus = NULL;
  3951. }
  3952. if (s->hostkey.exponent) {
  3953. sfree(s->hostkey.exponent);
  3954. s->hostkey.exponent = NULL;
  3955. }
  3956. crWaitUntil(pktin);
  3957. if (pktin->type != SSH1_SMSG_SUCCESS) {
  3958. bombout(("Encryption not successfully enabled"));
  3959. crStop(0);
  3960. }
  3961. logevent("Successfully started encryption");
  3962. fflush(stdout); /* FIXME eh? */
  3963. {
  3964. if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
  3965. int ret; /* need not be kept over crReturn */
  3966. s->cur_prompt = new_prompts(ssh->frontend);
  3967. s->cur_prompt->to_server = TRUE;
  3968. s->cur_prompt->name = dupstr("SSH login name");
  3969. add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
  3970. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  3971. while (ret < 0) {
  3972. ssh->send_ok = 1;
  3973. crWaitUntil(!pktin);
  3974. ret = get_userpass_input(s->cur_prompt, in, inlen);
  3975. ssh->send_ok = 0;
  3976. }
  3977. if (!ret) {
  3978. /*
  3979. * Failed to get a username. Terminate.
  3980. */
  3981. free_prompts(s->cur_prompt);
  3982. ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
  3983. crStop(0);
  3984. }
  3985. ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
  3986. free_prompts(s->cur_prompt);
  3987. }
  3988. send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
  3989. {
  3990. char *userlog = dupprintf(MPEXT_BOM "Sent username \"%s\"", ssh->username);
  3991. logevent(userlog);
  3992. if (flags & FLAG_INTERACTIVE &&
  3993. (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
  3994. c_write_str(ssh, userlog);
  3995. c_write_str(ssh, "\r\n");
  3996. }
  3997. sfree(userlog);
  3998. }
  3999. }
  4000. crWaitUntil(pktin);
  4001. if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
  4002. /* We must not attempt PK auth. Pretend we've already tried it. */
  4003. s->tried_publickey = s->tried_agent = 1;
  4004. } else {
  4005. s->tried_publickey = s->tried_agent = 0;
  4006. }
  4007. s->tis_auth_refused = s->ccard_auth_refused = 0;
  4008. /*
  4009. * Load the public half of any configured keyfile for later use.
  4010. */
  4011. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  4012. if (!filename_is_null(s->keyfile)) {
  4013. int keytype;
  4014. logeventf(ssh, MPEXT_BOM "Reading key file \"%.150s\"",
  4015. filename_to_str(s->keyfile));
  4016. keytype = key_type(s->keyfile);
  4017. if (keytype == SSH_KEYTYPE_SSH1 ||
  4018. keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
  4019. const char *error;
  4020. if (rsakey_pubblob(s->keyfile,
  4021. &s->publickey_blob, &s->publickey_bloblen,
  4022. &s->publickey_comment, &error)) {
  4023. s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
  4024. if (!s->privatekey_available)
  4025. logeventf(ssh, "Key file contains public key only");
  4026. s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
  4027. NULL);
  4028. } else {
  4029. char *msgbuf;
  4030. logeventf(ssh, "Unable to load key (%s)", error);
  4031. msgbuf = dupprintf(MPEXT_BOM "Unable to load key file "
  4032. "\"%.150s\" (%s)\r\n",
  4033. filename_to_str(s->keyfile),
  4034. error);
  4035. c_write_str(ssh, msgbuf);
  4036. sfree(msgbuf);
  4037. s->publickey_blob = NULL;
  4038. }
  4039. } else {
  4040. char *msgbuf;
  4041. logeventf(ssh, "Unable to use this key file (%s)",
  4042. key_type_to_str(keytype));
  4043. msgbuf = dupprintf(MPEXT_BOM "Unable to use key file \"%.150s\""
  4044. " (%s)\r\n",
  4045. filename_to_str(s->keyfile),
  4046. key_type_to_str(keytype));
  4047. c_write_str(ssh, msgbuf);
  4048. sfree(msgbuf);
  4049. s->publickey_blob = NULL;
  4050. }
  4051. } else
  4052. s->publickey_blob = NULL;
  4053. while (pktin->type == SSH1_SMSG_FAILURE) {
  4054. s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
  4055. if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
  4056. /*
  4057. * Attempt RSA authentication using Pageant.
  4058. */
  4059. void *r;
  4060. s->authed = FALSE;
  4061. s->tried_agent = 1;
  4062. logevent("Pageant is running. Requesting keys.");
  4063. /* Request the keys held by the agent. */
  4064. PUT_32BIT(s->request, 1);
  4065. s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
  4066. ssh->auth_agent_query = agent_query(
  4067. s->request, 5, &r, &s->responselen, ssh_agent_callback, ssh);
  4068. if (ssh->auth_agent_query) {
  4069. do {
  4070. crReturn(0);
  4071. if (pktin) {
  4072. bombout(("Unexpected data from server while waiting"
  4073. " for agent response"));
  4074. crStop(0);
  4075. }
  4076. } while (pktin || inlen > 0);
  4077. r = ssh->agent_response;
  4078. s->responselen = ssh->agent_response_len;
  4079. }
  4080. s->response = (unsigned char *) r;
  4081. if (s->response && s->responselen >= 5 &&
  4082. s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
  4083. s->p = s->response + 5;
  4084. s->nkeys = toint(GET_32BIT(s->p));
  4085. if (s->nkeys < 0) {
  4086. logeventf(ssh, "Pageant reported negative key count %d",
  4087. s->nkeys);
  4088. s->nkeys = 0;
  4089. }
  4090. s->p += 4;
  4091. logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
  4092. for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
  4093. unsigned char *pkblob = s->p;
  4094. s->p += 4;
  4095. {
  4096. int n, ok = FALSE;
  4097. do { /* do while (0) to make breaking easy */
  4098. n = ssh1_read_bignum
  4099. (s->p, toint(s->responselen-(s->p-s->response)),
  4100. &s->key.exponent);
  4101. if (n < 0)
  4102. break;
  4103. s->p += n;
  4104. n = ssh1_read_bignum
  4105. (s->p, toint(s->responselen-(s->p-s->response)),
  4106. &s->key.modulus);
  4107. if (n < 0)
  4108. break;
  4109. s->p += n;
  4110. if (s->responselen - (s->p-s->response) < 4)
  4111. break;
  4112. s->commentlen = toint(GET_32BIT(s->p));
  4113. s->p += 4;
  4114. if (s->commentlen < 0 ||
  4115. toint(s->responselen - (s->p-s->response)) <
  4116. s->commentlen)
  4117. break;
  4118. s->commentp = (char *)s->p;
  4119. s->p += s->commentlen;
  4120. ok = TRUE;
  4121. } while (0);
  4122. if (!ok) {
  4123. logevent("Pageant key list packet was truncated");
  4124. break;
  4125. }
  4126. }
  4127. if (s->publickey_blob) {
  4128. if (!memcmp(pkblob, s->publickey_blob,
  4129. s->publickey_bloblen)) {
  4130. logeventf(ssh, "Pageant key #%d matches "
  4131. "configured key file", s->keyi);
  4132. s->tried_publickey = 1;
  4133. } else
  4134. /* Skip non-configured key */
  4135. continue;
  4136. }
  4137. logeventf(ssh, "Trying Pageant key #%d", s->keyi);
  4138. send_packet(ssh, SSH1_CMSG_AUTH_RSA,
  4139. PKT_BIGNUM, s->key.modulus, PKT_END);
  4140. crWaitUntil(pktin);
  4141. if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
  4142. logevent("Key refused");
  4143. continue;
  4144. }
  4145. logevent("Received RSA challenge");
  4146. if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
  4147. bombout(("Server's RSA challenge was badly formatted"));
  4148. crStop(0);
  4149. }
  4150. {
  4151. char *agentreq, *q, *ret;
  4152. void *vret;
  4153. int len, retlen;
  4154. len = 1 + 4; /* message type, bit count */
  4155. len += ssh1_bignum_length(s->key.exponent);
  4156. len += ssh1_bignum_length(s->key.modulus);
  4157. len += ssh1_bignum_length(s->challenge);
  4158. len += 16; /* session id */
  4159. len += 4; /* response format */
  4160. agentreq = snewn(4 + len, char);
  4161. PUT_32BIT(agentreq, len);
  4162. q = agentreq + 4;
  4163. *q++ = SSH1_AGENTC_RSA_CHALLENGE;
  4164. PUT_32BIT(q, bignum_bitcount(s->key.modulus));
  4165. q += 4;
  4166. q += ssh1_write_bignum(q, s->key.exponent);
  4167. q += ssh1_write_bignum(q, s->key.modulus);
  4168. q += ssh1_write_bignum(q, s->challenge);
  4169. memcpy(q, s->session_id, 16);
  4170. q += 16;
  4171. PUT_32BIT(q, 1); /* response format */
  4172. ssh->auth_agent_query = agent_query(
  4173. agentreq, len + 4, &vret, &retlen,
  4174. ssh_agent_callback, ssh);
  4175. if (ssh->auth_agent_query) {
  4176. sfree(agentreq);
  4177. do {
  4178. crReturn(0);
  4179. if (pktin) {
  4180. bombout(("Unexpected data from server"
  4181. " while waiting for agent"
  4182. " response"));
  4183. crStop(0);
  4184. }
  4185. } while (pktin || inlen > 0);
  4186. vret = ssh->agent_response;
  4187. retlen = ssh->agent_response_len;
  4188. } else
  4189. sfree(agentreq);
  4190. ret = vret;
  4191. if (ret) {
  4192. if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
  4193. logevent("Sending Pageant's response");
  4194. send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
  4195. PKT_DATA, ret + 5, 16,
  4196. PKT_END);
  4197. sfree(ret);
  4198. crWaitUntil(pktin);
  4199. if (pktin->type == SSH1_SMSG_SUCCESS) {
  4200. logevent
  4201. ("Pageant's response accepted");
  4202. if (flags & FLAG_VERBOSE) {
  4203. c_write_str(ssh, "Authenticated using"
  4204. " RSA key \"");
  4205. c_write(ssh, s->commentp,
  4206. s->commentlen);
  4207. c_write_str(ssh, "\" from agent\r\n");
  4208. }
  4209. s->authed = TRUE;
  4210. } else
  4211. logevent
  4212. ("Pageant's response not accepted");
  4213. } else {
  4214. logevent
  4215. ("Pageant failed to answer challenge");
  4216. sfree(ret);
  4217. }
  4218. } else {
  4219. logevent("No reply received from Pageant");
  4220. }
  4221. }
  4222. freebn(s->key.exponent);
  4223. freebn(s->key.modulus);
  4224. freebn(s->challenge);
  4225. if (s->authed)
  4226. break;
  4227. }
  4228. sfree(s->response);
  4229. if (s->publickey_blob && !s->tried_publickey)
  4230. logevent("Configured key file not in Pageant");
  4231. } else {
  4232. logevent("Failed to get reply from Pageant");
  4233. }
  4234. if (s->authed)
  4235. break;
  4236. }
  4237. if (s->publickey_blob && s->privatekey_available &&
  4238. !s->tried_publickey) {
  4239. /*
  4240. * Try public key authentication with the specified
  4241. * key file.
  4242. */
  4243. int got_passphrase; /* need not be kept over crReturn */
  4244. if (flags & FLAG_VERBOSE)
  4245. c_write_str(ssh, "Trying public key authentication.\r\n");
  4246. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  4247. logeventf(ssh, MPEXT_BOM "Trying public key \"%s\"",
  4248. filename_to_str(s->keyfile));
  4249. s->tried_publickey = 1;
  4250. got_passphrase = FALSE;
  4251. while (!got_passphrase) {
  4252. /*
  4253. * Get a passphrase, if necessary.
  4254. */
  4255. char *passphrase = NULL; /* only written after crReturn */
  4256. const char *error;
  4257. if (!s->privatekey_encrypted) {
  4258. if (flags & FLAG_VERBOSE)
  4259. c_write_str(ssh, "No passphrase required.\r\n");
  4260. passphrase = NULL;
  4261. } else {
  4262. int ret; /* need not be kept over crReturn */
  4263. s->cur_prompt = new_prompts(ssh->frontend);
  4264. s->cur_prompt->to_server = FALSE;
  4265. s->cur_prompt->name = dupstr("SSH key passphrase");
  4266. add_prompt(s->cur_prompt,
  4267. dupprintf("Passphrase for key \"%.100s\": ",
  4268. s->publickey_comment), FALSE);
  4269. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  4270. while (ret < 0) {
  4271. ssh->send_ok = 1;
  4272. crWaitUntil(!pktin);
  4273. ret = get_userpass_input(s->cur_prompt, in, inlen);
  4274. ssh->send_ok = 0;
  4275. }
  4276. if (!ret) {
  4277. /* Failed to get a passphrase. Terminate. */
  4278. free_prompts(s->cur_prompt);
  4279. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  4280. 0, TRUE);
  4281. crStop(0);
  4282. }
  4283. passphrase = dupstr(s->cur_prompt->prompts[0]->result);
  4284. free_prompts(s->cur_prompt);
  4285. }
  4286. /*
  4287. * Try decrypting key with passphrase.
  4288. */
  4289. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  4290. ret = loadrsakey(s->keyfile, &s->key, passphrase,
  4291. &error);
  4292. if (passphrase) {
  4293. smemclr(passphrase, strlen(passphrase));
  4294. sfree(passphrase);
  4295. }
  4296. if (ret == 1) {
  4297. /* Correct passphrase. */
  4298. got_passphrase = TRUE;
  4299. } else if (ret == 0) {
  4300. c_write_str(ssh, MPEXT_BOM "Couldn't load private key from ");
  4301. c_write_str(ssh, filename_to_str(s->keyfile));
  4302. c_write_str(ssh, " (");
  4303. c_write_str(ssh, error);
  4304. c_write_str(ssh, ").\r\n");
  4305. got_passphrase = FALSE;
  4306. break; /* go and try something else */
  4307. } else if (ret == -1) {
  4308. c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
  4309. got_passphrase = FALSE;
  4310. /* and try again */
  4311. } else {
  4312. assert(0 && "unexpected return from loadrsakey()");
  4313. got_passphrase = FALSE; /* placate optimisers */
  4314. }
  4315. }
  4316. if (got_passphrase) {
  4317. /*
  4318. * Send a public key attempt.
  4319. */
  4320. send_packet(ssh, SSH1_CMSG_AUTH_RSA,
  4321. PKT_BIGNUM, s->key.modulus, PKT_END);
  4322. crWaitUntil(pktin);
  4323. if (pktin->type == SSH1_SMSG_FAILURE) {
  4324. c_write_str(ssh, "Server refused our public key.\r\n");
  4325. continue; /* go and try something else */
  4326. }
  4327. if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
  4328. bombout(("Bizarre response to offer of public key"));
  4329. crStop(0);
  4330. }
  4331. {
  4332. int i;
  4333. unsigned char buffer[32];
  4334. Bignum challenge, response;
  4335. if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
  4336. bombout(("Server's RSA challenge was badly formatted"));
  4337. crStop(0);
  4338. }
  4339. response = rsadecrypt(challenge, &s->key);
  4340. freebn(s->key.private_exponent);/* burn the evidence */
  4341. for (i = 0; i < 32; i++) {
  4342. buffer[i] = bignum_byte(response, 31 - i);
  4343. }
  4344. MD5Init(&md5c);
  4345. MD5Update(&md5c, buffer, 32);
  4346. MD5Update(&md5c, s->session_id, 16);
  4347. MD5Final(buffer, &md5c);
  4348. send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
  4349. PKT_DATA, buffer, 16, PKT_END);
  4350. freebn(challenge);
  4351. freebn(response);
  4352. }
  4353. crWaitUntil(pktin);
  4354. if (pktin->type == SSH1_SMSG_FAILURE) {
  4355. if (flags & FLAG_VERBOSE)
  4356. c_write_str(ssh, "Failed to authenticate with"
  4357. " our public key.\r\n");
  4358. continue; /* go and try something else */
  4359. } else if (pktin->type != SSH1_SMSG_SUCCESS) {
  4360. bombout(("Bizarre response to RSA authentication response"));
  4361. crStop(0);
  4362. }
  4363. break; /* we're through! */
  4364. }
  4365. }
  4366. /*
  4367. * Otherwise, try various forms of password-like authentication.
  4368. */
  4369. s->cur_prompt = new_prompts(ssh->frontend);
  4370. if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
  4371. (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
  4372. !s->tis_auth_refused) {
  4373. s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
  4374. logevent("Requested TIS authentication");
  4375. send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
  4376. crWaitUntil(pktin);
  4377. if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
  4378. logevent("TIS authentication declined");
  4379. if (flags & FLAG_INTERACTIVE)
  4380. c_write_str(ssh, "TIS authentication refused.\r\n");
  4381. s->tis_auth_refused = 1;
  4382. continue;
  4383. } else {
  4384. char *challenge;
  4385. int challengelen;
  4386. char *instr_suf, *prompt;
  4387. ssh_pkt_getstring(pktin, &challenge, &challengelen);
  4388. if (!challenge) {
  4389. bombout(("TIS challenge packet was badly formed"));
  4390. crStop(0);
  4391. }
  4392. logevent("Received TIS challenge");
  4393. s->cur_prompt->to_server = TRUE;
  4394. s->cur_prompt->name = dupstr("SSH TIS authentication");
  4395. /* Prompt heuristic comes from OpenSSH */
  4396. if (memchr(challenge, '\n', challengelen)) {
  4397. instr_suf = dupstr("");
  4398. prompt = dupprintf("%.*s", challengelen, challenge);
  4399. } else {
  4400. instr_suf = dupprintf("%.*s", challengelen, challenge);
  4401. prompt = dupstr("Response: ");
  4402. }
  4403. s->cur_prompt->instruction =
  4404. dupprintf("Using TIS authentication.%s%s",
  4405. (*instr_suf) ? "\n" : "",
  4406. instr_suf);
  4407. s->cur_prompt->instr_reqd = TRUE;
  4408. add_prompt(s->cur_prompt, prompt, FALSE);
  4409. sfree(instr_suf);
  4410. }
  4411. }
  4412. if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
  4413. (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
  4414. !s->ccard_auth_refused) {
  4415. s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
  4416. logevent("Requested CryptoCard authentication");
  4417. send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
  4418. crWaitUntil(pktin);
  4419. if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
  4420. logevent("CryptoCard authentication declined");
  4421. c_write_str(ssh, "CryptoCard authentication refused.\r\n");
  4422. s->ccard_auth_refused = 1;
  4423. continue;
  4424. } else {
  4425. char *challenge;
  4426. int challengelen;
  4427. char *instr_suf, *prompt;
  4428. ssh_pkt_getstring(pktin, &challenge, &challengelen);
  4429. if (!challenge) {
  4430. bombout(("CryptoCard challenge packet was badly formed"));
  4431. crStop(0);
  4432. }
  4433. logevent("Received CryptoCard challenge");
  4434. s->cur_prompt->to_server = TRUE;
  4435. s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
  4436. s->cur_prompt->name_reqd = FALSE;
  4437. /* Prompt heuristic comes from OpenSSH */
  4438. if (memchr(challenge, '\n', challengelen)) {
  4439. instr_suf = dupstr("");
  4440. prompt = dupprintf("%.*s", challengelen, challenge);
  4441. } else {
  4442. instr_suf = dupprintf("%.*s", challengelen, challenge);
  4443. prompt = dupstr("Response: ");
  4444. }
  4445. s->cur_prompt->instruction =
  4446. dupprintf("Using CryptoCard authentication.%s%s",
  4447. (*instr_suf) ? "\n" : "",
  4448. instr_suf);
  4449. s->cur_prompt->instr_reqd = TRUE;
  4450. add_prompt(s->cur_prompt, prompt, FALSE);
  4451. sfree(instr_suf);
  4452. }
  4453. }
  4454. if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
  4455. if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
  4456. bombout(("No supported authentication methods available"));
  4457. crStop(0);
  4458. }
  4459. s->cur_prompt->to_server = TRUE;
  4460. s->cur_prompt->name = dupstr("SSH password");
  4461. add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
  4462. ssh->username, ssh->savedhost),
  4463. FALSE);
  4464. }
  4465. /*
  4466. * Show password prompt, having first obtained it via a TIS
  4467. * or CryptoCard exchange if we're doing TIS or CryptoCard
  4468. * authentication.
  4469. */
  4470. {
  4471. int ret; /* need not be kept over crReturn */
  4472. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  4473. while (ret < 0) {
  4474. ssh->send_ok = 1;
  4475. crWaitUntil(!pktin);
  4476. ret = get_userpass_input(s->cur_prompt, in, inlen);
  4477. ssh->send_ok = 0;
  4478. }
  4479. if (!ret) {
  4480. /*
  4481. * Failed to get a password (for example
  4482. * because one was supplied on the command line
  4483. * which has already failed to work). Terminate.
  4484. */
  4485. free_prompts(s->cur_prompt);
  4486. ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
  4487. crStop(0);
  4488. }
  4489. }
  4490. if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
  4491. /*
  4492. * Defence against traffic analysis: we send a
  4493. * whole bunch of packets containing strings of
  4494. * different lengths. One of these strings is the
  4495. * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
  4496. * The others are all random data in
  4497. * SSH1_MSG_IGNORE packets. This way a passive
  4498. * listener can't tell which is the password, and
  4499. * hence can't deduce the password length.
  4500. *
  4501. * Anybody with a password length greater than 16
  4502. * bytes is going to have enough entropy in their
  4503. * password that a listener won't find it _that_
  4504. * much help to know how long it is. So what we'll
  4505. * do is:
  4506. *
  4507. * - if password length < 16, we send 15 packets
  4508. * containing string lengths 1 through 15
  4509. *
  4510. * - otherwise, we let N be the nearest multiple
  4511. * of 8 below the password length, and send 8
  4512. * packets containing string lengths N through
  4513. * N+7. This won't obscure the order of
  4514. * magnitude of the password length, but it will
  4515. * introduce a bit of extra uncertainty.
  4516. *
  4517. * A few servers can't deal with SSH1_MSG_IGNORE, at
  4518. * least in this context. For these servers, we need
  4519. * an alternative defence. We make use of the fact
  4520. * that the password is interpreted as a C string:
  4521. * so we can append a NUL, then some random data.
  4522. *
  4523. * A few servers can deal with neither SSH1_MSG_IGNORE
  4524. * here _nor_ a padded password string.
  4525. * For these servers we are left with no defences
  4526. * against password length sniffing.
  4527. */
  4528. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
  4529. !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
  4530. /*
  4531. * The server can deal with SSH1_MSG_IGNORE, so
  4532. * we can use the primary defence.
  4533. */
  4534. int bottom, top, pwlen, i;
  4535. char *randomstr;
  4536. pwlen = strlen(s->cur_prompt->prompts[0]->result);
  4537. if (pwlen < 16) {
  4538. bottom = 0; /* zero length passwords are OK! :-) */
  4539. top = 15;
  4540. } else {
  4541. bottom = pwlen & ~7;
  4542. top = bottom + 7;
  4543. }
  4544. assert(pwlen >= bottom && pwlen <= top);
  4545. randomstr = snewn(top + 1, char);
  4546. for (i = bottom; i <= top; i++) {
  4547. if (i == pwlen) {
  4548. defer_packet(ssh, s->pwpkt_type,
  4549. PKT_STR,s->cur_prompt->prompts[0]->result,
  4550. PKT_END);
  4551. } else {
  4552. for (j = 0; j < i; j++) {
  4553. do {
  4554. randomstr[j] = random_byte();
  4555. } while (randomstr[j] == '\0');
  4556. }
  4557. randomstr[i] = '\0';
  4558. defer_packet(ssh, SSH1_MSG_IGNORE,
  4559. PKT_STR, randomstr, PKT_END);
  4560. }
  4561. }
  4562. logevent("Sending password with camouflage packets");
  4563. ssh_pkt_defersend(ssh);
  4564. sfree(randomstr);
  4565. }
  4566. else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
  4567. /*
  4568. * The server can't deal with SSH1_MSG_IGNORE
  4569. * but can deal with padded passwords, so we
  4570. * can use the secondary defence.
  4571. */
  4572. char string[64];
  4573. char *ss;
  4574. int len;
  4575. len = strlen(s->cur_prompt->prompts[0]->result);
  4576. if (len < sizeof(string)) {
  4577. ss = string;
  4578. strcpy(string, s->cur_prompt->prompts[0]->result);
  4579. len++; /* cover the zero byte */
  4580. while (len < sizeof(string)) {
  4581. string[len++] = (char) random_byte();
  4582. }
  4583. } else {
  4584. ss = s->cur_prompt->prompts[0]->result;
  4585. }
  4586. logevent("Sending length-padded password");
  4587. send_packet(ssh, s->pwpkt_type,
  4588. PKT_INT, len, PKT_DATA, ss, len,
  4589. PKT_END);
  4590. } else {
  4591. /*
  4592. * The server is believed unable to cope with
  4593. * any of our password camouflage methods.
  4594. */
  4595. int len;
  4596. len = strlen(s->cur_prompt->prompts[0]->result);
  4597. logevent("Sending unpadded password");
  4598. send_packet(ssh, s->pwpkt_type,
  4599. PKT_INT, len,
  4600. PKT_DATA, s->cur_prompt->prompts[0]->result, len,
  4601. PKT_END);
  4602. }
  4603. } else {
  4604. send_packet(ssh, s->pwpkt_type,
  4605. PKT_STR, s->cur_prompt->prompts[0]->result,
  4606. PKT_END);
  4607. }
  4608. logevent("Sent password");
  4609. free_prompts(s->cur_prompt);
  4610. crWaitUntil(pktin);
  4611. if (pktin->type == SSH1_SMSG_FAILURE) {
  4612. if (flags & FLAG_VERBOSE)
  4613. c_write_str(ssh, "Access denied\r\n");
  4614. logevent("Authentication refused");
  4615. } else if (pktin->type != SSH1_SMSG_SUCCESS) {
  4616. bombout(("Strange packet received, type %d", pktin->type));
  4617. crStop(0);
  4618. }
  4619. }
  4620. /* Clear up */
  4621. if (s->publickey_blob) {
  4622. sfree(s->publickey_blob);
  4623. sfree(s->publickey_comment);
  4624. }
  4625. logevent("Authentication successful");
  4626. crFinish(1);
  4627. }
  4628. static void ssh_channel_try_eof(struct ssh_channel *c)
  4629. {
  4630. Ssh ssh = c->ssh;
  4631. assert(c->pending_eof); /* precondition for calling us */
  4632. if (c->halfopen)
  4633. return; /* can't close: not even opened yet */
  4634. if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
  4635. return; /* can't send EOF: pending outgoing data */
  4636. c->pending_eof = FALSE; /* we're about to send it */
  4637. if (ssh->version == 1) {
  4638. send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
  4639. PKT_END);
  4640. c->closes |= CLOSES_SENT_EOF;
  4641. } else {
  4642. struct Packet *pktout;
  4643. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
  4644. ssh2_pkt_adduint32(pktout, c->remoteid);
  4645. ssh2_pkt_send(ssh, pktout);
  4646. c->closes |= CLOSES_SENT_EOF;
  4647. ssh2_channel_check_close(c);
  4648. }
  4649. }
  4650. Conf *sshfwd_get_conf(struct ssh_channel *c)
  4651. {
  4652. Ssh ssh = c->ssh;
  4653. return ssh->conf;
  4654. }
  4655. void sshfwd_write_eof(struct ssh_channel *c)
  4656. {
  4657. Ssh ssh = c->ssh;
  4658. if (ssh->state == SSH_STATE_CLOSED)
  4659. return;
  4660. if (c->closes & CLOSES_SENT_EOF)
  4661. return;
  4662. c->pending_eof = TRUE;
  4663. ssh_channel_try_eof(c);
  4664. }
  4665. void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
  4666. {
  4667. Ssh ssh = c->ssh;
  4668. char *reason;
  4669. if (ssh->state == SSH_STATE_CLOSED)
  4670. return;
  4671. reason = dupprintf("due to local error: %s", err);
  4672. ssh_channel_close_local(c, reason);
  4673. sfree(reason);
  4674. c->pending_eof = FALSE; /* this will confuse a zombie channel */
  4675. ssh2_channel_check_close(c);
  4676. }
  4677. int sshfwd_write(struct ssh_channel *c, char *buf, int len)
  4678. {
  4679. Ssh ssh = c->ssh;
  4680. if (ssh->state == SSH_STATE_CLOSED)
  4681. return 0;
  4682. return ssh_send_channel_data(c, buf, len);
  4683. }
  4684. void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
  4685. {
  4686. Ssh ssh = c->ssh;
  4687. if (ssh->state == SSH_STATE_CLOSED)
  4688. return;
  4689. ssh_channel_unthrottle(c, bufsize);
  4690. }
  4691. static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
  4692. {
  4693. struct queued_handler *qh = ssh->qhead;
  4694. assert(qh != NULL);
  4695. assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
  4696. if (qh->msg1 > 0) {
  4697. assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
  4698. ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
  4699. }
  4700. if (qh->msg2 > 0) {
  4701. assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
  4702. ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
  4703. }
  4704. if (qh->next) {
  4705. ssh->qhead = qh->next;
  4706. if (ssh->qhead->msg1 > 0) {
  4707. ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
  4708. ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
  4709. }
  4710. if (ssh->qhead->msg2 > 0) {
  4711. ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
  4712. ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
  4713. }
  4714. } else {
  4715. ssh->qhead = ssh->qtail = NULL;
  4716. }
  4717. qh->handler(ssh, pktin, qh->ctx);
  4718. sfree(qh);
  4719. }
  4720. static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
  4721. chandler_fn_t handler, void *ctx)
  4722. {
  4723. struct queued_handler *qh;
  4724. qh = snew(struct queued_handler);
  4725. qh->msg1 = msg1;
  4726. qh->msg2 = msg2;
  4727. qh->handler = handler;
  4728. qh->ctx = ctx;
  4729. qh->next = NULL;
  4730. if (ssh->qtail == NULL) {
  4731. ssh->qhead = qh;
  4732. if (qh->msg1 > 0) {
  4733. ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
  4734. ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
  4735. }
  4736. if (qh->msg2 > 0) {
  4737. ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
  4738. ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
  4739. }
  4740. } else {
  4741. ssh->qtail->next = qh;
  4742. }
  4743. ssh->qtail = qh;
  4744. }
  4745. static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
  4746. {
  4747. struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
  4748. if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
  4749. SSH2_MSG_REQUEST_SUCCESS)) {
  4750. logeventf(ssh, "Remote port forwarding from %s enabled",
  4751. pf->sportdesc);
  4752. } else {
  4753. logeventf(ssh, "Remote port forwarding from %s refused",
  4754. pf->sportdesc);
  4755. rpf = del234(ssh->rportfwds, pf);
  4756. assert(rpf == pf);
  4757. pf->pfrec->remote = NULL;
  4758. free_rportfwd(pf);
  4759. }
  4760. }
  4761. int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
  4762. void *share_ctx)
  4763. {
  4764. struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
  4765. pf->dhost = NULL;
  4766. pf->dport = 0;
  4767. pf->share_ctx = share_ctx;
  4768. pf->shost = dupstr(shost);
  4769. pf->sport = sport;
  4770. pf->sportdesc = NULL;
  4771. if (!ssh->rportfwds) {
  4772. assert(ssh->version == 2);
  4773. ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
  4774. }
  4775. if (add234(ssh->rportfwds, pf) != pf) {
  4776. sfree(pf->shost);
  4777. sfree(pf);
  4778. return FALSE;
  4779. }
  4780. return TRUE;
  4781. }
  4782. static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
  4783. void *ctx)
  4784. {
  4785. share_got_pkt_from_server(ctx, pktin->type,
  4786. pktin->body, pktin->length);
  4787. }
  4788. void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
  4789. {
  4790. ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
  4791. ssh_sharing_global_request_response, share_ctx);
  4792. }
  4793. static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
  4794. {
  4795. struct ssh_portfwd *epf;
  4796. int i;
  4797. char *key, *val;
  4798. if (!ssh->portfwds) {
  4799. ssh->portfwds = newtree234(ssh_portcmp);
  4800. } else {
  4801. /*
  4802. * Go through the existing port forwardings and tag them
  4803. * with status==DESTROY. Any that we want to keep will be
  4804. * re-enabled (status==KEEP) as we go through the
  4805. * configuration and find out which bits are the same as
  4806. * they were before.
  4807. */
  4808. struct ssh_portfwd *epf;
  4809. int i;
  4810. for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
  4811. epf->status = DESTROY;
  4812. }
  4813. for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
  4814. val != NULL;
  4815. val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
  4816. char *kp, *kp2, *vp, *vp2;
  4817. char address_family, type;
  4818. int sport,dport,sserv,dserv;
  4819. char *sports, *dports, *saddr, *host;
  4820. kp = key;
  4821. address_family = 'A';
  4822. type = 'L';
  4823. if (*kp == 'A' || *kp == '4' || *kp == '6')
  4824. address_family = *kp++;
  4825. if (*kp == 'L' || *kp == 'R')
  4826. type = *kp++;
  4827. if ((kp2 = host_strchr(kp, ':')) != NULL) {
  4828. /*
  4829. * There's a colon in the middle of the source port
  4830. * string, which means that the part before it is
  4831. * actually a source address.
  4832. */
  4833. char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
  4834. saddr = host_strduptrim(saddr_tmp);
  4835. sfree(saddr_tmp);
  4836. sports = kp2+1;
  4837. } else {
  4838. saddr = NULL;
  4839. sports = kp;
  4840. }
  4841. sport = atoi(sports);
  4842. sserv = 0;
  4843. if (sport == 0) {
  4844. sserv = 1;
  4845. sport = net_service_lookup(sports);
  4846. if (!sport) {
  4847. logeventf(ssh, "Service lookup failed for source"
  4848. " port \"%s\"", sports);
  4849. }
  4850. }
  4851. if (type == 'L' && !strcmp(val, "D")) {
  4852. /* dynamic forwarding */
  4853. host = NULL;
  4854. dports = NULL;
  4855. dport = -1;
  4856. dserv = 0;
  4857. type = 'D';
  4858. } else {
  4859. /* ordinary forwarding */
  4860. vp = val;
  4861. vp2 = vp + host_strcspn(vp, ":");
  4862. host = dupprintf("%.*s", (int)(vp2 - vp), vp);
  4863. if (*vp2)
  4864. vp2++;
  4865. dports = vp2;
  4866. dport = atoi(dports);
  4867. dserv = 0;
  4868. if (dport == 0) {
  4869. dserv = 1;
  4870. dport = net_service_lookup(dports);
  4871. if (!dport) {
  4872. logeventf(ssh, "Service lookup failed for destination"
  4873. " port \"%s\"", dports);
  4874. }
  4875. }
  4876. }
  4877. if (sport && dport) {
  4878. /* Set up a description of the source port. */
  4879. struct ssh_portfwd *pfrec, *epfrec;
  4880. pfrec = snew(struct ssh_portfwd);
  4881. pfrec->type = type;
  4882. pfrec->saddr = saddr;
  4883. pfrec->sserv = sserv ? dupstr(sports) : NULL;
  4884. pfrec->sport = sport;
  4885. pfrec->daddr = host;
  4886. pfrec->dserv = dserv ? dupstr(dports) : NULL;
  4887. pfrec->dport = dport;
  4888. pfrec->local = NULL;
  4889. pfrec->remote = NULL;
  4890. pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
  4891. address_family == '6' ? ADDRTYPE_IPV6 :
  4892. ADDRTYPE_UNSPEC);
  4893. epfrec = add234(ssh->portfwds, pfrec);
  4894. if (epfrec != pfrec) {
  4895. if (epfrec->status == DESTROY) {
  4896. /*
  4897. * We already have a port forwarding up and running
  4898. * with precisely these parameters. Hence, no need
  4899. * to do anything; simply re-tag the existing one
  4900. * as KEEP.
  4901. */
  4902. epfrec->status = KEEP;
  4903. }
  4904. /*
  4905. * Anything else indicates that there was a duplicate
  4906. * in our input, which we'll silently ignore.
  4907. */
  4908. free_portfwd(pfrec);
  4909. } else {
  4910. pfrec->status = CREATE;
  4911. }
  4912. } else {
  4913. sfree(saddr);
  4914. sfree(host);
  4915. }
  4916. }
  4917. /*
  4918. * Now go through and destroy any port forwardings which were
  4919. * not re-enabled.
  4920. */
  4921. for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
  4922. if (epf->status == DESTROY) {
  4923. char *message;
  4924. message = dupprintf("%s port forwarding from %s%s%d",
  4925. epf->type == 'L' ? "local" :
  4926. epf->type == 'R' ? "remote" : "dynamic",
  4927. epf->saddr ? epf->saddr : "",
  4928. epf->saddr ? ":" : "",
  4929. epf->sport);
  4930. if (epf->type != 'D') {
  4931. char *msg2 = dupprintf("%s to %s:%d", message,
  4932. epf->daddr, epf->dport);
  4933. sfree(message);
  4934. message = msg2;
  4935. }
  4936. logeventf(ssh, "Cancelling %s", message);
  4937. sfree(message);
  4938. /* epf->remote or epf->local may be NULL if setting up a
  4939. * forwarding failed. */
  4940. if (epf->remote) {
  4941. struct ssh_rportfwd *rpf = epf->remote;
  4942. struct Packet *pktout;
  4943. /*
  4944. * Cancel the port forwarding at the server
  4945. * end.
  4946. */
  4947. if (ssh->version == 1) {
  4948. /*
  4949. * We cannot cancel listening ports on the
  4950. * server side in SSH-1! There's no message
  4951. * to support it. Instead, we simply remove
  4952. * the rportfwd record from the local end
  4953. * so that any connections the server tries
  4954. * to make on it are rejected.
  4955. */
  4956. } else {
  4957. pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
  4958. ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
  4959. ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
  4960. if (epf->saddr) {
  4961. ssh2_pkt_addstring(pktout, epf->saddr);
  4962. } else if (conf_get_int(conf, CONF_rport_acceptall)) {
  4963. /* XXX: rport_acceptall may not represent
  4964. * what was used to open the original connection,
  4965. * since it's reconfigurable. */
  4966. ssh2_pkt_addstring(pktout, "");
  4967. } else {
  4968. ssh2_pkt_addstring(pktout, "localhost");
  4969. }
  4970. ssh2_pkt_adduint32(pktout, epf->sport);
  4971. ssh2_pkt_send(ssh, pktout);
  4972. }
  4973. del234(ssh->rportfwds, rpf);
  4974. free_rportfwd(rpf);
  4975. } else if (epf->local) {
  4976. pfl_terminate(epf->local);
  4977. }
  4978. delpos234(ssh->portfwds, i);
  4979. free_portfwd(epf);
  4980. i--; /* so we don't skip one in the list */
  4981. }
  4982. /*
  4983. * And finally, set up any new port forwardings (status==CREATE).
  4984. */
  4985. for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
  4986. if (epf->status == CREATE) {
  4987. char *sportdesc, *dportdesc;
  4988. sportdesc = dupprintf("%s%s%s%s%d%s",
  4989. epf->saddr ? epf->saddr : "",
  4990. epf->saddr ? ":" : "",
  4991. epf->sserv ? epf->sserv : "",
  4992. epf->sserv ? "(" : "",
  4993. epf->sport,
  4994. epf->sserv ? ")" : "");
  4995. if (epf->type == 'D') {
  4996. dportdesc = NULL;
  4997. } else {
  4998. dportdesc = dupprintf("%s:%s%s%d%s",
  4999. epf->daddr,
  5000. epf->dserv ? epf->dserv : "",
  5001. epf->dserv ? "(" : "",
  5002. epf->dport,
  5003. epf->dserv ? ")" : "");
  5004. }
  5005. if (epf->type == 'L') {
  5006. char *err = pfl_listen(epf->daddr, epf->dport,
  5007. epf->saddr, epf->sport,
  5008. ssh, conf, &epf->local,
  5009. epf->addressfamily);
  5010. logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
  5011. epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
  5012. epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
  5013. sportdesc, dportdesc,
  5014. err ? " failed: " : "", err ? err : "");
  5015. if (err)
  5016. sfree(err);
  5017. } else if (epf->type == 'D') {
  5018. char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
  5019. ssh, conf, &epf->local,
  5020. epf->addressfamily);
  5021. logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
  5022. epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
  5023. epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
  5024. sportdesc,
  5025. err ? " failed: " : "", err ? err : "");
  5026. if (err)
  5027. sfree(err);
  5028. } else {
  5029. struct ssh_rportfwd *pf;
  5030. /*
  5031. * Ensure the remote port forwardings tree exists.
  5032. */
  5033. if (!ssh->rportfwds) {
  5034. if (ssh->version == 1)
  5035. ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
  5036. else
  5037. ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
  5038. }
  5039. pf = snew(struct ssh_rportfwd);
  5040. pf->share_ctx = NULL;
  5041. pf->dhost = dupstr(epf->daddr);
  5042. pf->dport = epf->dport;
  5043. if (epf->saddr) {
  5044. pf->shost = dupstr(epf->saddr);
  5045. } else if (conf_get_int(conf, CONF_rport_acceptall)) {
  5046. pf->shost = dupstr("");
  5047. } else {
  5048. pf->shost = dupstr("localhost");
  5049. }
  5050. pf->sport = epf->sport;
  5051. if (add234(ssh->rportfwds, pf) != pf) {
  5052. logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
  5053. epf->daddr, epf->dport);
  5054. sfree(pf);
  5055. } else {
  5056. logeventf(ssh, "Requesting remote port %s"
  5057. " forward to %s", sportdesc, dportdesc);
  5058. pf->sportdesc = sportdesc;
  5059. sportdesc = NULL;
  5060. epf->remote = pf;
  5061. pf->pfrec = epf;
  5062. if (ssh->version == 1) {
  5063. send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
  5064. PKT_INT, epf->sport,
  5065. PKT_STR, epf->daddr,
  5066. PKT_INT, epf->dport,
  5067. PKT_END);
  5068. ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
  5069. SSH1_SMSG_FAILURE,
  5070. ssh_rportfwd_succfail, pf);
  5071. } else {
  5072. struct Packet *pktout;
  5073. pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
  5074. ssh2_pkt_addstring(pktout, "tcpip-forward");
  5075. ssh2_pkt_addbool(pktout, 1);/* want reply */
  5076. ssh2_pkt_addstring(pktout, pf->shost);
  5077. ssh2_pkt_adduint32(pktout, pf->sport);
  5078. ssh2_pkt_send(ssh, pktout);
  5079. ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
  5080. SSH2_MSG_REQUEST_FAILURE,
  5081. ssh_rportfwd_succfail, pf);
  5082. }
  5083. }
  5084. }
  5085. sfree(sportdesc);
  5086. sfree(dportdesc);
  5087. }
  5088. }
  5089. static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
  5090. {
  5091. char *string;
  5092. int stringlen, bufsize;
  5093. ssh_pkt_getstring(pktin, &string, &stringlen);
  5094. if (string == NULL) {
  5095. bombout(("Incoming terminal data packet was badly formed"));
  5096. return;
  5097. }
  5098. bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
  5099. string, stringlen);
  5100. if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
  5101. ssh->v1_stdout_throttling = 1;
  5102. ssh_throttle_conn(ssh, +1);
  5103. }
  5104. }
  5105. static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
  5106. {
  5107. /* Remote side is trying to open a channel to talk to our
  5108. * X-Server. Give them back a local channel number. */
  5109. struct ssh_channel *c;
  5110. int remoteid = ssh_pkt_getuint32(pktin);
  5111. logevent("Received X11 connect request");
  5112. /* Refuse if X11 forwarding is disabled. */
  5113. if (!ssh->X11_fwd_enabled) {
  5114. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  5115. PKT_INT, remoteid, PKT_END);
  5116. logevent("Rejected X11 connect request");
  5117. } else {
  5118. c = snew(struct ssh_channel);
  5119. c->ssh = ssh;
  5120. ssh_channel_init(c);
  5121. c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
  5122. c->remoteid = remoteid;
  5123. c->halfopen = FALSE;
  5124. c->type = CHAN_X11; /* identify channel type */
  5125. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
  5126. PKT_INT, c->remoteid, PKT_INT,
  5127. c->localid, PKT_END);
  5128. logevent("Opened X11 forward channel");
  5129. }
  5130. }
  5131. static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
  5132. {
  5133. /* Remote side is trying to open a channel to talk to our
  5134. * agent. Give them back a local channel number. */
  5135. struct ssh_channel *c;
  5136. int remoteid = ssh_pkt_getuint32(pktin);
  5137. /* Refuse if agent forwarding is disabled. */
  5138. if (!ssh->agentfwd_enabled) {
  5139. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  5140. PKT_INT, remoteid, PKT_END);
  5141. } else {
  5142. c = snew(struct ssh_channel);
  5143. c->ssh = ssh;
  5144. ssh_channel_init(c);
  5145. c->remoteid = remoteid;
  5146. c->halfopen = FALSE;
  5147. c->type = CHAN_AGENT; /* identify channel type */
  5148. c->u.a.pending = NULL;
  5149. bufchain_init(&c->u.a.inbuffer);
  5150. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
  5151. PKT_INT, c->remoteid, PKT_INT, c->localid,
  5152. PKT_END);
  5153. }
  5154. }
  5155. static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
  5156. {
  5157. /* Remote side is trying to open a channel to talk to a
  5158. * forwarded port. Give them back a local channel number. */
  5159. struct ssh_rportfwd pf, *pfp;
  5160. int remoteid;
  5161. int hostsize, port;
  5162. char *host;
  5163. char *err;
  5164. remoteid = ssh_pkt_getuint32(pktin);
  5165. ssh_pkt_getstring(pktin, &host, &hostsize);
  5166. port = ssh_pkt_getuint32(pktin);
  5167. pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
  5168. pf.dport = port;
  5169. pfp = find234(ssh->rportfwds, &pf, NULL);
  5170. if (pfp == NULL) {
  5171. logeventf(ssh, "Rejected remote port open request for %s:%d",
  5172. pf.dhost, port);
  5173. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  5174. PKT_INT, remoteid, PKT_END);
  5175. } else {
  5176. struct ssh_channel *c = snew(struct ssh_channel);
  5177. c->ssh = ssh;
  5178. logeventf(ssh, "Received remote port open request for %s:%d",
  5179. pf.dhost, port);
  5180. err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
  5181. c, ssh->conf, pfp->pfrec->addressfamily);
  5182. if (err != NULL) {
  5183. logeventf(ssh, "Port open failed: %s", err);
  5184. sfree(err);
  5185. sfree(c);
  5186. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  5187. PKT_INT, remoteid, PKT_END);
  5188. } else {
  5189. ssh_channel_init(c);
  5190. c->remoteid = remoteid;
  5191. c->halfopen = FALSE;
  5192. c->type = CHAN_SOCKDATA; /* identify channel type */
  5193. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
  5194. PKT_INT, c->remoteid, PKT_INT,
  5195. c->localid, PKT_END);
  5196. logevent("Forwarded port opened successfully");
  5197. }
  5198. }
  5199. sfree(pf.dhost);
  5200. }
  5201. static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
  5202. {
  5203. struct ssh_channel *c;
  5204. c = ssh_channel_msg(ssh, pktin);
  5205. if (c && c->type == CHAN_SOCKDATA) {
  5206. c->remoteid = ssh_pkt_getuint32(pktin);
  5207. c->halfopen = FALSE;
  5208. c->throttling_conn = 0;
  5209. pfd_confirm(c->u.pfd.pf);
  5210. }
  5211. if (c && c->pending_eof) {
  5212. /*
  5213. * We have a pending close on this channel,
  5214. * which we decided on before the server acked
  5215. * the channel open. So now we know the
  5216. * remoteid, we can close it again.
  5217. */
  5218. ssh_channel_try_eof(c);
  5219. }
  5220. }
  5221. static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
  5222. {
  5223. struct ssh_channel *c;
  5224. c = ssh_channel_msg(ssh, pktin);
  5225. if (c && c->type == CHAN_SOCKDATA) {
  5226. logevent("Forwarded connection refused by server");
  5227. pfd_close(c->u.pfd.pf);
  5228. del234(ssh->channels, c);
  5229. sfree(c);
  5230. }
  5231. }
  5232. static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
  5233. {
  5234. /* Remote side closes a channel. */
  5235. struct ssh_channel *c;
  5236. c = ssh_channel_msg(ssh, pktin);
  5237. if (c) {
  5238. if (pktin->type == SSH1_MSG_CHANNEL_CLOSE) {
  5239. /*
  5240. * Received CHANNEL_CLOSE, which we translate into
  5241. * outgoing EOF.
  5242. */
  5243. ssh_channel_got_eof(c);
  5244. }
  5245. if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
  5246. !(c->closes & CLOSES_RCVD_CLOSE)) {
  5247. if (!(c->closes & CLOSES_SENT_EOF)) {
  5248. bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %u"
  5249. " for which we never sent CHANNEL_CLOSE\n",
  5250. c->localid));
  5251. }
  5252. c->closes |= CLOSES_RCVD_CLOSE;
  5253. }
  5254. if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
  5255. !(c->closes & CLOSES_SENT_CLOSE)) {
  5256. send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
  5257. PKT_INT, c->remoteid, PKT_END);
  5258. c->closes |= CLOSES_SENT_CLOSE;
  5259. }
  5260. if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
  5261. ssh_channel_destroy(c);
  5262. }
  5263. }
  5264. /*
  5265. * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
  5266. */
  5267. static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
  5268. int length)
  5269. {
  5270. bufchain_add(&c->u.a.inbuffer, data, length);
  5271. ssh_agentf_try_forward(c);
  5272. /*
  5273. * We exert back-pressure on an agent forwarding client if and
  5274. * only if we're waiting for the response to an asynchronous agent
  5275. * request. This prevents the client running out of window while
  5276. * receiving the _first_ message, but means that if any message
  5277. * takes time to process, the client will be discouraged from
  5278. * sending an endless stream of further ones after it.
  5279. */
  5280. return (c->u.a.pending ? bufchain_size(&c->u.a.inbuffer) : 0);
  5281. }
  5282. static int ssh_channel_data(struct ssh_channel *c, int is_stderr,
  5283. char *data, int length)
  5284. {
  5285. switch (c->type) {
  5286. case CHAN_MAINSESSION:
  5287. return from_backend(c->ssh->frontend, is_stderr, data, length);
  5288. case CHAN_X11:
  5289. return x11_send(c->u.x11.xconn, data, length);
  5290. case CHAN_SOCKDATA:
  5291. return pfd_send(c->u.pfd.pf, data, length);
  5292. case CHAN_AGENT:
  5293. return ssh_agent_channel_data(c, data, length);
  5294. }
  5295. return 0;
  5296. }
  5297. static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
  5298. {
  5299. /* Data sent down one of our channels. */
  5300. char *p;
  5301. int len;
  5302. struct ssh_channel *c;
  5303. c = ssh_channel_msg(ssh, pktin);
  5304. ssh_pkt_getstring(pktin, &p, &len);
  5305. if (c) {
  5306. int bufsize = ssh_channel_data(c, FALSE, p, len);
  5307. if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
  5308. c->throttling_conn = 1;
  5309. ssh_throttle_conn(ssh, +1);
  5310. }
  5311. }
  5312. }
  5313. static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
  5314. {
  5315. ssh->exitcode = ssh_pkt_getuint32(pktin);
  5316. logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
  5317. send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
  5318. /*
  5319. * In case `helpful' firewalls or proxies tack
  5320. * extra human-readable text on the end of the
  5321. * session which we might mistake for another
  5322. * encrypted packet, we close the session once
  5323. * we've sent EXIT_CONFIRMATION.
  5324. */
  5325. ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
  5326. }
  5327. /* Helper function to deal with sending tty modes for REQUEST_PTY */
  5328. static void ssh1_send_ttymode(void *data,
  5329. const struct ssh_ttymode *mode, char *val)
  5330. {
  5331. struct Packet *pktout = (struct Packet *)data;
  5332. unsigned int arg = 0;
  5333. switch (mode->type) {
  5334. case TTY_OP_CHAR:
  5335. arg = ssh_tty_parse_specchar(val);
  5336. break;
  5337. case TTY_OP_BOOL:
  5338. arg = ssh_tty_parse_boolean(val);
  5339. break;
  5340. }
  5341. ssh2_pkt_addbyte(pktout, mode->opcode);
  5342. ssh2_pkt_addbyte(pktout, arg);
  5343. }
  5344. int ssh_agent_forwarding_permitted(Ssh ssh)
  5345. {
  5346. return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
  5347. }
  5348. static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
  5349. struct Packet *pktin)
  5350. {
  5351. crBegin(ssh->do_ssh1_connection_crstate);
  5352. ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
  5353. ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
  5354. ssh1_smsg_stdout_stderr_data;
  5355. ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
  5356. ssh1_msg_channel_open_confirmation;
  5357. ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
  5358. ssh1_msg_channel_open_failure;
  5359. ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
  5360. ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
  5361. ssh1_msg_channel_close;
  5362. ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
  5363. ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
  5364. if (ssh_agent_forwarding_permitted(ssh)) {
  5365. logevent("Requesting agent forwarding");
  5366. send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
  5367. do {
  5368. crReturnV;
  5369. } while (!pktin);
  5370. if (pktin->type != SSH1_SMSG_SUCCESS
  5371. && pktin->type != SSH1_SMSG_FAILURE) {
  5372. bombout(("Protocol confusion"));
  5373. crStopV;
  5374. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5375. logevent("Agent forwarding refused");
  5376. } else {
  5377. logevent("Agent forwarding enabled");
  5378. ssh->agentfwd_enabled = TRUE;
  5379. ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
  5380. }
  5381. }
  5382. if (conf_get_int(ssh->conf, CONF_x11_forward)) {
  5383. ssh->x11disp =
  5384. x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
  5385. ssh->conf);
  5386. if (!ssh->x11disp) {
  5387. /* FIXME: return an error message from x11_setup_display */
  5388. logevent("X11 forwarding not enabled: unable to"
  5389. " initialise X display");
  5390. } else {
  5391. ssh->x11auth = x11_invent_fake_auth
  5392. (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
  5393. ssh->x11auth->disp = ssh->x11disp;
  5394. logevent("Requesting X11 forwarding");
  5395. if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
  5396. send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
  5397. PKT_STR, ssh->x11auth->protoname,
  5398. PKT_STR, ssh->x11auth->datastring,
  5399. PKT_INT, ssh->x11disp->screennum,
  5400. PKT_END);
  5401. } else {
  5402. send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
  5403. PKT_STR, ssh->x11auth->protoname,
  5404. PKT_STR, ssh->x11auth->datastring,
  5405. PKT_END);
  5406. }
  5407. do {
  5408. crReturnV;
  5409. } while (!pktin);
  5410. if (pktin->type != SSH1_SMSG_SUCCESS
  5411. && pktin->type != SSH1_SMSG_FAILURE) {
  5412. bombout(("Protocol confusion"));
  5413. crStopV;
  5414. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5415. logevent("X11 forwarding refused");
  5416. } else {
  5417. logevent("X11 forwarding enabled");
  5418. ssh->X11_fwd_enabled = TRUE;
  5419. ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
  5420. }
  5421. }
  5422. }
  5423. ssh_setup_portfwd(ssh, ssh->conf);
  5424. ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
  5425. if (!conf_get_int(ssh->conf, CONF_nopty)) {
  5426. struct Packet *pkt;
  5427. /* Unpick the terminal-speed string. */
  5428. /* XXX perhaps we should allow no speeds to be sent. */
  5429. ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
  5430. sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
  5431. /* Send the pty request. */
  5432. pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
  5433. ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
  5434. ssh_pkt_adduint32(pkt, ssh->term_height);
  5435. ssh_pkt_adduint32(pkt, ssh->term_width);
  5436. ssh_pkt_adduint32(pkt, 0); /* width in pixels */
  5437. ssh_pkt_adduint32(pkt, 0); /* height in pixels */
  5438. parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
  5439. ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
  5440. ssh_pkt_adduint32(pkt, ssh->ispeed);
  5441. ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
  5442. ssh_pkt_adduint32(pkt, ssh->ospeed);
  5443. ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
  5444. s_wrpkt(ssh, pkt);
  5445. ssh->state = SSH_STATE_INTERMED;
  5446. do {
  5447. crReturnV;
  5448. } while (!pktin);
  5449. if (pktin->type != SSH1_SMSG_SUCCESS
  5450. && pktin->type != SSH1_SMSG_FAILURE) {
  5451. bombout(("Protocol confusion"));
  5452. crStopV;
  5453. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5454. c_write_str(ssh, "Server refused to allocate pty\r\n");
  5455. ssh->editing = ssh->echoing = 1;
  5456. } else {
  5457. logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
  5458. ssh->ospeed, ssh->ispeed);
  5459. ssh->got_pty = TRUE;
  5460. }
  5461. } else {
  5462. ssh->editing = ssh->echoing = 1;
  5463. }
  5464. if (conf_get_int(ssh->conf, CONF_compression)) {
  5465. send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
  5466. do {
  5467. crReturnV;
  5468. } while (!pktin);
  5469. if (pktin->type != SSH1_SMSG_SUCCESS
  5470. && pktin->type != SSH1_SMSG_FAILURE) {
  5471. bombout(("Protocol confusion"));
  5472. crStopV;
  5473. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5474. c_write_str(ssh, "Server refused to compress\r\n");
  5475. }
  5476. logevent("Started compression");
  5477. ssh->v1_compressing = TRUE;
  5478. ssh->cs_comp_ctx = zlib_compress_init();
  5479. logevent("Initialised zlib (RFC1950) compression");
  5480. ssh->sc_comp_ctx = zlib_decompress_init();
  5481. logevent("Initialised zlib (RFC1950) decompression");
  5482. }
  5483. /*
  5484. * Start the shell or command.
  5485. *
  5486. * Special case: if the first-choice command is an SSH-2
  5487. * subsystem (hence not usable here) and the second choice
  5488. * exists, we fall straight back to that.
  5489. */
  5490. {
  5491. char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
  5492. if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
  5493. conf_get_str(ssh->conf, CONF_remote_cmd2)) {
  5494. cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
  5495. ssh->fallback_cmd = TRUE;
  5496. }
  5497. if (*cmd)
  5498. send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
  5499. else
  5500. send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
  5501. logevent("Started session");
  5502. }
  5503. ssh->state = SSH_STATE_SESSION;
  5504. if (ssh->size_needed)
  5505. ssh_size(ssh, ssh->term_width, ssh->term_height);
  5506. if (ssh->eof_needed)
  5507. ssh_special(ssh, TS_EOF);
  5508. if (ssh->ldisc)
  5509. ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
  5510. ssh->send_ok = 1;
  5511. ssh->channels = newtree234(ssh_channelcmp);
  5512. while (1) {
  5513. /*
  5514. * By this point, most incoming packets are already being
  5515. * handled by the dispatch table, and we need only pay
  5516. * attention to the unusual ones.
  5517. */
  5518. crReturnV;
  5519. if (pktin) {
  5520. if (pktin->type == SSH1_SMSG_SUCCESS) {
  5521. /* may be from EXEC_SHELL on some servers */
  5522. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5523. /* may be from EXEC_SHELL on some servers
  5524. * if no pty is available or in other odd cases. Ignore */
  5525. } else {
  5526. bombout(("Strange packet received: type %d", pktin->type));
  5527. crStopV;
  5528. }
  5529. } else {
  5530. while (inlen > 0) {
  5531. int len = min(inlen, 512);
  5532. send_packet(ssh, SSH1_CMSG_STDIN_DATA,
  5533. PKT_INT, len, PKT_DATA, in, len,
  5534. PKT_END);
  5535. in += len;
  5536. inlen -= len;
  5537. }
  5538. }
  5539. }
  5540. crFinishV;
  5541. }
  5542. /*
  5543. * Handle the top-level SSH-2 protocol.
  5544. */
  5545. static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
  5546. {
  5547. char *msg;
  5548. int msglen;
  5549. ssh_pkt_getstring(pktin, &msg, &msglen);
  5550. logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
  5551. }
  5552. static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
  5553. {
  5554. /* log reason code in disconnect message */
  5555. char *msg;
  5556. int msglen;
  5557. ssh_pkt_getstring(pktin, &msg, &msglen);
  5558. bombout(("Server sent disconnect message:\n\"%.*s\"",
  5559. msglen, NULLTOEMPTY(msg)));
  5560. }
  5561. static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
  5562. {
  5563. /* Do nothing, because we're ignoring it! Duhh. */
  5564. }
  5565. static void ssh1_protocol_setup(Ssh ssh)
  5566. {
  5567. int i;
  5568. /*
  5569. * Most messages are handled by the coroutines.
  5570. */
  5571. for (i = 0; i < 256; i++)
  5572. ssh->packet_dispatch[i] = NULL;
  5573. /*
  5574. * These special message types we install handlers for.
  5575. */
  5576. ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
  5577. ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
  5578. ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
  5579. }
  5580. static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
  5581. struct Packet *pktin)
  5582. {
  5583. const unsigned char *in = (const unsigned char *)vin;
  5584. if (ssh->state == SSH_STATE_CLOSED)
  5585. return;
  5586. if (pktin && ssh->packet_dispatch[pktin->type]) {
  5587. ssh->packet_dispatch[pktin->type](ssh, pktin);
  5588. return;
  5589. }
  5590. if (!ssh->protocol_initial_phase_done) {
  5591. if (do_ssh1_login(ssh, in, inlen, pktin))
  5592. ssh->protocol_initial_phase_done = TRUE;
  5593. else
  5594. return;
  5595. }
  5596. do_ssh1_connection(ssh, in, inlen, pktin);
  5597. }
  5598. /*
  5599. * Utility routines for decoding comma-separated strings in KEXINIT.
  5600. */
  5601. static int first_in_commasep_string(char const *needle, char const *haystack,
  5602. int haylen)
  5603. {
  5604. int needlen;
  5605. if (!needle || !haystack) /* protect against null pointers */
  5606. return 0;
  5607. needlen = strlen(needle);
  5608. if (haylen >= needlen && /* haystack is long enough */
  5609. !memcmp(needle, haystack, needlen) && /* initial match */
  5610. (haylen == needlen || haystack[needlen] == ',')
  5611. /* either , or EOS follows */
  5612. )
  5613. return 1;
  5614. return 0;
  5615. }
  5616. static int in_commasep_string(char const *needle, char const *haystack,
  5617. int haylen)
  5618. {
  5619. char *p;
  5620. if (!needle || !haystack) /* protect against null pointers */
  5621. return 0;
  5622. /*
  5623. * Is it at the start of the string?
  5624. */
  5625. if (first_in_commasep_string(needle, haystack, haylen))
  5626. return 1;
  5627. /*
  5628. * If not, search for the next comma and resume after that.
  5629. * If no comma found, terminate.
  5630. */
  5631. p = memchr(haystack, ',', haylen);
  5632. if (!p) return 0;
  5633. /* + 1 to skip over comma */
  5634. return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
  5635. }
  5636. /*
  5637. * Add a value to the comma-separated string at the end of the packet.
  5638. */
  5639. static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
  5640. {
  5641. if (pkt->length - pkt->savedpos > 0)
  5642. ssh_pkt_addstring_str(pkt, ",");
  5643. ssh_pkt_addstring_str(pkt, data);
  5644. }
  5645. /*
  5646. * SSH-2 key derivation (RFC 4253 section 7.2).
  5647. */
  5648. static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
  5649. char chr, int keylen)
  5650. {
  5651. const struct ssh_hash *h = ssh->kex->hash;
  5652. int keylen_padded;
  5653. unsigned char *key;
  5654. void *s, *s2;
  5655. if (keylen == 0)
  5656. return NULL;
  5657. /* Round up to the next multiple of hash length. */
  5658. keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
  5659. key = snewn(keylen_padded, unsigned char);
  5660. /* First hlen bytes. */
  5661. s = h->init();
  5662. if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
  5663. hash_mpint(h, s, K);
  5664. h->bytes(s, H, h->hlen);
  5665. h->bytes(s, &chr, 1);
  5666. h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
  5667. h->final(s, key);
  5668. /* Subsequent blocks of hlen bytes. */
  5669. if (keylen_padded > h->hlen) {
  5670. int offset;
  5671. s = h->init();
  5672. if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
  5673. hash_mpint(h, s, K);
  5674. h->bytes(s, H, h->hlen);
  5675. for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
  5676. h->bytes(s, key + offset - h->hlen, h->hlen);
  5677. s2 = h->copy(s);
  5678. h->final(s2, key + offset);
  5679. }
  5680. h->free(s);
  5681. }
  5682. /* Now clear any extra bytes of key material beyond the length
  5683. * we're officially returning, because the caller won't know to
  5684. * smemclr those. */
  5685. if (keylen_padded > keylen)
  5686. smemclr(key + keylen, keylen_padded - keylen);
  5687. return key;
  5688. }
  5689. /*
  5690. * Structure for constructing KEXINIT algorithm lists.
  5691. */
  5692. #define MAXKEXLIST 16
  5693. struct kexinit_algorithm {
  5694. const char *name;
  5695. union {
  5696. struct {
  5697. const struct ssh_kex *kex;
  5698. int warn;
  5699. } kex;
  5700. struct {
  5701. const struct ssh_signkey *hostkey;
  5702. int warn;
  5703. } hk;
  5704. struct {
  5705. const struct ssh2_cipher *cipher;
  5706. int warn;
  5707. } cipher;
  5708. struct {
  5709. const struct ssh_mac *mac;
  5710. int etm;
  5711. } mac;
  5712. const struct ssh_compress *comp;
  5713. } u;
  5714. };
  5715. /*
  5716. * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
  5717. * If the algorithm is already in the list, return a pointer to its
  5718. * entry, otherwise return an entry from the end of the list.
  5719. * This assumes that every time a particular name is passed in, it
  5720. * comes from the same string constant. If this isn't true, this
  5721. * function may need to be rewritten to use strcmp() instead.
  5722. */
  5723. static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
  5724. *list, const char *name)
  5725. {
  5726. int i;
  5727. for (i = 0; i < MAXKEXLIST; i++)
  5728. if (list[i].name == NULL || list[i].name == name) {
  5729. list[i].name = name;
  5730. return &list[i];
  5731. }
  5732. assert(!"No space in KEXINIT list");
  5733. return NULL;
  5734. }
  5735. /*
  5736. * Handle the SSH-2 transport layer.
  5737. */
  5738. static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
  5739. struct Packet *pktin)
  5740. {
  5741. const unsigned char *in = (const unsigned char *)vin;
  5742. enum kexlist {
  5743. KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
  5744. KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
  5745. NKEXLIST
  5746. };
  5747. const char * kexlist_descr[NKEXLIST] = {
  5748. "key exchange algorithm", "host key algorithm",
  5749. "client-to-server cipher", "server-to-client cipher",
  5750. "client-to-server MAC", "server-to-client MAC",
  5751. "client-to-server compression method",
  5752. "server-to-client compression method" };
  5753. struct do_ssh2_transport_state {
  5754. int crLine;
  5755. int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
  5756. Bignum p, g, e, f, K;
  5757. void *our_kexinit;
  5758. int our_kexinitlen;
  5759. int kex_init_value, kex_reply_value;
  5760. const struct ssh_mac *const *maclist;
  5761. int nmacs;
  5762. const struct ssh2_cipher *cscipher_tobe;
  5763. const struct ssh2_cipher *sccipher_tobe;
  5764. const struct ssh_mac *csmac_tobe;
  5765. const struct ssh_mac *scmac_tobe;
  5766. int csmac_etm_tobe, scmac_etm_tobe;
  5767. const struct ssh_compress *cscomp_tobe;
  5768. const struct ssh_compress *sccomp_tobe;
  5769. char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
  5770. int hostkeylen, siglen, rsakeylen;
  5771. void *hkey; /* actual host key */
  5772. void *rsakey; /* for RSA kex */
  5773. void *eckey; /* for ECDH kex */
  5774. unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
  5775. int n_preferred_kex;
  5776. const struct ssh_kexes *preferred_kex[KEX_MAX];
  5777. int n_preferred_hk;
  5778. int preferred_hk[HK_MAX];
  5779. int n_preferred_ciphers;
  5780. const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
  5781. const struct ssh_compress *preferred_comp;
  5782. int userauth_succeeded; /* for delayed compression */
  5783. int pending_compression;
  5784. int got_session_id, activated_authconn;
  5785. struct Packet *pktout;
  5786. int dlgret;
  5787. int guessok;
  5788. int ignorepkt;
  5789. struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
  5790. };
  5791. crState(do_ssh2_transport_state);
  5792. assert(!ssh->bare_connection);
  5793. assert(ssh->version == 2);
  5794. crBeginState;
  5795. s->cscipher_tobe = s->sccipher_tobe = NULL;
  5796. s->csmac_tobe = s->scmac_tobe = NULL;
  5797. s->cscomp_tobe = s->sccomp_tobe = NULL;
  5798. s->got_session_id = s->activated_authconn = FALSE;
  5799. s->userauth_succeeded = FALSE;
  5800. s->pending_compression = FALSE;
  5801. /*
  5802. * Be prepared to work around the buggy MAC problem.
  5803. */
  5804. if (ssh->remote_bugs & BUG_SSH2_HMAC)
  5805. s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
  5806. else
  5807. s->maclist = macs, s->nmacs = lenof(macs);
  5808. begin_key_exchange:
  5809. ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
  5810. {
  5811. int i, j, k, warn;
  5812. struct kexinit_algorithm *alg;
  5813. /*
  5814. * Set up the preferred key exchange. (NULL => warn below here)
  5815. */
  5816. s->n_preferred_kex = 0;
  5817. for (i = 0; i < KEX_MAX; i++) {
  5818. switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
  5819. case KEX_DHGEX:
  5820. s->preferred_kex[s->n_preferred_kex++] =
  5821. &ssh_diffiehellman_gex;
  5822. break;
  5823. case KEX_DHGROUP14:
  5824. s->preferred_kex[s->n_preferred_kex++] =
  5825. &ssh_diffiehellman_group14;
  5826. break;
  5827. case KEX_DHGROUP1:
  5828. s->preferred_kex[s->n_preferred_kex++] =
  5829. &ssh_diffiehellman_group1;
  5830. break;
  5831. case KEX_RSA:
  5832. s->preferred_kex[s->n_preferred_kex++] =
  5833. &ssh_rsa_kex;
  5834. break;
  5835. case KEX_ECDH:
  5836. s->preferred_kex[s->n_preferred_kex++] =
  5837. &ssh_ecdh_kex;
  5838. break;
  5839. case KEX_WARN:
  5840. /* Flag for later. Don't bother if it's the last in
  5841. * the list. */
  5842. if (i < KEX_MAX - 1) {
  5843. s->preferred_kex[s->n_preferred_kex++] = NULL;
  5844. }
  5845. break;
  5846. }
  5847. }
  5848. /*
  5849. * Set up the preferred host key types. These are just the ids
  5850. * in the enum in putty.h, so 'warn below here' is indicated
  5851. * by HK_WARN.
  5852. */
  5853. s->n_preferred_hk = 0;
  5854. for (i = 0; i < HK_MAX; i++) {
  5855. int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
  5856. /* As above, don't bother with HK_WARN if it's last in the
  5857. * list */
  5858. if (id != HK_WARN || i < HK_MAX - 1)
  5859. s->preferred_hk[s->n_preferred_hk++] = id;
  5860. }
  5861. /*
  5862. * Set up the preferred ciphers. (NULL => warn below here)
  5863. */
  5864. s->n_preferred_ciphers = 0;
  5865. for (i = 0; i < CIPHER_MAX; i++) {
  5866. switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
  5867. case CIPHER_BLOWFISH:
  5868. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
  5869. break;
  5870. case CIPHER_DES:
  5871. if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
  5872. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
  5873. }
  5874. break;
  5875. case CIPHER_3DES:
  5876. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
  5877. break;
  5878. case CIPHER_AES:
  5879. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
  5880. break;
  5881. case CIPHER_ARCFOUR:
  5882. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
  5883. break;
  5884. case CIPHER_CHACHA20:
  5885. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
  5886. break;
  5887. case CIPHER_WARN:
  5888. /* Flag for later. Don't bother if it's the last in
  5889. * the list. */
  5890. if (i < CIPHER_MAX - 1) {
  5891. s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
  5892. }
  5893. break;
  5894. }
  5895. }
  5896. /*
  5897. * Set up preferred compression.
  5898. */
  5899. if (conf_get_int(ssh->conf, CONF_compression))
  5900. s->preferred_comp = &ssh_zlib;
  5901. else
  5902. s->preferred_comp = &ssh_comp_none;
  5903. /*
  5904. * Enable queueing of outgoing auth- or connection-layer
  5905. * packets while we are in the middle of a key exchange.
  5906. */
  5907. ssh->queueing = TRUE;
  5908. /*
  5909. * Flag that KEX is in progress.
  5910. */
  5911. ssh->kex_in_progress = TRUE;
  5912. for (i = 0; i < NKEXLIST; i++)
  5913. for (j = 0; j < MAXKEXLIST; j++)
  5914. s->kexlists[i][j].name = NULL;
  5915. /* List key exchange algorithms. */
  5916. warn = FALSE;
  5917. for (i = 0; i < s->n_preferred_kex; i++) {
  5918. const struct ssh_kexes *k = s->preferred_kex[i];
  5919. if (!k) warn = TRUE;
  5920. else for (j = 0; j < k->nkexes; j++) {
  5921. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
  5922. k->list[j]->name);
  5923. alg->u.kex.kex = k->list[j];
  5924. alg->u.kex.warn = warn;
  5925. }
  5926. }
  5927. /* List server host key algorithms. */
  5928. if (!s->got_session_id) {
  5929. /*
  5930. * In the first key exchange, we list all the algorithms
  5931. * we're prepared to cope with, but prefer those algorithms
  5932. * for which we have a host key for this host.
  5933. *
  5934. * If the host key algorithm is below the warning
  5935. * threshold, we warn even if we did already have a key
  5936. * for it, on the basis that if the user has just
  5937. * reconfigured that host key type to be warned about,
  5938. * they surely _do_ want to be alerted that a server
  5939. * they're actually connecting to is using it.
  5940. */
  5941. warn = FALSE;
  5942. for (i = 0; i < s->n_preferred_hk; i++) {
  5943. if (s->preferred_hk[i] == HK_WARN)
  5944. warn = TRUE;
  5945. for (j = 0; j < lenof(hostkey_algs); j++) {
  5946. if (hostkey_algs[j].id != s->preferred_hk[i])
  5947. continue;
  5948. if (have_ssh_host_key(
  5949. #ifdef MPEXT
  5950. ssh->frontend,
  5951. #endif
  5952. ssh->savedhost, ssh->savedport,
  5953. hostkey_algs[j].alg->keytype)) {
  5954. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  5955. hostkey_algs[j].alg->name);
  5956. alg->u.hk.hostkey = hostkey_algs[j].alg;
  5957. alg->u.hk.warn = warn;
  5958. }
  5959. }
  5960. }
  5961. warn = FALSE;
  5962. for (i = 0; i < s->n_preferred_hk; i++) {
  5963. if (s->preferred_hk[i] == HK_WARN)
  5964. warn = TRUE;
  5965. for (j = 0; j < lenof(hostkey_algs); j++) {
  5966. if (hostkey_algs[j].id != s->preferred_hk[i])
  5967. continue;
  5968. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  5969. hostkey_algs[j].alg->name);
  5970. alg->u.hk.hostkey = hostkey_algs[j].alg;
  5971. alg->u.hk.warn = warn;
  5972. }
  5973. }
  5974. } else {
  5975. /*
  5976. * In subsequent key exchanges, we list only the kex
  5977. * algorithm that was selected in the first key exchange,
  5978. * so that we keep getting the same host key and hence
  5979. * don't have to interrupt the user's session to ask for
  5980. * reverification.
  5981. */
  5982. assert(ssh->kex);
  5983. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  5984. ssh->hostkey->name);
  5985. alg->u.hk.hostkey = ssh->hostkey;
  5986. alg->u.hk.warn = FALSE;
  5987. }
  5988. /* List encryption algorithms (client->server then server->client). */
  5989. for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
  5990. warn = FALSE;
  5991. #ifdef FUZZING
  5992. alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
  5993. alg->u.cipher.cipher = NULL;
  5994. alg->u.cipher.warn = warn;
  5995. #endif /* FUZZING */
  5996. for (i = 0; i < s->n_preferred_ciphers; i++) {
  5997. const struct ssh2_ciphers *c = s->preferred_ciphers[i];
  5998. if (!c) warn = TRUE;
  5999. else for (j = 0; j < c->nciphers; j++) {
  6000. alg = ssh2_kexinit_addalg(s->kexlists[k],
  6001. c->list[j]->name);
  6002. alg->u.cipher.cipher = c->list[j];
  6003. alg->u.cipher.warn = warn;
  6004. }
  6005. }
  6006. }
  6007. /* List MAC algorithms (client->server then server->client). */
  6008. for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
  6009. #ifdef FUZZING
  6010. alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
  6011. alg->u.mac.mac = NULL;
  6012. alg->u.mac.etm = FALSE;
  6013. #endif /* FUZZING */
  6014. for (i = 0; i < s->nmacs; i++) {
  6015. alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
  6016. alg->u.mac.mac = s->maclist[i];
  6017. alg->u.mac.etm = FALSE;
  6018. }
  6019. for (i = 0; i < s->nmacs; i++)
  6020. /* For each MAC, there may also be an ETM version,
  6021. * which we list second. */
  6022. if (s->maclist[i]->etm_name) {
  6023. alg = ssh2_kexinit_addalg(s->kexlists[j],
  6024. s->maclist[i]->etm_name);
  6025. alg->u.mac.mac = s->maclist[i];
  6026. alg->u.mac.etm = TRUE;
  6027. }
  6028. }
  6029. /* List client->server compression algorithms,
  6030. * then server->client compression algorithms. (We use the
  6031. * same set twice.) */
  6032. for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
  6033. assert(lenof(compressions) > 1);
  6034. /* Prefer non-delayed versions */
  6035. alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
  6036. alg->u.comp = s->preferred_comp;
  6037. /* We don't even list delayed versions of algorithms until
  6038. * they're allowed to be used, to avoid a race. See the end of
  6039. * this function. */
  6040. if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
  6041. alg = ssh2_kexinit_addalg(s->kexlists[j],
  6042. s->preferred_comp->delayed_name);
  6043. alg->u.comp = s->preferred_comp;
  6044. }
  6045. for (i = 0; i < lenof(compressions); i++) {
  6046. const struct ssh_compress *c = compressions[i];
  6047. alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
  6048. alg->u.comp = c;
  6049. if (s->userauth_succeeded && c->delayed_name) {
  6050. alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
  6051. alg->u.comp = c;
  6052. }
  6053. }
  6054. }
  6055. /*
  6056. * Construct and send our key exchange packet.
  6057. */
  6058. s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
  6059. for (i = 0; i < 16; i++)
  6060. ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
  6061. for (i = 0; i < NKEXLIST; i++) {
  6062. ssh2_pkt_addstring_start(s->pktout);
  6063. for (j = 0; j < MAXKEXLIST; j++) {
  6064. if (s->kexlists[i][j].name == NULL) break;
  6065. ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
  6066. }
  6067. }
  6068. /* List client->server languages. Empty list. */
  6069. ssh2_pkt_addstring_start(s->pktout);
  6070. /* List server->client languages. Empty list. */
  6071. ssh2_pkt_addstring_start(s->pktout);
  6072. /* First KEX packet does _not_ follow, because we're not that brave. */
  6073. ssh2_pkt_addbool(s->pktout, FALSE);
  6074. /* Reserved. */
  6075. ssh2_pkt_adduint32(s->pktout, 0);
  6076. }
  6077. s->our_kexinitlen = s->pktout->length - 5;
  6078. s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
  6079. memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
  6080. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6081. if (!pktin)
  6082. crWaitUntilV(pktin);
  6083. /*
  6084. * Now examine the other side's KEXINIT to see what we're up
  6085. * to.
  6086. */
  6087. {
  6088. char *str;
  6089. int i, j, len;
  6090. if (pktin->type != SSH2_MSG_KEXINIT) {
  6091. bombout(("expected key exchange packet from server"));
  6092. crStopV;
  6093. }
  6094. ssh->kex = NULL;
  6095. ssh->hostkey = NULL;
  6096. s->cscipher_tobe = NULL;
  6097. s->sccipher_tobe = NULL;
  6098. s->csmac_tobe = NULL;
  6099. s->scmac_tobe = NULL;
  6100. s->cscomp_tobe = NULL;
  6101. s->sccomp_tobe = NULL;
  6102. s->warn_kex = s->warn_hk = FALSE;
  6103. s->warn_cscipher = s->warn_sccipher = FALSE;
  6104. pktin->savedpos += 16; /* skip garbage cookie */
  6105. s->guessok = FALSE;
  6106. for (i = 0; i < NKEXLIST; i++) {
  6107. ssh_pkt_getstring(pktin, &str, &len);
  6108. if (!str) {
  6109. bombout(("KEXINIT packet was incomplete"));
  6110. crStopV;
  6111. }
  6112. /* If we've already selected a cipher which requires a
  6113. * particular MAC, then just select that, and don't even
  6114. * bother looking through the server's KEXINIT string for
  6115. * MACs. */
  6116. if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
  6117. s->cscipher_tobe->required_mac) {
  6118. s->csmac_tobe = s->cscipher_tobe->required_mac;
  6119. s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
  6120. goto matched;
  6121. }
  6122. if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
  6123. s->sccipher_tobe->required_mac) {
  6124. s->scmac_tobe = s->sccipher_tobe->required_mac;
  6125. s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
  6126. goto matched;
  6127. }
  6128. for (j = 0; j < MAXKEXLIST; j++) {
  6129. struct kexinit_algorithm *alg = &s->kexlists[i][j];
  6130. if (alg->name == NULL) break;
  6131. if (in_commasep_string(alg->name, str, len)) {
  6132. /* We've found a matching algorithm. */
  6133. if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
  6134. /* Check if we might need to ignore first kex pkt */
  6135. if (j != 0 ||
  6136. !first_in_commasep_string(alg->name, str, len))
  6137. s->guessok = FALSE;
  6138. }
  6139. if (i == KEXLIST_KEX) {
  6140. ssh->kex = alg->u.kex.kex;
  6141. s->warn_kex = alg->u.kex.warn;
  6142. } else if (i == KEXLIST_HOSTKEY) {
  6143. ssh->hostkey = alg->u.hk.hostkey;
  6144. s->warn_hk = alg->u.hk.warn;
  6145. } else if (i == KEXLIST_CSCIPHER) {
  6146. s->cscipher_tobe = alg->u.cipher.cipher;
  6147. s->warn_cscipher = alg->u.cipher.warn;
  6148. } else if (i == KEXLIST_SCCIPHER) {
  6149. s->sccipher_tobe = alg->u.cipher.cipher;
  6150. s->warn_sccipher = alg->u.cipher.warn;
  6151. } else if (i == KEXLIST_CSMAC) {
  6152. s->csmac_tobe = alg->u.mac.mac;
  6153. s->csmac_etm_tobe = alg->u.mac.etm;
  6154. } else if (i == KEXLIST_SCMAC) {
  6155. s->scmac_tobe = alg->u.mac.mac;
  6156. s->scmac_etm_tobe = alg->u.mac.etm;
  6157. } else if (i == KEXLIST_CSCOMP) {
  6158. s->cscomp_tobe = alg->u.comp;
  6159. } else if (i == KEXLIST_SCCOMP) {
  6160. s->sccomp_tobe = alg->u.comp;
  6161. }
  6162. goto matched;
  6163. }
  6164. if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
  6165. in_commasep_string(alg->u.comp->delayed_name, str, len))
  6166. s->pending_compression = TRUE; /* try this later */
  6167. }
  6168. bombout(("Couldn't agree a %s (available: %.*s)",
  6169. kexlist_descr[i], len, str));
  6170. crStopV;
  6171. matched:;
  6172. if (i == KEXLIST_HOSTKEY) {
  6173. int j;
  6174. /*
  6175. * In addition to deciding which host key we're
  6176. * actually going to use, we should make a list of the
  6177. * host keys offered by the server which we _don't_
  6178. * have cached. These will be offered as cross-
  6179. * certification options by ssh_get_specials.
  6180. *
  6181. * We also count the key we're currently using for KEX
  6182. * as one we've already got, because by the time this
  6183. * menu becomes visible, it will be.
  6184. */
  6185. ssh->n_uncert_hostkeys = 0;
  6186. for (j = 0; j < lenof(hostkey_algs); j++) {
  6187. if (hostkey_algs[j].alg != ssh->hostkey &&
  6188. in_commasep_string(hostkey_algs[j].alg->name,
  6189. str, len) &&
  6190. !have_ssh_host_key(
  6191. #ifdef MPEXT
  6192. ssh->frontend,
  6193. #endif
  6194. ssh->savedhost, ssh->savedport,
  6195. hostkey_algs[j].alg->keytype)) {
  6196. ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
  6197. }
  6198. }
  6199. }
  6200. }
  6201. if (s->pending_compression) {
  6202. logevent("Server supports delayed compression; "
  6203. "will try this later");
  6204. }
  6205. ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
  6206. ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
  6207. s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
  6208. ssh->exhash = ssh->kex->hash->init();
  6209. hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
  6210. hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
  6211. hash_string(ssh->kex->hash, ssh->exhash,
  6212. s->our_kexinit, s->our_kexinitlen);
  6213. sfree(s->our_kexinit);
  6214. /* Include the type byte in the hash of server's KEXINIT */
  6215. hash_string(ssh->kex->hash, ssh->exhash,
  6216. pktin->body - 1, pktin->length + 1);
  6217. if (s->warn_kex) {
  6218. ssh_set_frozen(ssh, 1);
  6219. s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
  6220. ssh->kex->name,
  6221. ssh_dialog_callback, ssh);
  6222. if (s->dlgret < 0) {
  6223. do {
  6224. crReturnV;
  6225. if (pktin) {
  6226. bombout(("Unexpected data from server while"
  6227. " waiting for user response"));
  6228. crStopV;
  6229. }
  6230. } while (pktin || inlen > 0);
  6231. s->dlgret = ssh->user_response;
  6232. }
  6233. ssh_set_frozen(ssh, 0);
  6234. if (s->dlgret == 0) {
  6235. ssh_disconnect(ssh, "User aborted at kex warning", NULL,
  6236. 0, TRUE);
  6237. crStopV;
  6238. }
  6239. }
  6240. if (s->warn_hk) {
  6241. int j, k;
  6242. char *betteralgs;
  6243. ssh_set_frozen(ssh, 1);
  6244. /*
  6245. * Change warning box wording depending on why we chose a
  6246. * warning-level host key algorithm. If it's because
  6247. * that's all we have *cached*, use the askhk mechanism,
  6248. * and list the host keys we could usefully cross-certify.
  6249. * Otherwise, use askalg for the standard wording.
  6250. */
  6251. betteralgs = NULL;
  6252. for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
  6253. const struct ssh_signkey_with_user_pref_id *hktype =
  6254. &hostkey_algs[ssh->uncert_hostkeys[j]];
  6255. int better = FALSE;
  6256. for (k = 0; k < HK_MAX; k++) {
  6257. int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
  6258. if (id == HK_WARN) {
  6259. break;
  6260. } else if (id == hktype->id) {
  6261. better = TRUE;
  6262. break;
  6263. }
  6264. }
  6265. if (better) {
  6266. if (betteralgs) {
  6267. char *old_ba = betteralgs;
  6268. betteralgs = dupcat(betteralgs, ",",
  6269. hktype->alg->name,
  6270. (const char *)NULL);
  6271. sfree(old_ba);
  6272. } else {
  6273. betteralgs = dupstr(hktype->alg->name);
  6274. }
  6275. }
  6276. }
  6277. if (betteralgs) {
  6278. s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
  6279. betteralgs, ssh_dialog_callback, ssh);
  6280. sfree(betteralgs);
  6281. } else {
  6282. s->dlgret = askalg(ssh->frontend, "host key type",
  6283. ssh->hostkey->name,
  6284. ssh_dialog_callback, ssh);
  6285. }
  6286. if (s->dlgret < 0) {
  6287. do {
  6288. crReturnV;
  6289. if (pktin) {
  6290. bombout(("Unexpected data from server while"
  6291. " waiting for user response"));
  6292. crStopV;
  6293. }
  6294. } while (pktin || inlen > 0);
  6295. s->dlgret = ssh->user_response;
  6296. }
  6297. ssh_set_frozen(ssh, 0);
  6298. if (s->dlgret == 0) {
  6299. ssh_disconnect(ssh, "User aborted at host key warning", NULL,
  6300. 0, TRUE);
  6301. crStopV;
  6302. }
  6303. }
  6304. if (s->warn_cscipher) {
  6305. ssh_set_frozen(ssh, 1);
  6306. s->dlgret = askalg(ssh->frontend,
  6307. "client-to-server cipher",
  6308. s->cscipher_tobe->name,
  6309. ssh_dialog_callback, ssh);
  6310. if (s->dlgret < 0) {
  6311. do {
  6312. crReturnV;
  6313. if (pktin) {
  6314. bombout(("Unexpected data from server while"
  6315. " waiting for user response"));
  6316. crStopV;
  6317. }
  6318. } while (pktin || inlen > 0);
  6319. s->dlgret = ssh->user_response;
  6320. }
  6321. ssh_set_frozen(ssh, 0);
  6322. if (s->dlgret == 0) {
  6323. ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
  6324. 0, TRUE);
  6325. crStopV;
  6326. }
  6327. }
  6328. if (s->warn_sccipher) {
  6329. ssh_set_frozen(ssh, 1);
  6330. s->dlgret = askalg(ssh->frontend,
  6331. "server-to-client cipher",
  6332. s->sccipher_tobe->name,
  6333. ssh_dialog_callback, ssh);
  6334. if (s->dlgret < 0) {
  6335. do {
  6336. crReturnV;
  6337. if (pktin) {
  6338. bombout(("Unexpected data from server while"
  6339. " waiting for user response"));
  6340. crStopV;
  6341. }
  6342. } while (pktin || inlen > 0);
  6343. s->dlgret = ssh->user_response;
  6344. }
  6345. ssh_set_frozen(ssh, 0);
  6346. if (s->dlgret == 0) {
  6347. ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
  6348. 0, TRUE);
  6349. crStopV;
  6350. }
  6351. }
  6352. if (s->ignorepkt) /* first_kex_packet_follows */
  6353. crWaitUntilV(pktin); /* Ignore packet */
  6354. }
  6355. if (ssh->kex->main_type == KEXTYPE_DH) {
  6356. /*
  6357. * Work out the number of bits of key we will need from the
  6358. * key exchange. We start with the maximum key length of
  6359. * either cipher...
  6360. */
  6361. {
  6362. int csbits, scbits;
  6363. csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
  6364. scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
  6365. s->nbits = (csbits > scbits ? csbits : scbits);
  6366. }
  6367. /* The keys only have hlen-bit entropy, since they're based on
  6368. * a hash. So cap the key size at hlen bits. */
  6369. if (s->nbits > ssh->kex->hash->hlen * 8)
  6370. s->nbits = ssh->kex->hash->hlen * 8;
  6371. /*
  6372. * If we're doing Diffie-Hellman group exchange, start by
  6373. * requesting a group.
  6374. */
  6375. if (dh_is_gex(ssh->kex)) {
  6376. logevent("Doing Diffie-Hellman group exchange");
  6377. ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
  6378. /*
  6379. * Work out how big a DH group we will need to allow that
  6380. * much data.
  6381. */
  6382. s->pbits = 512 << ((s->nbits - 1) / 64);
  6383. if (s->pbits < DH_MIN_SIZE)
  6384. s->pbits = DH_MIN_SIZE;
  6385. if (s->pbits > DH_MAX_SIZE)
  6386. s->pbits = DH_MAX_SIZE;
  6387. if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
  6388. s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
  6389. ssh2_pkt_adduint32(s->pktout, s->pbits);
  6390. } else {
  6391. s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
  6392. ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
  6393. ssh2_pkt_adduint32(s->pktout, s->pbits);
  6394. ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
  6395. }
  6396. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6397. crWaitUntilV(pktin);
  6398. if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
  6399. bombout(("expected key exchange group packet from server"));
  6400. crStopV;
  6401. }
  6402. s->p = ssh2_pkt_getmp(pktin);
  6403. s->g = ssh2_pkt_getmp(pktin);
  6404. if (!s->p || !s->g) {
  6405. bombout(("unable to read mp-ints from incoming group packet"));
  6406. crStopV;
  6407. }
  6408. ssh->kex_ctx = dh_setup_gex(s->p, s->g);
  6409. s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
  6410. s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
  6411. } else {
  6412. ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
  6413. ssh->kex_ctx = dh_setup_group(ssh->kex);
  6414. s->kex_init_value = SSH2_MSG_KEXDH_INIT;
  6415. s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
  6416. logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
  6417. ssh->kex->groupname);
  6418. }
  6419. logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
  6420. ssh->kex->hash->text_name);
  6421. /*
  6422. * Now generate and send e for Diffie-Hellman.
  6423. */
  6424. set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
  6425. s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
  6426. s->pktout = ssh2_pkt_init(s->kex_init_value);
  6427. ssh2_pkt_addmp(s->pktout, s->e);
  6428. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6429. set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
  6430. crWaitUntilV(pktin);
  6431. if (pktin->type != s->kex_reply_value) {
  6432. bombout(("expected key exchange reply packet from server"));
  6433. crStopV;
  6434. }
  6435. set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
  6436. ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
  6437. if (!s->hostkeydata) {
  6438. bombout(("unable to parse key exchange reply packet"));
  6439. crStopV;
  6440. }
  6441. s->hkey = ssh->hostkey->newkey(ssh->hostkey,
  6442. s->hostkeydata, s->hostkeylen);
  6443. s->f = ssh2_pkt_getmp(pktin);
  6444. if (!s->f) {
  6445. bombout(("unable to parse key exchange reply packet"));
  6446. crStopV;
  6447. }
  6448. ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
  6449. if (!s->sigdata) {
  6450. bombout(("unable to parse key exchange reply packet"));
  6451. crStopV;
  6452. }
  6453. {
  6454. const char *err = dh_validate_f(ssh->kex_ctx, s->f);
  6455. if (err) {
  6456. bombout(("key exchange reply failed validation: %s", err));
  6457. crStopV;
  6458. }
  6459. }
  6460. s->K = dh_find_K(ssh->kex_ctx, s->f);
  6461. /* We assume everything from now on will be quick, and it might
  6462. * involve user interaction. */
  6463. set_busy_status(ssh->frontend, BUSY_NOT);
  6464. hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
  6465. if (dh_is_gex(ssh->kex)) {
  6466. if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
  6467. hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
  6468. hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
  6469. if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
  6470. hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
  6471. hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
  6472. hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
  6473. }
  6474. hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
  6475. hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
  6476. dh_cleanup(ssh->kex_ctx);
  6477. freebn(s->f);
  6478. if (dh_is_gex(ssh->kex)) {
  6479. freebn(s->g);
  6480. freebn(s->p);
  6481. }
  6482. } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
  6483. logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
  6484. ssh_ecdhkex_curve_textname(ssh->kex),
  6485. ssh->kex->hash->text_name);
  6486. ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
  6487. s->eckey = ssh_ecdhkex_newkey(ssh->kex);
  6488. if (!s->eckey) {
  6489. bombout(("Unable to generate key for ECDH"));
  6490. crStopV;
  6491. }
  6492. {
  6493. char *publicPoint;
  6494. int publicPointLength;
  6495. publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
  6496. if (!publicPoint) {
  6497. ssh_ecdhkex_freekey(s->eckey);
  6498. bombout(("Unable to encode public key for ECDH"));
  6499. crStopV;
  6500. }
  6501. s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
  6502. ssh2_pkt_addstring_start(s->pktout);
  6503. ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
  6504. sfree(publicPoint);
  6505. }
  6506. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6507. crWaitUntilV(pktin);
  6508. if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
  6509. ssh_ecdhkex_freekey(s->eckey);
  6510. bombout(("expected ECDH reply packet from server"));
  6511. crStopV;
  6512. }
  6513. ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
  6514. if (!s->hostkeydata) {
  6515. bombout(("unable to parse ECDH reply packet"));
  6516. crStopV;
  6517. }
  6518. hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
  6519. s->hkey = ssh->hostkey->newkey(ssh->hostkey,
  6520. s->hostkeydata, s->hostkeylen);
  6521. {
  6522. char *publicPoint;
  6523. int publicPointLength;
  6524. publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
  6525. if (!publicPoint) {
  6526. ssh_ecdhkex_freekey(s->eckey);
  6527. bombout(("Unable to encode public key for ECDH hash"));
  6528. crStopV;
  6529. }
  6530. hash_string(ssh->kex->hash, ssh->exhash,
  6531. publicPoint, publicPointLength);
  6532. sfree(publicPoint);
  6533. }
  6534. {
  6535. char *keydata;
  6536. int keylen;
  6537. ssh_pkt_getstring(pktin, &keydata, &keylen);
  6538. if (!keydata) {
  6539. bombout(("unable to parse ECDH reply packet"));
  6540. crStopV;
  6541. }
  6542. hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
  6543. s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
  6544. if (!s->K) {
  6545. ssh_ecdhkex_freekey(s->eckey);
  6546. bombout(("point received in ECDH was not valid"));
  6547. crStopV;
  6548. }
  6549. }
  6550. ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
  6551. if (!s->sigdata) {
  6552. bombout(("unable to parse key exchange reply packet"));
  6553. crStopV;
  6554. }
  6555. ssh_ecdhkex_freekey(s->eckey);
  6556. } else {
  6557. logeventf(ssh, "Doing RSA key exchange with hash %s",
  6558. ssh->kex->hash->text_name);
  6559. ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
  6560. /*
  6561. * RSA key exchange. First expect a KEXRSA_PUBKEY packet
  6562. * from the server.
  6563. */
  6564. crWaitUntilV(pktin);
  6565. if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
  6566. bombout(("expected RSA public key packet from server"));
  6567. crStopV;
  6568. }
  6569. ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
  6570. if (!s->hostkeydata) {
  6571. bombout(("unable to parse RSA public key packet"));
  6572. crStopV;
  6573. }
  6574. hash_string(ssh->kex->hash, ssh->exhash,
  6575. s->hostkeydata, s->hostkeylen);
  6576. s->hkey = ssh->hostkey->newkey(ssh->hostkey,
  6577. s->hostkeydata, s->hostkeylen);
  6578. {
  6579. char *keydata;
  6580. ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
  6581. if (!keydata) {
  6582. bombout(("unable to parse RSA public key packet"));
  6583. crStopV;
  6584. }
  6585. s->rsakeydata = snewn(s->rsakeylen, char);
  6586. memcpy(s->rsakeydata, keydata, s->rsakeylen);
  6587. }
  6588. s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
  6589. if (!s->rsakey) {
  6590. sfree(s->rsakeydata);
  6591. bombout(("unable to parse RSA public key from server"));
  6592. crStopV;
  6593. }
  6594. hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
  6595. /*
  6596. * Next, set up a shared secret K, of precisely KLEN -
  6597. * 2*HLEN - 49 bits, where KLEN is the bit length of the
  6598. * RSA key modulus and HLEN is the bit length of the hash
  6599. * we're using.
  6600. */
  6601. {
  6602. int klen = ssh_rsakex_klen(s->rsakey);
  6603. int nbits;
  6604. int i, byte = 0;
  6605. unsigned char *kstr1, *kstr2, *outstr;
  6606. int kstr1len, kstr2len, outstrlen;
  6607. const struct ssh_rsa_kex_extra *extra =
  6608. (const struct ssh_rsa_kex_extra *)ssh->kex->extra;
  6609. if (klen < extra->minklen) {
  6610. bombout(("Server sent RSA key with less bits than the minimum size for key exchange"));
  6611. crStopV;
  6612. }
  6613. nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
  6614. s->K = bn_power_2(nbits - 1);
  6615. for (i = 0; i < nbits; i++) {
  6616. if ((i & 7) == 0) {
  6617. byte = random_byte();
  6618. }
  6619. bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
  6620. }
  6621. /*
  6622. * Encode this as an mpint.
  6623. */
  6624. kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
  6625. kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
  6626. PUT_32BIT(kstr2, kstr1len);
  6627. memcpy(kstr2 + 4, kstr1, kstr1len);
  6628. /*
  6629. * Encrypt it with the given RSA key.
  6630. */
  6631. outstrlen = (klen + 7) / 8;
  6632. outstr = snewn(outstrlen, unsigned char);
  6633. ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
  6634. outstr, outstrlen, s->rsakey);
  6635. /*
  6636. * And send it off in a return packet.
  6637. */
  6638. s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
  6639. ssh2_pkt_addstring_start(s->pktout);
  6640. ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
  6641. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6642. hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
  6643. sfree(kstr2);
  6644. sfree(kstr1);
  6645. sfree(outstr);
  6646. }
  6647. ssh_rsakex_freekey(s->rsakey);
  6648. crWaitUntilV(pktin);
  6649. if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
  6650. sfree(s->rsakeydata);
  6651. bombout(("expected signature packet from server"));
  6652. crStopV;
  6653. }
  6654. ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
  6655. if (!s->sigdata) {
  6656. bombout(("unable to parse signature packet"));
  6657. crStopV;
  6658. }
  6659. sfree(s->rsakeydata);
  6660. }
  6661. hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
  6662. assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
  6663. ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
  6664. ssh->kex_ctx = NULL;
  6665. #if 0
  6666. debug(("Exchange hash is:\n"));
  6667. dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
  6668. #endif
  6669. if (!s->hkey) {
  6670. bombout(("Server's host key is invalid"));
  6671. crStopV;
  6672. }
  6673. if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
  6674. (char *)s->exchange_hash,
  6675. ssh->kex->hash->hlen)) {
  6676. #ifndef FUZZING
  6677. bombout(("Server's host key did not match the signature supplied"));
  6678. crStopV;
  6679. #endif
  6680. }
  6681. s->keystr = ssh->hostkey->fmtkey(s->hkey);
  6682. if (!s->got_session_id) {
  6683. /*
  6684. * Make a note of any other host key formats that are available.
  6685. */
  6686. {
  6687. int i, j, nkeys = 0;
  6688. char *list = NULL;
  6689. for (i = 0; i < lenof(hostkey_algs); i++) {
  6690. if (hostkey_algs[i].alg == ssh->hostkey)
  6691. continue;
  6692. for (j = 0; j < ssh->n_uncert_hostkeys; j++)
  6693. if (ssh->uncert_hostkeys[j] == i)
  6694. break;
  6695. if (j < ssh->n_uncert_hostkeys) {
  6696. char *newlist;
  6697. if (list)
  6698. newlist = dupprintf("%s/%s", list,
  6699. hostkey_algs[i].alg->name);
  6700. else
  6701. newlist = dupprintf("%s", hostkey_algs[i].alg->name);
  6702. sfree(list);
  6703. list = newlist;
  6704. nkeys++;
  6705. }
  6706. }
  6707. if (list) {
  6708. logeventf(ssh,
  6709. "Server also has %s host key%s, but we "
  6710. "don't know %s", list,
  6711. nkeys > 1 ? "s" : "",
  6712. nkeys > 1 ? "any of them" : "it");
  6713. sfree(list);
  6714. }
  6715. }
  6716. /*
  6717. * Authenticate remote host: verify host key. (We've already
  6718. * checked the signature of the exchange hash.)
  6719. */
  6720. s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
  6721. logevent("Host key fingerprint is:");
  6722. logevent(s->fingerprint);
  6723. /* First check against manually configured host keys. */
  6724. s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
  6725. ssh->hostkey, s->hkey);
  6726. if (s->dlgret == 0) { /* did not match */
  6727. bombout(("Host key did not appear in manually configured list"));
  6728. crStopV;
  6729. } else if (s->dlgret < 0) { /* none configured; use standard handling */
  6730. ssh_set_frozen(ssh, 1);
  6731. s->dlgret = verify_ssh_host_key(ssh->frontend,
  6732. ssh->savedhost, ssh->savedport,
  6733. ssh->hostkey->keytype, s->keystr,
  6734. s->fingerprint,
  6735. ssh_dialog_callback, ssh);
  6736. #ifdef FUZZING
  6737. s->dlgret = 1;
  6738. #endif
  6739. if (s->dlgret < 0) {
  6740. do {
  6741. crReturnV;
  6742. if (pktin) {
  6743. bombout(("Unexpected data from server while waiting"
  6744. " for user host key response"));
  6745. crStopV;
  6746. }
  6747. } while (pktin || inlen > 0);
  6748. s->dlgret = ssh->user_response;
  6749. }
  6750. ssh_set_frozen(ssh, 0);
  6751. if (s->dlgret == 0) {
  6752. ssh_disconnect(ssh, "Aborted at host key verification", NULL,
  6753. 0, TRUE);
  6754. crStopV;
  6755. }
  6756. }
  6757. sfree(s->fingerprint);
  6758. /*
  6759. * Save this host key, to check against the one presented in
  6760. * subsequent rekeys.
  6761. */
  6762. ssh->hostkey_str = s->keystr;
  6763. } else if (ssh->cross_certifying) {
  6764. s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
  6765. logevent("Storing additional host key for this host:");
  6766. logevent(s->fingerprint);
  6767. sfree(s->fingerprint);
  6768. store_host_key(ssh->savedhost, ssh->savedport,
  6769. ssh->hostkey->keytype, s->keystr);
  6770. ssh->cross_certifying = FALSE;
  6771. /*
  6772. * Don't forget to store the new key as the one we'll be
  6773. * re-checking in future normal rekeys.
  6774. */
  6775. ssh->hostkey_str = s->keystr;
  6776. } else {
  6777. /*
  6778. * In a rekey, we never present an interactive host key
  6779. * verification request to the user. Instead, we simply
  6780. * enforce that the key we're seeing this time is identical to
  6781. * the one we saw before.
  6782. */
  6783. if (strcmp(ssh->hostkey_str, s->keystr)) {
  6784. #ifndef FUZZING
  6785. bombout(("Host key was different in repeat key exchange"));
  6786. crStopV;
  6787. #endif
  6788. }
  6789. sfree(s->keystr);
  6790. }
  6791. ssh->hostkey->freekey(s->hkey);
  6792. /*
  6793. * The exchange hash from the very first key exchange is also
  6794. * the session id, used in session key construction and
  6795. * authentication.
  6796. */
  6797. if (!s->got_session_id) {
  6798. assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
  6799. memcpy(ssh->v2_session_id, s->exchange_hash,
  6800. sizeof(s->exchange_hash));
  6801. ssh->v2_session_id_len = ssh->kex->hash->hlen;
  6802. assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
  6803. s->got_session_id = TRUE;
  6804. }
  6805. /*
  6806. * Send SSH2_MSG_NEWKEYS.
  6807. */
  6808. s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
  6809. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6810. ssh->outgoing_data_size = 0; /* start counting from here */
  6811. /*
  6812. * We've sent client NEWKEYS, so create and initialise
  6813. * client-to-server session keys.
  6814. */
  6815. if (ssh->cs_cipher_ctx)
  6816. ssh->cscipher->free_context(ssh->cs_cipher_ctx);
  6817. ssh->cscipher = s->cscipher_tobe;
  6818. if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
  6819. if (ssh->cs_mac_ctx)
  6820. ssh->csmac->free_context(ssh->cs_mac_ctx);
  6821. ssh->csmac = s->csmac_tobe;
  6822. ssh->csmac_etm = s->csmac_etm_tobe;
  6823. if (ssh->csmac)
  6824. ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
  6825. if (ssh->cs_comp_ctx)
  6826. ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
  6827. ssh->cscomp = s->cscomp_tobe;
  6828. ssh->cs_comp_ctx = ssh->cscomp->compress_init();
  6829. /*
  6830. * Set IVs on client-to-server keys. Here we use the exchange
  6831. * hash from the _first_ key exchange.
  6832. */
  6833. if (ssh->cscipher) {
  6834. unsigned char *key;
  6835. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
  6836. ssh->cscipher->padded_keybytes);
  6837. ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
  6838. smemclr(key, ssh->cscipher->padded_keybytes);
  6839. sfree(key);
  6840. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
  6841. ssh->cscipher->blksize);
  6842. ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
  6843. smemclr(key, ssh->cscipher->blksize);
  6844. sfree(key);
  6845. }
  6846. if (ssh->csmac) {
  6847. unsigned char *key;
  6848. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
  6849. ssh->csmac->keylen);
  6850. ssh->csmac->setkey(ssh->cs_mac_ctx, key);
  6851. smemclr(key, ssh->csmac->keylen);
  6852. sfree(key);
  6853. }
  6854. if (ssh->cscipher)
  6855. logeventf(ssh, "Initialised %.200s client->server encryption",
  6856. ssh->cscipher->text_name);
  6857. if (ssh->csmac)
  6858. logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
  6859. ssh->csmac->text_name,
  6860. ssh->csmac_etm ? " (in ETM mode)" : "",
  6861. ssh->cscipher->required_mac ? " (required by cipher)" : "");
  6862. if (ssh->cscomp->text_name)
  6863. logeventf(ssh, "Initialised %s compression",
  6864. ssh->cscomp->text_name);
  6865. /*
  6866. * Now our end of the key exchange is complete, we can send all
  6867. * our queued higher-layer packets.
  6868. */
  6869. ssh->queueing = FALSE;
  6870. ssh2_pkt_queuesend(ssh);
  6871. /*
  6872. * Expect SSH2_MSG_NEWKEYS from server.
  6873. */
  6874. crWaitUntilV(pktin);
  6875. if (pktin->type != SSH2_MSG_NEWKEYS) {
  6876. bombout(("expected new-keys packet from server"));
  6877. crStopV;
  6878. }
  6879. ssh->incoming_data_size = 0; /* start counting from here */
  6880. /*
  6881. * We've seen server NEWKEYS, so create and initialise
  6882. * server-to-client session keys.
  6883. */
  6884. if (ssh->sc_cipher_ctx)
  6885. ssh->sccipher->free_context(ssh->sc_cipher_ctx);
  6886. if (s->sccipher_tobe) {
  6887. ssh->sccipher = s->sccipher_tobe;
  6888. ssh->sc_cipher_ctx = ssh->sccipher->make_context();
  6889. }
  6890. if (ssh->sc_mac_ctx)
  6891. ssh->scmac->free_context(ssh->sc_mac_ctx);
  6892. if (s->scmac_tobe) {
  6893. ssh->scmac = s->scmac_tobe;
  6894. ssh->scmac_etm = s->scmac_etm_tobe;
  6895. ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
  6896. }
  6897. if (ssh->sc_comp_ctx)
  6898. ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
  6899. ssh->sccomp = s->sccomp_tobe;
  6900. ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
  6901. /*
  6902. * Set IVs on server-to-client keys. Here we use the exchange
  6903. * hash from the _first_ key exchange.
  6904. */
  6905. if (ssh->sccipher) {
  6906. unsigned char *key;
  6907. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
  6908. ssh->sccipher->padded_keybytes);
  6909. ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
  6910. smemclr(key, ssh->sccipher->padded_keybytes);
  6911. sfree(key);
  6912. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
  6913. ssh->sccipher->blksize);
  6914. ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
  6915. smemclr(key, ssh->sccipher->blksize);
  6916. sfree(key);
  6917. }
  6918. if (ssh->scmac) {
  6919. unsigned char *key;
  6920. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
  6921. ssh->scmac->keylen);
  6922. ssh->scmac->setkey(ssh->sc_mac_ctx, key);
  6923. smemclr(key, ssh->scmac->keylen);
  6924. sfree(key);
  6925. }
  6926. if (ssh->sccipher)
  6927. logeventf(ssh, "Initialised %.200s server->client encryption",
  6928. ssh->sccipher->text_name);
  6929. if (ssh->scmac)
  6930. logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
  6931. ssh->scmac->text_name,
  6932. ssh->scmac_etm ? " (in ETM mode)" : "",
  6933. ssh->sccipher->required_mac ? " (required by cipher)" : "");
  6934. if (ssh->sccomp->text_name)
  6935. logeventf(ssh, "Initialised %s decompression",
  6936. ssh->sccomp->text_name);
  6937. /*
  6938. * Free shared secret.
  6939. */
  6940. freebn(s->K);
  6941. /*
  6942. * Update the specials menu to list the remaining uncertified host
  6943. * keys.
  6944. */
  6945. update_specials_menu(ssh->frontend);
  6946. /*
  6947. * Key exchange is over. Loop straight back round if we have a
  6948. * deferred rekey reason.
  6949. */
  6950. if (ssh->deferred_rekey_reason) {
  6951. logevent(ssh->deferred_rekey_reason);
  6952. pktin = NULL;
  6953. ssh->deferred_rekey_reason = NULL;
  6954. goto begin_key_exchange;
  6955. }
  6956. /*
  6957. * Otherwise, schedule a timer for our next rekey.
  6958. */
  6959. ssh->kex_in_progress = FALSE;
  6960. ssh->last_rekey = GETTICKCOUNT();
  6961. if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
  6962. ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
  6963. ssh2_timer, ssh);
  6964. /*
  6965. * Now we're encrypting. Begin returning 1 to the protocol main
  6966. * function so that other things can run on top of the
  6967. * transport. If we ever see a KEXINIT, we must go back to the
  6968. * start.
  6969. *
  6970. * We _also_ go back to the start if we see pktin==NULL and
  6971. * inlen negative, because this is a special signal meaning
  6972. * `initiate client-driven rekey', and `in' contains a message
  6973. * giving the reason for the rekey.
  6974. *
  6975. * inlen==-1 means always initiate a rekey;
  6976. * inlen==-2 means that userauth has completed successfully and
  6977. * we should consider rekeying (for delayed compression).
  6978. */
  6979. while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
  6980. (!pktin && inlen < 0))) {
  6981. wait_for_rekey:
  6982. if (!ssh->protocol_initial_phase_done) {
  6983. ssh->protocol_initial_phase_done = TRUE;
  6984. /*
  6985. * Allow authconn to initialise itself.
  6986. */
  6987. do_ssh2_authconn(ssh, NULL, 0, NULL);
  6988. }
  6989. crReturnV;
  6990. }
  6991. if (pktin) {
  6992. logevent("Server initiated key re-exchange");
  6993. } else {
  6994. if (inlen == -2) {
  6995. /*
  6996. * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
  6997. * delayed compression, if it's available.
  6998. *
  6999. * draft-miller-secsh-compression-delayed-00 says that you
  7000. * negotiate delayed compression in the first key exchange, and
  7001. * both sides start compressing when the server has sent
  7002. * USERAUTH_SUCCESS. This has a race condition -- the server
  7003. * can't know when the client has seen it, and thus which incoming
  7004. * packets it should treat as compressed.
  7005. *
  7006. * Instead, we do the initial key exchange without offering the
  7007. * delayed methods, but note if the server offers them; when we
  7008. * get here, if a delayed method was available that was higher
  7009. * on our list than what we got, we initiate a rekey in which we
  7010. * _do_ list the delayed methods (and hopefully get it as a
  7011. * result). Subsequent rekeys will do the same.
  7012. */
  7013. assert(!s->userauth_succeeded); /* should only happen once */
  7014. s->userauth_succeeded = TRUE;
  7015. if (!s->pending_compression)
  7016. /* Can't see any point rekeying. */
  7017. goto wait_for_rekey; /* this is utterly horrid */
  7018. /* else fall through to rekey... */
  7019. s->pending_compression = FALSE;
  7020. }
  7021. /*
  7022. * Now we've decided to rekey.
  7023. *
  7024. * Special case: if the server bug is set that doesn't
  7025. * allow rekeying, we give a different log message and
  7026. * continue waiting. (If such a server _initiates_ a rekey,
  7027. * we process it anyway!)
  7028. */
  7029. if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
  7030. logeventf(ssh, "Server bug prevents key re-exchange (%s)",
  7031. (char *)in);
  7032. /* Reset the counters, so that at least this message doesn't
  7033. * hit the event log _too_ often. */
  7034. ssh->outgoing_data_size = 0;
  7035. ssh->incoming_data_size = 0;
  7036. if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
  7037. ssh->next_rekey =
  7038. schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
  7039. ssh2_timer, ssh);
  7040. }
  7041. goto wait_for_rekey; /* this is still utterly horrid */
  7042. } else {
  7043. logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
  7044. }
  7045. }
  7046. goto begin_key_exchange;
  7047. crFinishV;
  7048. }
  7049. /*
  7050. * Send data on an SSH channel. In SSH-2, this involves buffering it
  7051. * first.
  7052. */
  7053. static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
  7054. int len)
  7055. {
  7056. if (c->ssh->version == 2) {
  7057. bufchain_add(&c->v.v2.outbuffer, buf, len);
  7058. return ssh2_try_send(c);
  7059. } else {
  7060. send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
  7061. PKT_INT, c->remoteid,
  7062. PKT_INT, len,
  7063. PKT_DATA, buf, len,
  7064. PKT_END);
  7065. /*
  7066. * In SSH-1 we can return 0 here - implying that channels are
  7067. * never individually throttled - because the only
  7068. * circumstance that can cause throttling will be the whole
  7069. * SSH connection backing up, in which case _everything_ will
  7070. * be throttled as a whole.
  7071. */
  7072. return 0;
  7073. }
  7074. }
  7075. /*
  7076. * Attempt to send data on an SSH-2 channel.
  7077. */
  7078. static int ssh2_try_send(struct ssh_channel *c)
  7079. {
  7080. Ssh ssh = c->ssh;
  7081. struct Packet *pktout;
  7082. int ret;
  7083. while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
  7084. int len;
  7085. void *data;
  7086. bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
  7087. if ((unsigned)len > c->v.v2.remwindow)
  7088. len = c->v.v2.remwindow;
  7089. if ((unsigned)len > c->v.v2.remmaxpkt)
  7090. len = c->v.v2.remmaxpkt;
  7091. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
  7092. ssh2_pkt_adduint32(pktout, c->remoteid);
  7093. ssh2_pkt_addstring_start(pktout);
  7094. ssh2_pkt_addstring_data(pktout, data, len);
  7095. ssh2_pkt_send(ssh, pktout);
  7096. bufchain_consume(&c->v.v2.outbuffer, len);
  7097. c->v.v2.remwindow -= len;
  7098. }
  7099. /*
  7100. * After having sent as much data as we can, return the amount
  7101. * still buffered.
  7102. */
  7103. ret = bufchain_size(&c->v.v2.outbuffer);
  7104. /*
  7105. * And if there's no data pending but we need to send an EOF, send
  7106. * it.
  7107. */
  7108. if (!ret && c->pending_eof)
  7109. ssh_channel_try_eof(c);
  7110. return ret;
  7111. }
  7112. static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
  7113. {
  7114. int bufsize;
  7115. if (c->closes & CLOSES_SENT_EOF)
  7116. return; /* don't send on channels we've EOFed */
  7117. bufsize = ssh2_try_send(c);
  7118. if (bufsize == 0) {
  7119. switch (c->type) {
  7120. case CHAN_MAINSESSION:
  7121. /* stdin need not receive an unthrottle
  7122. * notification since it will be polled */
  7123. break;
  7124. case CHAN_X11:
  7125. x11_unthrottle(c->u.x11.xconn);
  7126. break;
  7127. case CHAN_AGENT:
  7128. /* Now that we've successfully sent all the outgoing
  7129. * replies we had, try to process more incoming data. */
  7130. ssh_agentf_try_forward(c);
  7131. break;
  7132. case CHAN_SOCKDATA:
  7133. pfd_unthrottle(c->u.pfd.pf);
  7134. break;
  7135. }
  7136. }
  7137. }
  7138. static int ssh_is_simple(Ssh ssh)
  7139. {
  7140. /*
  7141. * We use the 'simple' variant of the SSH protocol if we're asked
  7142. * to, except not if we're also doing connection-sharing (either
  7143. * tunnelling our packets over an upstream or expecting to be
  7144. * tunnelled over ourselves), since then the assumption that we
  7145. * have only one channel to worry about is not true after all.
  7146. */
  7147. return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
  7148. !ssh->bare_connection && !ssh->connshare);
  7149. }
  7150. /*
  7151. * Set up most of a new ssh_channel.
  7152. */
  7153. static void ssh_channel_init(struct ssh_channel *c)
  7154. {
  7155. Ssh ssh = c->ssh;
  7156. c->localid = alloc_channel_id(ssh);
  7157. c->closes = 0;
  7158. c->pending_eof = FALSE;
  7159. c->throttling_conn = FALSE;
  7160. if (ssh->version == 2) {
  7161. c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
  7162. ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
  7163. c->v.v2.chanreq_head = NULL;
  7164. c->v.v2.throttle_state = UNTHROTTLED;
  7165. bufchain_init(&c->v.v2.outbuffer);
  7166. }
  7167. add234(ssh->channels, c);
  7168. }
  7169. /*
  7170. * Construct the common parts of a CHANNEL_OPEN.
  7171. */
  7172. static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
  7173. const char *type)
  7174. {
  7175. struct Packet *pktout;
  7176. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
  7177. ssh2_pkt_addstring(pktout, type);
  7178. ssh2_pkt_adduint32(pktout, c->localid);
  7179. ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
  7180. ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
  7181. return pktout;
  7182. }
  7183. /*
  7184. * CHANNEL_FAILURE doesn't come with any indication of what message
  7185. * caused it, so we have to keep track of the outstanding
  7186. * CHANNEL_REQUESTs ourselves.
  7187. */
  7188. static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
  7189. cchandler_fn_t handler, void *ctx)
  7190. {
  7191. struct outstanding_channel_request *ocr =
  7192. snew(struct outstanding_channel_request);
  7193. assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
  7194. ocr->handler = handler;
  7195. ocr->ctx = ctx;
  7196. ocr->next = NULL;
  7197. if (!c->v.v2.chanreq_head)
  7198. c->v.v2.chanreq_head = ocr;
  7199. else
  7200. c->v.v2.chanreq_tail->next = ocr;
  7201. c->v.v2.chanreq_tail = ocr;
  7202. }
  7203. /*
  7204. * Construct the common parts of a CHANNEL_REQUEST. If handler is not
  7205. * NULL then a reply will be requested and the handler will be called
  7206. * when it arrives. The returned packet is ready to have any
  7207. * request-specific data added and be sent. Note that if a handler is
  7208. * provided, it's essential that the request actually be sent.
  7209. *
  7210. * The handler will usually be passed the response packet in pktin. If
  7211. * pktin is NULL, this means that no reply will ever be forthcoming
  7212. * (e.g. because the entire connection is being destroyed, or because
  7213. * the server initiated channel closure before we saw the response)
  7214. * and the handler should free any storage it's holding.
  7215. */
  7216. static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
  7217. const char *type,
  7218. cchandler_fn_t handler, void *ctx)
  7219. {
  7220. struct Packet *pktout;
  7221. assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
  7222. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
  7223. ssh2_pkt_adduint32(pktout, c->remoteid);
  7224. ssh2_pkt_addstring(pktout, type);
  7225. ssh2_pkt_addbool(pktout, handler != NULL);
  7226. if (handler != NULL)
  7227. ssh2_queue_chanreq_handler(c, handler, ctx);
  7228. return pktout;
  7229. }
  7230. static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
  7231. {
  7232. Ssh ssh = c->ssh;
  7233. int buflimit;
  7234. if (ssh->version == 1) {
  7235. buflimit = SSH1_BUFFER_LIMIT;
  7236. } else {
  7237. if (ssh_is_simple(ssh))
  7238. buflimit = 0;
  7239. else
  7240. buflimit = c->v.v2.locmaxwin;
  7241. if (bufsize < buflimit)
  7242. ssh2_set_window(c, buflimit - bufsize);
  7243. }
  7244. if (c->throttling_conn && bufsize <= buflimit) {
  7245. c->throttling_conn = 0;
  7246. ssh_throttle_conn(ssh, -1);
  7247. }
  7248. }
  7249. /*
  7250. * Potentially enlarge the window on an SSH-2 channel.
  7251. */
  7252. static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
  7253. void *);
  7254. static void ssh2_set_window(struct ssh_channel *c, int newwin)
  7255. {
  7256. Ssh ssh = c->ssh;
  7257. /*
  7258. * Never send WINDOW_ADJUST for a channel that the remote side has
  7259. * already sent EOF on; there's no point, since it won't be
  7260. * sending any more data anyway. Ditto if _we've_ already sent
  7261. * CLOSE.
  7262. */
  7263. if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
  7264. return;
  7265. /*
  7266. * Also, never widen the window for an X11 channel when we're
  7267. * still waiting to see its initial auth and may yet hand it off
  7268. * to a downstream.
  7269. */
  7270. if (c->type == CHAN_X11 && c->u.x11.initial)
  7271. return;
  7272. /*
  7273. * If the remote end has a habit of ignoring maxpkt, limit the
  7274. * window so that it has no choice (assuming it doesn't ignore the
  7275. * window as well).
  7276. */
  7277. if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
  7278. newwin = OUR_V2_MAXPKT;
  7279. /*
  7280. * Only send a WINDOW_ADJUST if there's significantly more window
  7281. * available than the other end thinks there is. This saves us
  7282. * sending a WINDOW_ADJUST for every character in a shell session.
  7283. *
  7284. * "Significant" is arbitrarily defined as half the window size.
  7285. */
  7286. if (newwin / 2 >= c->v.v2.locwindow) {
  7287. struct Packet *pktout;
  7288. unsigned *up;
  7289. /*
  7290. * In order to keep track of how much window the client
  7291. * actually has available, we'd like it to acknowledge each
  7292. * WINDOW_ADJUST. We can't do that directly, so we accompany
  7293. * it with a CHANNEL_REQUEST that has to be acknowledged.
  7294. *
  7295. * This is only necessary if we're opening the window wide.
  7296. * If we're not, then throughput is being constrained by
  7297. * something other than the maximum window size anyway.
  7298. */
  7299. if (newwin == c->v.v2.locmaxwin &&
  7300. !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
  7301. up = snew(unsigned);
  7302. *up = newwin - c->v.v2.locwindow;
  7303. pktout = ssh2_chanreq_init(c, "[email protected]",
  7304. ssh2_handle_winadj_response, up);
  7305. ssh2_pkt_send(ssh, pktout);
  7306. if (c->v.v2.throttle_state != UNTHROTTLED)
  7307. c->v.v2.throttle_state = UNTHROTTLING;
  7308. } else {
  7309. /* Pretend the WINDOW_ADJUST was acked immediately. */
  7310. c->v.v2.remlocwin = newwin;
  7311. c->v.v2.throttle_state = THROTTLED;
  7312. }
  7313. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  7314. ssh2_pkt_adduint32(pktout, c->remoteid);
  7315. ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
  7316. ssh2_pkt_send(ssh, pktout);
  7317. c->v.v2.locwindow = newwin;
  7318. }
  7319. }
  7320. /*
  7321. * Find the channel associated with a message. If there's no channel,
  7322. * or it's not properly open, make a noise about it and return NULL.
  7323. * If the channel is shared, pass the message on to downstream and
  7324. * also return NULL (meaning the caller should ignore this message).
  7325. */
  7326. static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin)
  7327. {
  7328. unsigned localid = ssh_pkt_getuint32(pktin);
  7329. struct ssh_channel *c;
  7330. int halfopen_ok;
  7331. /* Is this message OK on a half-open connection? */
  7332. if (ssh->version == 1)
  7333. halfopen_ok = (pktin->type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION ||
  7334. pktin->type == SSH1_MSG_CHANNEL_OPEN_FAILURE);
  7335. else
  7336. halfopen_ok = (pktin->type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION ||
  7337. pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE);
  7338. c = find234(ssh->channels, &localid, ssh_channelfind);
  7339. if (!c || (c->type != CHAN_SHARING && (c->halfopen != halfopen_ok))) {
  7340. char *buf = dupprintf("Received %s for %s channel %u",
  7341. ssh_pkt_type(ssh, pktin->type),
  7342. !c ? "nonexistent" :
  7343. c->halfopen ? "half-open" : "open",
  7344. localid);
  7345. ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
  7346. sfree(buf);
  7347. return NULL;
  7348. }
  7349. if (c->type == CHAN_SHARING) {
  7350. share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
  7351. pktin->body, pktin->length);
  7352. return NULL;
  7353. }
  7354. return c;
  7355. }
  7356. static void ssh2_handle_winadj_response(struct ssh_channel *c,
  7357. struct Packet *pktin, void *ctx)
  7358. {
  7359. unsigned *sizep = ctx;
  7360. /*
  7361. * Winadj responses should always be failures. However, at least
  7362. * one server ("boks_sshd") is known to return SUCCESS for channel
  7363. * requests it's never heard of, such as "winadj@putty". Raised
  7364. * with foxt.com as bug 090916-090424, but for the sake of a quiet
  7365. * life, we don't worry about what kind of response we got.
  7366. */
  7367. c->v.v2.remlocwin += *sizep;
  7368. sfree(sizep);
  7369. /*
  7370. * winadj messages are only sent when the window is fully open, so
  7371. * if we get an ack of one, we know any pending unthrottle is
  7372. * complete.
  7373. */
  7374. if (c->v.v2.throttle_state == UNTHROTTLING)
  7375. c->v.v2.throttle_state = UNTHROTTLED;
  7376. }
  7377. static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
  7378. {
  7379. struct ssh_channel *c = ssh_channel_msg(ssh, pktin);
  7380. struct outstanding_channel_request *ocr;
  7381. if (!c) return;
  7382. ocr = c->v.v2.chanreq_head;
  7383. if (!ocr) {
  7384. ssh2_msg_unexpected(ssh, pktin);
  7385. return;
  7386. }
  7387. ocr->handler(c, pktin, ocr->ctx);
  7388. c->v.v2.chanreq_head = ocr->next;
  7389. sfree(ocr);
  7390. /*
  7391. * We may now initiate channel-closing procedures, if that
  7392. * CHANNEL_REQUEST was the last thing outstanding before we send
  7393. * CHANNEL_CLOSE.
  7394. */
  7395. ssh2_channel_check_close(c);
  7396. }
  7397. static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
  7398. {
  7399. struct ssh_channel *c;
  7400. c = ssh_channel_msg(ssh, pktin);
  7401. if (!c)
  7402. return;
  7403. if (!(c->closes & CLOSES_SENT_EOF)) {
  7404. c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
  7405. ssh2_try_send_and_unthrottle(ssh, c);
  7406. }
  7407. }
  7408. static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
  7409. {
  7410. char *data;
  7411. int length;
  7412. unsigned ext_type = 0; /* 0 means not extended */
  7413. struct ssh_channel *c;
  7414. c = ssh_channel_msg(ssh, pktin);
  7415. if (!c)
  7416. return;
  7417. if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
  7418. ext_type = ssh_pkt_getuint32(pktin);
  7419. ssh_pkt_getstring(pktin, &data, &length);
  7420. if (data) {
  7421. int bufsize;
  7422. c->v.v2.locwindow -= length;
  7423. c->v.v2.remlocwin -= length;
  7424. if (ext_type != 0 && ext_type != SSH2_EXTENDED_DATA_STDERR)
  7425. length = 0; /* Don't do anything with unknown extended data. */
  7426. bufsize = ssh_channel_data(c, ext_type == SSH2_EXTENDED_DATA_STDERR,
  7427. data, length);
  7428. /*
  7429. * If it looks like the remote end hit the end of its window,
  7430. * and we didn't want it to do that, think about using a
  7431. * larger window.
  7432. */
  7433. if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
  7434. c->v.v2.locmaxwin < 0x40000000)
  7435. c->v.v2.locmaxwin += OUR_V2_WINSIZE;
  7436. /*
  7437. * If we are not buffering too much data,
  7438. * enlarge the window again at the remote side.
  7439. * If we are buffering too much, we may still
  7440. * need to adjust the window if the server's
  7441. * sent excess data.
  7442. */
  7443. if (bufsize < c->v.v2.locmaxwin)
  7444. ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
  7445. /*
  7446. * If we're either buffering way too much data, or if we're
  7447. * buffering anything at all and we're in "simple" mode,
  7448. * throttle the whole channel.
  7449. */
  7450. if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
  7451. && !c->throttling_conn) {
  7452. c->throttling_conn = 1;
  7453. ssh_throttle_conn(ssh, +1);
  7454. }
  7455. }
  7456. }
  7457. static void ssh_check_termination(Ssh ssh)
  7458. {
  7459. if (ssh->version == 2 &&
  7460. !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
  7461. (ssh->channels && count234(ssh->channels) == 0) &&
  7462. !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
  7463. /*
  7464. * We used to send SSH_MSG_DISCONNECT here, because I'd
  7465. * believed that _every_ conforming SSH-2 connection had to
  7466. * end with a disconnect being sent by at least one side;
  7467. * apparently I was wrong and it's perfectly OK to
  7468. * unceremoniously slam the connection shut when you're done,
  7469. * and indeed OpenSSH feels this is more polite than sending a
  7470. * DISCONNECT. So now we don't.
  7471. */
  7472. ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
  7473. }
  7474. }
  7475. void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
  7476. const char *peerinfo)
  7477. {
  7478. if (peerinfo)
  7479. logeventf(ssh, "Connection sharing downstream #%u connected from %s",
  7480. id, peerinfo);
  7481. else
  7482. logeventf(ssh, "Connection sharing downstream #%u connected", id);
  7483. }
  7484. void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
  7485. {
  7486. logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
  7487. ssh_check_termination(ssh);
  7488. }
  7489. void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
  7490. {
  7491. va_list ap;
  7492. char *buf;
  7493. va_start(ap, logfmt);
  7494. buf = dupvprintf(logfmt, ap);
  7495. va_end(ap);
  7496. if (id)
  7497. logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
  7498. else
  7499. logeventf(ssh, "Connection sharing: %s", buf);
  7500. sfree(buf);
  7501. }
  7502. /*
  7503. * Close any local socket and free any local resources associated with
  7504. * a channel. This converts the channel into a CHAN_ZOMBIE.
  7505. */
  7506. static void ssh_channel_close_local(struct ssh_channel *c, char const *reason)
  7507. {
  7508. Ssh ssh = c->ssh;
  7509. char const *msg = NULL;
  7510. switch (c->type) {
  7511. case CHAN_MAINSESSION:
  7512. ssh->mainchan = NULL;
  7513. update_specials_menu(ssh->frontend);
  7514. break;
  7515. case CHAN_X11:
  7516. assert(c->u.x11.xconn != NULL);
  7517. x11_close(c->u.x11.xconn);
  7518. msg = "Forwarded X11 connection terminated";
  7519. break;
  7520. case CHAN_AGENT:
  7521. if (c->u.a.pending)
  7522. agent_cancel_query(c->u.a.pending);
  7523. bufchain_clear(&c->u.a.inbuffer);
  7524. msg = "Agent-forwarding connection closed";
  7525. break;
  7526. case CHAN_SOCKDATA:
  7527. assert(c->u.pfd.pf != NULL);
  7528. pfd_close(c->u.pfd.pf);
  7529. msg = "Forwarded port closed";
  7530. break;
  7531. }
  7532. c->type = CHAN_ZOMBIE;
  7533. if (msg != NULL) {
  7534. if (reason != NULL)
  7535. logeventf(ssh, "%s %s", msg, reason);
  7536. else
  7537. logevent(msg);
  7538. }
  7539. }
  7540. static void ssh_channel_destroy(struct ssh_channel *c)
  7541. {
  7542. Ssh ssh = c->ssh;
  7543. ssh_channel_close_local(c, NULL);
  7544. del234(ssh->channels, c);
  7545. if (ssh->version == 2) {
  7546. bufchain_clear(&c->v.v2.outbuffer);
  7547. assert(c->v.v2.chanreq_head == NULL);
  7548. }
  7549. sfree(c);
  7550. /*
  7551. * If that was the last channel left open, we might need to
  7552. * terminate.
  7553. */
  7554. ssh_check_termination(ssh);
  7555. }
  7556. static void ssh2_channel_check_close(struct ssh_channel *c)
  7557. {
  7558. Ssh ssh = c->ssh;
  7559. struct Packet *pktout;
  7560. assert(ssh->version == 2);
  7561. if (c->halfopen) {
  7562. /*
  7563. * If we've sent out our own CHANNEL_OPEN but not yet seen
  7564. * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
  7565. * it's too early to be sending close messages of any kind.
  7566. */
  7567. return;
  7568. }
  7569. if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
  7570. c->type == CHAN_ZOMBIE) &&
  7571. !c->v.v2.chanreq_head &&
  7572. !(c->closes & CLOSES_SENT_CLOSE)) {
  7573. /*
  7574. * We have both sent and received EOF (or the channel is a
  7575. * zombie), and we have no outstanding channel requests, which
  7576. * means the channel is in final wind-up. But we haven't sent
  7577. * CLOSE, so let's do so now.
  7578. */
  7579. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
  7580. ssh2_pkt_adduint32(pktout, c->remoteid);
  7581. ssh2_pkt_send(ssh, pktout);
  7582. c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
  7583. }
  7584. if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
  7585. assert(c->v.v2.chanreq_head == NULL);
  7586. /*
  7587. * We have both sent and received CLOSE, which means we're
  7588. * completely done with the channel.
  7589. */
  7590. ssh_channel_destroy(c);
  7591. }
  7592. }
  7593. static void ssh_channel_got_eof(struct ssh_channel *c)
  7594. {
  7595. if (c->closes & CLOSES_RCVD_EOF)
  7596. return; /* already seen EOF */
  7597. c->closes |= CLOSES_RCVD_EOF;
  7598. if (c->type == CHAN_X11) {
  7599. assert(c->u.x11.xconn != NULL);
  7600. x11_send_eof(c->u.x11.xconn);
  7601. } else if (c->type == CHAN_AGENT) {
  7602. /* Just call try_forward, which will respond to the EOF now if
  7603. * appropriate, or wait until the queue of outstanding
  7604. * requests is dealt with if not */
  7605. ssh_agentf_try_forward(c);
  7606. } else if (c->type == CHAN_SOCKDATA) {
  7607. assert(c->u.pfd.pf != NULL);
  7608. pfd_send_eof(c->u.pfd.pf);
  7609. } else if (c->type == CHAN_MAINSESSION) {
  7610. Ssh ssh = c->ssh;
  7611. if (!ssh->sent_console_eof &&
  7612. (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
  7613. /*
  7614. * Either from_backend_eof told us that the front end
  7615. * wants us to close the outgoing side of the connection
  7616. * as soon as we see EOF from the far end, or else we've
  7617. * unilaterally decided to do that because we've allocated
  7618. * a remote pty and hence EOF isn't a particularly
  7619. * meaningful concept.
  7620. */
  7621. sshfwd_write_eof(c);
  7622. }
  7623. ssh->sent_console_eof = TRUE;
  7624. }
  7625. }
  7626. static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
  7627. {
  7628. struct ssh_channel *c;
  7629. c = ssh_channel_msg(ssh, pktin);
  7630. if (!c)
  7631. return;
  7632. ssh_channel_got_eof(c);
  7633. ssh2_channel_check_close(c);
  7634. }
  7635. static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
  7636. {
  7637. struct ssh_channel *c;
  7638. c = ssh_channel_msg(ssh, pktin);
  7639. if (!c)
  7640. return;
  7641. /*
  7642. * When we receive CLOSE on a channel, we assume it comes with an
  7643. * implied EOF if we haven't seen EOF yet.
  7644. */
  7645. ssh_channel_got_eof(c);
  7646. if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
  7647. /*
  7648. * It also means we stop expecting to see replies to any
  7649. * outstanding channel requests, so clean those up too.
  7650. * (ssh_chanreq_init will enforce by assertion that we don't
  7651. * subsequently put anything back on this list.)
  7652. */
  7653. while (c->v.v2.chanreq_head) {
  7654. struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
  7655. ocr->handler(c, NULL, ocr->ctx);
  7656. c->v.v2.chanreq_head = ocr->next;
  7657. sfree(ocr);
  7658. }
  7659. }
  7660. /*
  7661. * And we also send an outgoing EOF, if we haven't already, on the
  7662. * assumption that CLOSE is a pretty forceful announcement that
  7663. * the remote side is doing away with the entire channel. (If it
  7664. * had wanted to send us EOF and continue receiving data from us,
  7665. * it would have just sent CHANNEL_EOF.)
  7666. */
  7667. if (!(c->closes & CLOSES_SENT_EOF)) {
  7668. /*
  7669. * Make sure we don't read any more from whatever our local
  7670. * data source is for this channel.
  7671. */
  7672. switch (c->type) {
  7673. case CHAN_MAINSESSION:
  7674. ssh->send_ok = 0; /* stop trying to read from stdin */
  7675. break;
  7676. case CHAN_X11:
  7677. x11_override_throttle(c->u.x11.xconn, 1);
  7678. break;
  7679. case CHAN_SOCKDATA:
  7680. pfd_override_throttle(c->u.pfd.pf, 1);
  7681. break;
  7682. }
  7683. /*
  7684. * Abandon any buffered data we still wanted to send to this
  7685. * channel. Receiving a CHANNEL_CLOSE is an indication that
  7686. * the server really wants to get on and _destroy_ this
  7687. * channel, and it isn't going to send us any further
  7688. * WINDOW_ADJUSTs to permit us to send pending stuff.
  7689. */
  7690. bufchain_clear(&c->v.v2.outbuffer);
  7691. /*
  7692. * Send outgoing EOF.
  7693. */
  7694. sshfwd_write_eof(c);
  7695. }
  7696. /*
  7697. * Now process the actual close.
  7698. */
  7699. if (!(c->closes & CLOSES_RCVD_CLOSE)) {
  7700. c->closes |= CLOSES_RCVD_CLOSE;
  7701. ssh2_channel_check_close(c);
  7702. }
  7703. }
  7704. static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
  7705. {
  7706. struct ssh_channel *c;
  7707. c = ssh_channel_msg(ssh, pktin);
  7708. if (!c)
  7709. return;
  7710. assert(c->halfopen); /* ssh_channel_msg will have enforced this */
  7711. c->remoteid = ssh_pkt_getuint32(pktin);
  7712. c->halfopen = FALSE;
  7713. c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
  7714. c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
  7715. if (c->type == CHAN_SOCKDATA) {
  7716. assert(c->u.pfd.pf != NULL);
  7717. pfd_confirm(c->u.pfd.pf);
  7718. } else if (c->type == CHAN_ZOMBIE) {
  7719. /*
  7720. * This case can occur if a local socket error occurred
  7721. * between us sending out CHANNEL_OPEN and receiving
  7722. * OPEN_CONFIRMATION. In this case, all we can do is
  7723. * immediately initiate close proceedings now that we know the
  7724. * server's id to put in the close message.
  7725. */
  7726. ssh2_channel_check_close(c);
  7727. } else {
  7728. /*
  7729. * We never expect to receive OPEN_CONFIRMATION for any
  7730. * *other* channel type (since only local-to-remote port
  7731. * forwardings cause us to send CHANNEL_OPEN after the main
  7732. * channel is live - all other auxiliary channel types are
  7733. * initiated from the server end). It's safe to enforce this
  7734. * by assertion rather than by ssh_disconnect, because the
  7735. * real point is that we never constructed a half-open channel
  7736. * structure in the first place with any type other than the
  7737. * above.
  7738. */
  7739. assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
  7740. }
  7741. if (c->pending_eof)
  7742. ssh_channel_try_eof(c); /* in case we had a pending EOF */
  7743. }
  7744. static char *ssh2_channel_open_failure_error_text(struct Packet *pktin)
  7745. {
  7746. static const char *const reasons[] = {
  7747. NULL,
  7748. "Administratively prohibited",
  7749. "Connect failed",
  7750. "Unknown channel type",
  7751. "Resource shortage",
  7752. };
  7753. unsigned reason_code;
  7754. const char *reason_code_string;
  7755. char reason_code_buf[256];
  7756. char *reason_string;
  7757. int reason_length;
  7758. reason_code = ssh_pkt_getuint32(pktin);
  7759. if (reason_code < lenof(reasons) && reasons[reason_code]) {
  7760. reason_code_string = reasons[reason_code];
  7761. } else {
  7762. reason_code_string = reason_code_buf;
  7763. sprintf(reason_code_buf, "unknown reason code %#x", reason_code);
  7764. }
  7765. ssh_pkt_getstring(pktin, &reason_string, &reason_length);
  7766. return dupprintf("%s [%.*s]", reason_code_string,
  7767. reason_length, NULLTOEMPTY(reason_string));
  7768. }
  7769. static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
  7770. {
  7771. struct ssh_channel *c;
  7772. c = ssh_channel_msg(ssh, pktin);
  7773. if (!c)
  7774. return;
  7775. assert(c->halfopen); /* ssh_channel_msg will have enforced this */
  7776. if (c->type == CHAN_SOCKDATA) {
  7777. char *errtext = ssh2_channel_open_failure_error_text(pktin);
  7778. logeventf(ssh, "Forwarded connection refused by server: %s", errtext);
  7779. sfree(errtext);
  7780. pfd_close(c->u.pfd.pf);
  7781. } else if (c->type == CHAN_ZOMBIE) {
  7782. /*
  7783. * This case can occur if a local socket error occurred
  7784. * between us sending out CHANNEL_OPEN and receiving
  7785. * OPEN_FAILURE. In this case, we need do nothing except allow
  7786. * the code below to throw the half-open channel away.
  7787. */
  7788. } else {
  7789. /*
  7790. * We never expect to receive OPEN_FAILURE for any *other*
  7791. * channel type (since only local-to-remote port forwardings
  7792. * cause us to send CHANNEL_OPEN after the main channel is
  7793. * live - all other auxiliary channel types are initiated from
  7794. * the server end). It's safe to enforce this by assertion
  7795. * rather than by ssh_disconnect, because the real point is
  7796. * that we never constructed a half-open channel structure in
  7797. * the first place with any type other than the above.
  7798. */
  7799. assert(!"Funny channel type in ssh2_msg_channel_open_failure");
  7800. }
  7801. del234(ssh->channels, c);
  7802. sfree(c);
  7803. }
  7804. static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
  7805. {
  7806. char *type;
  7807. int typelen, want_reply;
  7808. int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
  7809. struct ssh_channel *c;
  7810. struct Packet *pktout;
  7811. c = ssh_channel_msg(ssh, pktin);
  7812. if (!c)
  7813. return;
  7814. ssh_pkt_getstring(pktin, &type, &typelen);
  7815. want_reply = ssh2_pkt_getbool(pktin);
  7816. if (c->closes & CLOSES_SENT_CLOSE) {
  7817. /*
  7818. * We don't reply to channel requests after we've sent
  7819. * CHANNEL_CLOSE for the channel, because our reply might
  7820. * cross in the network with the other side's CHANNEL_CLOSE
  7821. * and arrive after they have wound the channel up completely.
  7822. */
  7823. want_reply = FALSE;
  7824. }
  7825. /*
  7826. * Having got the channel number, we now look at
  7827. * the request type string to see if it's something
  7828. * we recognise.
  7829. */
  7830. if (c == ssh->mainchan) {
  7831. /*
  7832. * We recognise "exit-status" and "exit-signal" on
  7833. * the primary channel.
  7834. */
  7835. if (typelen == 11 &&
  7836. !memcmp(type, "exit-status", 11)) {
  7837. ssh->exitcode = ssh_pkt_getuint32(pktin);
  7838. logeventf(ssh, "Server sent command exit status %d",
  7839. ssh->exitcode);
  7840. reply = SSH2_MSG_CHANNEL_SUCCESS;
  7841. } else if (typelen == 11 &&
  7842. !memcmp(type, "exit-signal", 11)) {
  7843. int is_plausible = TRUE, is_int = FALSE;
  7844. char *fmt_sig = NULL, *fmt_msg = NULL;
  7845. char *msg;
  7846. int msglen = 0, core = FALSE;
  7847. /* ICK: older versions of OpenSSH (e.g. 3.4p1)
  7848. * provide an `int' for the signal, despite its
  7849. * having been a `string' in the drafts of RFC 4254 since at
  7850. * least 2001. (Fixed in session.c 1.147.) Try to
  7851. * infer which we can safely parse it as. */
  7852. {
  7853. unsigned char *p = pktin->body +
  7854. pktin->savedpos;
  7855. long len = pktin->length - pktin->savedpos;
  7856. unsigned long num = GET_32BIT(p); /* what is it? */
  7857. /* If it's 0, it hardly matters; assume string */
  7858. if (num == 0) {
  7859. is_int = FALSE;
  7860. } else {
  7861. int maybe_int = FALSE, maybe_str = FALSE;
  7862. #define CHECK_HYPOTHESIS(offset, result) \
  7863. do \
  7864. { \
  7865. int q = toint(offset); \
  7866. if (q >= 0 && q+4 <= len) { \
  7867. q = toint(q + 4 + GET_32BIT(p+q)); \
  7868. if (q >= 0 && q+4 <= len && \
  7869. ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
  7870. q == len) \
  7871. result = TRUE; \
  7872. } \
  7873. } while(0)
  7874. CHECK_HYPOTHESIS(4+1, maybe_int);
  7875. CHECK_HYPOTHESIS(4+num+1, maybe_str);
  7876. #undef CHECK_HYPOTHESIS
  7877. if (maybe_int && !maybe_str)
  7878. is_int = TRUE;
  7879. else if (!maybe_int && maybe_str)
  7880. is_int = FALSE;
  7881. else
  7882. /* Crikey. Either or neither. Panic. */
  7883. is_plausible = FALSE;
  7884. }
  7885. }
  7886. ssh->exitcode = 128; /* means `unknown signal' */
  7887. if (is_plausible) {
  7888. if (is_int) {
  7889. /* Old non-standard OpenSSH. */
  7890. int signum = ssh_pkt_getuint32(pktin);
  7891. fmt_sig = dupprintf(" %d", signum);
  7892. ssh->exitcode = 128 + signum;
  7893. } else {
  7894. /* As per RFC 4254. */
  7895. char *sig;
  7896. int siglen;
  7897. ssh_pkt_getstring(pktin, &sig, &siglen);
  7898. /* Signal name isn't supposed to be blank, but
  7899. * let's cope gracefully if it is. */
  7900. if (siglen) {
  7901. fmt_sig = dupprintf(" \"%.*s\"",
  7902. siglen, sig);
  7903. }
  7904. /*
  7905. * Really hideous method of translating the
  7906. * signal description back into a locally
  7907. * meaningful number.
  7908. */
  7909. if (0)
  7910. ;
  7911. #define TRANSLATE_SIGNAL(s) \
  7912. else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
  7913. ssh->exitcode = 128 + SIG ## s
  7914. #ifdef SIGABRT
  7915. TRANSLATE_SIGNAL(ABRT);
  7916. #endif
  7917. #ifdef SIGALRM
  7918. TRANSLATE_SIGNAL(ALRM);
  7919. #endif
  7920. #ifdef SIGFPE
  7921. TRANSLATE_SIGNAL(FPE);
  7922. #endif
  7923. #ifdef SIGHUP
  7924. TRANSLATE_SIGNAL(HUP);
  7925. #endif
  7926. #ifdef SIGILL
  7927. TRANSLATE_SIGNAL(ILL);
  7928. #endif
  7929. #ifdef SIGINT
  7930. TRANSLATE_SIGNAL(INT);
  7931. #endif
  7932. #ifdef SIGKILL
  7933. TRANSLATE_SIGNAL(KILL);
  7934. #endif
  7935. #ifdef SIGPIPE
  7936. TRANSLATE_SIGNAL(PIPE);
  7937. #endif
  7938. #ifdef SIGQUIT
  7939. TRANSLATE_SIGNAL(QUIT);
  7940. #endif
  7941. #ifdef SIGSEGV
  7942. TRANSLATE_SIGNAL(SEGV);
  7943. #endif
  7944. #ifdef SIGTERM
  7945. TRANSLATE_SIGNAL(TERM);
  7946. #endif
  7947. #ifdef SIGUSR1
  7948. TRANSLATE_SIGNAL(USR1);
  7949. #endif
  7950. #ifdef SIGUSR2
  7951. TRANSLATE_SIGNAL(USR2);
  7952. #endif
  7953. #undef TRANSLATE_SIGNAL
  7954. else
  7955. ssh->exitcode = 128;
  7956. }
  7957. core = ssh2_pkt_getbool(pktin);
  7958. ssh_pkt_getstring(pktin, &msg, &msglen);
  7959. if (msglen) {
  7960. fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
  7961. }
  7962. /* ignore lang tag */
  7963. } /* else don't attempt to parse */
  7964. logeventf(ssh, "Server exited on signal%s%s%s",
  7965. fmt_sig ? fmt_sig : "",
  7966. core ? " (core dumped)" : "",
  7967. fmt_msg ? fmt_msg : "");
  7968. sfree(fmt_sig);
  7969. sfree(fmt_msg);
  7970. reply = SSH2_MSG_CHANNEL_SUCCESS;
  7971. }
  7972. } else {
  7973. /*
  7974. * This is a channel request we don't know
  7975. * about, so we now either ignore the request
  7976. * or respond with CHANNEL_FAILURE, depending
  7977. * on want_reply.
  7978. */
  7979. reply = SSH2_MSG_CHANNEL_FAILURE;
  7980. }
  7981. if (want_reply) {
  7982. pktout = ssh2_pkt_init(reply);
  7983. ssh2_pkt_adduint32(pktout, c->remoteid);
  7984. ssh2_pkt_send(ssh, pktout);
  7985. }
  7986. }
  7987. static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
  7988. {
  7989. char *type;
  7990. int typelen, want_reply;
  7991. struct Packet *pktout;
  7992. ssh_pkt_getstring(pktin, &type, &typelen);
  7993. want_reply = ssh2_pkt_getbool(pktin);
  7994. /*
  7995. * We currently don't support any global requests
  7996. * at all, so we either ignore the request or
  7997. * respond with REQUEST_FAILURE, depending on
  7998. * want_reply.
  7999. */
  8000. if (want_reply) {
  8001. pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
  8002. ssh2_pkt_send(ssh, pktout);
  8003. }
  8004. }
  8005. struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
  8006. void *share_cs,
  8007. void *share_chan)
  8008. {
  8009. struct X11FakeAuth *auth;
  8010. /*
  8011. * Make up a new set of fake X11 auth data, and add it to the tree
  8012. * of currently valid ones with an indication of the sharing
  8013. * context that it's relevant to.
  8014. */
  8015. auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
  8016. auth->share_cs = share_cs;
  8017. auth->share_chan = share_chan;
  8018. return auth;
  8019. }
  8020. void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
  8021. {
  8022. del234(ssh->x11authtree, auth);
  8023. x11_free_fake_auth(auth);
  8024. }
  8025. static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
  8026. {
  8027. char *type;
  8028. int typelen;
  8029. char *peeraddr;
  8030. int peeraddrlen;
  8031. int peerport;
  8032. const char *error = NULL;
  8033. struct ssh_channel *c;
  8034. unsigned remid, winsize, pktsize;
  8035. unsigned our_winsize_override = 0;
  8036. struct Packet *pktout;
  8037. ssh_pkt_getstring(pktin, &type, &typelen);
  8038. c = snew(struct ssh_channel);
  8039. c->ssh = ssh;
  8040. remid = ssh_pkt_getuint32(pktin);
  8041. winsize = ssh_pkt_getuint32(pktin);
  8042. pktsize = ssh_pkt_getuint32(pktin);
  8043. if (typelen == 3 && !memcmp(type, "x11", 3)) {
  8044. char *addrstr;
  8045. ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
  8046. addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
  8047. peerport = ssh_pkt_getuint32(pktin);
  8048. logeventf(ssh, "Received X11 connect request from %s:%d",
  8049. addrstr, peerport);
  8050. if (!ssh->X11_fwd_enabled && !ssh->connshare)
  8051. error = "X11 forwarding is not enabled";
  8052. else {
  8053. c->u.x11.xconn = x11_init(ssh->x11authtree, c,
  8054. addrstr, peerport);
  8055. c->type = CHAN_X11;
  8056. c->u.x11.initial = TRUE;
  8057. /*
  8058. * If we are a connection-sharing upstream, then we should
  8059. * initially present a very small window, adequate to take
  8060. * the X11 initial authorisation packet but not much more.
  8061. * Downstream will then present us a larger window (by
  8062. * fiat of the connection-sharing protocol) and we can
  8063. * guarantee to send a positive-valued WINDOW_ADJUST.
  8064. */
  8065. if (ssh->connshare)
  8066. our_winsize_override = 128;
  8067. logevent("Opened X11 forward channel");
  8068. }
  8069. sfree(addrstr);
  8070. } else if (typelen == 15 &&
  8071. !memcmp(type, "forwarded-tcpip", 15)) {
  8072. struct ssh_rportfwd pf, *realpf;
  8073. char *shost;
  8074. int shostlen;
  8075. ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
  8076. pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
  8077. pf.sport = ssh_pkt_getuint32(pktin);
  8078. ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
  8079. peerport = ssh_pkt_getuint32(pktin);
  8080. realpf = find234(ssh->rportfwds, &pf, NULL);
  8081. logeventf(ssh, "Received remote port %s:%d open request "
  8082. "from %.*s:%d", pf.shost, pf.sport,
  8083. peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
  8084. sfree(pf.shost);
  8085. if (realpf == NULL) {
  8086. error = "Remote port is not recognised";
  8087. } else {
  8088. char *err;
  8089. if (realpf->share_ctx) {
  8090. /*
  8091. * This port forwarding is on behalf of a
  8092. * connection-sharing downstream, so abandon our own
  8093. * channel-open procedure and just pass the message on
  8094. * to sshshare.c.
  8095. */
  8096. share_got_pkt_from_server(realpf->share_ctx, pktin->type,
  8097. pktin->body, pktin->length);
  8098. sfree(c);
  8099. return;
  8100. }
  8101. err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
  8102. c, ssh->conf, realpf->pfrec->addressfamily);
  8103. logeventf(ssh, "Attempting to forward remote port to "
  8104. "%s:%d", realpf->dhost, realpf->dport);
  8105. if (err != NULL) {
  8106. logeventf(ssh, "Port open failed: %s", err);
  8107. sfree(err);
  8108. error = "Port open failed";
  8109. } else {
  8110. logevent("Forwarded port opened successfully");
  8111. c->type = CHAN_SOCKDATA;
  8112. }
  8113. }
  8114. } else if (typelen == 22 &&
  8115. !memcmp(type, "[email protected]", 22)) {
  8116. if (!ssh->agentfwd_enabled)
  8117. error = "Agent forwarding is not enabled";
  8118. else {
  8119. c->type = CHAN_AGENT; /* identify channel type */
  8120. bufchain_init(&c->u.a.inbuffer);
  8121. c->u.a.pending = NULL;
  8122. }
  8123. } else {
  8124. error = "Unsupported channel type requested";
  8125. }
  8126. c->remoteid = remid;
  8127. c->halfopen = FALSE;
  8128. if (error) {
  8129. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
  8130. ssh2_pkt_adduint32(pktout, c->remoteid);
  8131. ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
  8132. ssh2_pkt_addstring(pktout, error);
  8133. ssh2_pkt_addstring(pktout, "en"); /* language tag */
  8134. ssh2_pkt_send(ssh, pktout);
  8135. logeventf(ssh, "Rejected channel open: %s", error);
  8136. sfree(c);
  8137. } else {
  8138. ssh_channel_init(c);
  8139. c->v.v2.remwindow = winsize;
  8140. c->v.v2.remmaxpkt = pktsize;
  8141. if (our_winsize_override) {
  8142. c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
  8143. our_winsize_override;
  8144. }
  8145. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
  8146. ssh2_pkt_adduint32(pktout, c->remoteid);
  8147. ssh2_pkt_adduint32(pktout, c->localid);
  8148. ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
  8149. ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
  8150. ssh2_pkt_send(ssh, pktout);
  8151. }
  8152. }
  8153. void sshfwd_x11_sharing_handover(struct ssh_channel *c,
  8154. void *share_cs, void *share_chan,
  8155. const char *peer_addr, int peer_port,
  8156. int endian, int protomajor, int protominor,
  8157. const void *initial_data, int initial_len)
  8158. {
  8159. /*
  8160. * This function is called when we've just discovered that an X
  8161. * forwarding channel on which we'd been handling the initial auth
  8162. * ourselves turns out to be destined for a connection-sharing
  8163. * downstream. So we turn the channel into a CHAN_SHARING, meaning
  8164. * that we completely stop tracking windows and buffering data and
  8165. * just pass more or less unmodified SSH messages back and forth.
  8166. */
  8167. c->type = CHAN_SHARING;
  8168. c->u.sharing.ctx = share_cs;
  8169. share_setup_x11_channel(share_cs, share_chan,
  8170. c->localid, c->remoteid, c->v.v2.remwindow,
  8171. c->v.v2.remmaxpkt, c->v.v2.locwindow,
  8172. peer_addr, peer_port, endian,
  8173. protomajor, protominor,
  8174. initial_data, initial_len);
  8175. }
  8176. void sshfwd_x11_is_local(struct ssh_channel *c)
  8177. {
  8178. /*
  8179. * This function is called when we've just discovered that an X
  8180. * forwarding channel is _not_ destined for a connection-sharing
  8181. * downstream but we're going to handle it ourselves. We stop
  8182. * presenting a cautiously small window and go into ordinary data
  8183. * exchange mode.
  8184. */
  8185. c->u.x11.initial = FALSE;
  8186. ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
  8187. }
  8188. /*
  8189. * Buffer banner messages for later display at some convenient point,
  8190. * if we're going to display them.
  8191. */
  8192. static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
  8193. {
  8194. /* Arbitrary limit to prevent unbounded inflation of buffer */
  8195. if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
  8196. bufchain_size(&ssh->banner) <= 131072) {
  8197. char *banner = NULL;
  8198. int size = 0;
  8199. ssh_pkt_getstring(pktin, &banner, &size);
  8200. if (banner)
  8201. bufchain_add(&ssh->banner, banner, size);
  8202. }
  8203. }
  8204. /* Helper function to deal with sending tty modes for "pty-req" */
  8205. static void ssh2_send_ttymode(void *data,
  8206. const struct ssh_ttymode *mode, char *val)
  8207. {
  8208. struct Packet *pktout = (struct Packet *)data;
  8209. unsigned int arg = 0;
  8210. switch (mode->type) {
  8211. case TTY_OP_CHAR:
  8212. arg = ssh_tty_parse_specchar(val);
  8213. break;
  8214. case TTY_OP_BOOL:
  8215. arg = ssh_tty_parse_boolean(val);
  8216. break;
  8217. }
  8218. ssh2_pkt_addbyte(pktout, mode->opcode);
  8219. ssh2_pkt_adduint32(pktout, arg);
  8220. }
  8221. static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
  8222. void *ctx)
  8223. {
  8224. struct ssh2_setup_x11_state {
  8225. int crLine;
  8226. };
  8227. Ssh ssh = c->ssh;
  8228. struct Packet *pktout;
  8229. crStateP(ssh2_setup_x11_state, ctx);
  8230. crBeginState;
  8231. logevent("Requesting X11 forwarding");
  8232. pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
  8233. ssh2_setup_x11, s);
  8234. ssh2_pkt_addbool(pktout, 0); /* many connections */
  8235. ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
  8236. ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
  8237. ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
  8238. ssh2_pkt_send(ssh, pktout);
  8239. /* Wait to be called back with either a response packet, or NULL
  8240. * meaning clean up and free our data */
  8241. crReturnV;
  8242. if (pktin) {
  8243. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
  8244. logevent("X11 forwarding enabled");
  8245. ssh->X11_fwd_enabled = TRUE;
  8246. } else
  8247. logevent("X11 forwarding refused");
  8248. }
  8249. crFinishFreeV;
  8250. }
  8251. static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
  8252. void *ctx)
  8253. {
  8254. struct ssh2_setup_agent_state {
  8255. int crLine;
  8256. };
  8257. Ssh ssh = c->ssh;
  8258. struct Packet *pktout;
  8259. crStateP(ssh2_setup_agent_state, ctx);
  8260. crBeginState;
  8261. logevent("Requesting OpenSSH-style agent forwarding");
  8262. pktout = ssh2_chanreq_init(ssh->mainchan, "[email protected]",
  8263. ssh2_setup_agent, s);
  8264. ssh2_pkt_send(ssh, pktout);
  8265. /* Wait to be called back with either a response packet, or NULL
  8266. * meaning clean up and free our data */
  8267. crReturnV;
  8268. if (pktin) {
  8269. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
  8270. logevent("Agent forwarding enabled");
  8271. ssh->agentfwd_enabled = TRUE;
  8272. } else
  8273. logevent("Agent forwarding refused");
  8274. }
  8275. crFinishFreeV;
  8276. }
  8277. static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
  8278. void *ctx)
  8279. {
  8280. struct ssh2_setup_pty_state {
  8281. int crLine;
  8282. };
  8283. Ssh ssh = c->ssh;
  8284. struct Packet *pktout;
  8285. crStateP(ssh2_setup_pty_state, ctx);
  8286. crBeginState;
  8287. /* Unpick the terminal-speed string. */
  8288. /* XXX perhaps we should allow no speeds to be sent. */
  8289. ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
  8290. sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
  8291. /* Build the pty request. */
  8292. pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
  8293. ssh2_setup_pty, s);
  8294. ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
  8295. ssh2_pkt_adduint32(pktout, ssh->term_width);
  8296. ssh2_pkt_adduint32(pktout, ssh->term_height);
  8297. ssh2_pkt_adduint32(pktout, 0); /* pixel width */
  8298. ssh2_pkt_adduint32(pktout, 0); /* pixel height */
  8299. ssh2_pkt_addstring_start(pktout);
  8300. parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
  8301. ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
  8302. ssh2_pkt_adduint32(pktout, ssh->ispeed);
  8303. ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
  8304. ssh2_pkt_adduint32(pktout, ssh->ospeed);
  8305. ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
  8306. ssh2_pkt_send(ssh, pktout);
  8307. ssh->state = SSH_STATE_INTERMED;
  8308. /* Wait to be called back with either a response packet, or NULL
  8309. * meaning clean up and free our data */
  8310. crReturnV;
  8311. if (pktin) {
  8312. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
  8313. logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
  8314. ssh->ospeed, ssh->ispeed);
  8315. ssh->got_pty = TRUE;
  8316. } else {
  8317. c_write_str(ssh, "Server refused to allocate pty\r\n");
  8318. ssh->editing = ssh->echoing = 1;
  8319. }
  8320. }
  8321. crFinishFreeV;
  8322. }
  8323. static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
  8324. void *ctx)
  8325. {
  8326. struct ssh2_setup_env_state {
  8327. int crLine;
  8328. int num_env, env_left, env_ok;
  8329. };
  8330. Ssh ssh = c->ssh;
  8331. struct Packet *pktout;
  8332. crStateP(ssh2_setup_env_state, ctx);
  8333. crBeginState;
  8334. /*
  8335. * Send environment variables.
  8336. *
  8337. * Simplest thing here is to send all the requests at once, and
  8338. * then wait for a whole bunch of successes or failures.
  8339. */
  8340. s->num_env = 0;
  8341. {
  8342. char *key, *val;
  8343. for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
  8344. val != NULL;
  8345. val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
  8346. pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
  8347. ssh2_pkt_addstring(pktout, key);
  8348. ssh2_pkt_addstring(pktout, val);
  8349. ssh2_pkt_send(ssh, pktout);
  8350. s->num_env++;
  8351. }
  8352. if (s->num_env)
  8353. logeventf(ssh, "Sent %d environment variables", s->num_env);
  8354. }
  8355. if (s->num_env) {
  8356. s->env_ok = 0;
  8357. s->env_left = s->num_env;
  8358. while (s->env_left > 0) {
  8359. /* Wait to be called back with either a response packet,
  8360. * or NULL meaning clean up and free our data */
  8361. crReturnV;
  8362. if (!pktin) goto out;
  8363. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
  8364. s->env_ok++;
  8365. s->env_left--;
  8366. }
  8367. if (s->env_ok == s->num_env) {
  8368. logevent("All environment variables successfully set");
  8369. } else if (s->env_ok == 0) {
  8370. logevent("All environment variables refused");
  8371. c_write_str(ssh, "Server refused to set environment variables\r\n");
  8372. } else {
  8373. logeventf(ssh, "%d environment variables refused",
  8374. s->num_env - s->env_ok);
  8375. c_write_str(ssh, "Server refused to set all environment variables\r\n");
  8376. }
  8377. }
  8378. out:;
  8379. crFinishFreeV;
  8380. }
  8381. /*
  8382. * Handle the SSH-2 userauth and connection layers.
  8383. */
  8384. static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
  8385. {
  8386. do_ssh2_authconn(ssh, NULL, 0, pktin);
  8387. }
  8388. static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
  8389. void *ctx)
  8390. {
  8391. if (pktin)
  8392. do_ssh2_authconn(c->ssh, NULL, 0, pktin);
  8393. }
  8394. static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
  8395. struct Packet *pktin)
  8396. {
  8397. struct do_ssh2_authconn_state {
  8398. int crLine;
  8399. enum {
  8400. AUTH_TYPE_NONE,
  8401. AUTH_TYPE_PUBLICKEY,
  8402. AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
  8403. AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
  8404. AUTH_TYPE_PASSWORD,
  8405. AUTH_TYPE_GSSAPI, /* always QUIET */
  8406. AUTH_TYPE_KEYBOARD_INTERACTIVE,
  8407. AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
  8408. } type;
  8409. int done_service_req;
  8410. int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
  8411. int tried_pubkey_config, done_agent;
  8412. #ifndef NO_GSSAPI
  8413. int can_gssapi;
  8414. int tried_gssapi;
  8415. #endif
  8416. int kbd_inter_refused;
  8417. int we_are_in, userauth_success;
  8418. prompts_t *cur_prompt;
  8419. #ifdef MPEXT
  8420. int change_password;
  8421. #endif
  8422. int num_prompts;
  8423. char *username;
  8424. char *password;
  8425. int got_username;
  8426. void *publickey_blob;
  8427. int publickey_bloblen;
  8428. int privatekey_available, privatekey_encrypted;
  8429. char *publickey_algorithm;
  8430. char *publickey_comment;
  8431. unsigned char agent_request[5], *agent_response, *agentp;
  8432. int agent_responselen;
  8433. unsigned char *pkblob_in_agent;
  8434. int keyi, nkeys;
  8435. char *pkblob, *alg, *commentp;
  8436. int pklen, alglen, commentlen;
  8437. int siglen, retlen, len;
  8438. char *q, *agentreq, *ret;
  8439. struct Packet *pktout;
  8440. Filename *keyfile;
  8441. #ifndef NO_GSSAPI
  8442. struct ssh_gss_library *gsslib;
  8443. Ssh_gss_ctx gss_ctx;
  8444. Ssh_gss_buf gss_buf;
  8445. Ssh_gss_buf gss_rcvtok, gss_sndtok;
  8446. Ssh_gss_name gss_srv_name;
  8447. Ssh_gss_stat gss_stat;
  8448. #endif
  8449. };
  8450. crState(do_ssh2_authconn_state);
  8451. crBeginState;
  8452. /* Register as a handler for all the messages this coroutine handles. */
  8453. ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
  8454. ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
  8455. ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
  8456. ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
  8457. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
  8458. ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
  8459. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
  8460. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
  8461. ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
  8462. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
  8463. ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
  8464. ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
  8465. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
  8466. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
  8467. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
  8468. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
  8469. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
  8470. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
  8471. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
  8472. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
  8473. s->done_service_req = FALSE;
  8474. s->we_are_in = s->userauth_success = FALSE;
  8475. s->agent_response = NULL;
  8476. #ifndef NO_GSSAPI
  8477. s->tried_gssapi = FALSE;
  8478. #endif
  8479. if (!ssh->bare_connection) {
  8480. if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
  8481. /*
  8482. * Request userauth protocol, and await a response to it.
  8483. */
  8484. s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
  8485. ssh2_pkt_addstring(s->pktout, "ssh-userauth");
  8486. ssh2_pkt_send(ssh, s->pktout);
  8487. crWaitUntilV(pktin);
  8488. if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
  8489. s->done_service_req = TRUE;
  8490. }
  8491. if (!s->done_service_req) {
  8492. /*
  8493. * Request connection protocol directly, without authentication.
  8494. */
  8495. s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
  8496. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  8497. ssh2_pkt_send(ssh, s->pktout);
  8498. crWaitUntilV(pktin);
  8499. if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
  8500. s->we_are_in = TRUE; /* no auth required */
  8501. } else {
  8502. bombout(("Server refused service request"));
  8503. crStopV;
  8504. }
  8505. }
  8506. } else {
  8507. s->we_are_in = TRUE;
  8508. }
  8509. /* Arrange to be able to deal with any BANNERs that come in.
  8510. * (We do this now as packets may come in during the next bit.) */
  8511. bufchain_init(&ssh->banner);
  8512. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
  8513. ssh2_msg_userauth_banner;
  8514. /*
  8515. * Misc one-time setup for authentication.
  8516. */
  8517. s->publickey_blob = NULL;
  8518. if (!s->we_are_in) {
  8519. /*
  8520. * Load the public half of any configured public key file
  8521. * for later use.
  8522. */
  8523. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  8524. if (!filename_is_null(s->keyfile)) {
  8525. int keytype;
  8526. #ifdef _DEBUG
  8527. // To suppress CodeGuard warning
  8528. logeventf(ssh, MPEXT_BOM "Reading key file \"%s\"",
  8529. filename_to_str(s->keyfile));
  8530. #else
  8531. logeventf(ssh, MPEXT_BOM "Reading key file \"%.150s\"",
  8532. filename_to_str(s->keyfile));
  8533. #endif
  8534. keytype = key_type(s->keyfile);
  8535. if (keytype == SSH_KEYTYPE_SSH2 ||
  8536. keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
  8537. keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  8538. const char *error;
  8539. s->publickey_blob =
  8540. ssh2_userkey_loadpub(s->keyfile,
  8541. &s->publickey_algorithm,
  8542. &s->publickey_bloblen,
  8543. &s->publickey_comment, &error);
  8544. if (s->publickey_blob) {
  8545. s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
  8546. if (!s->privatekey_available)
  8547. logeventf(ssh, "Key file contains public key only");
  8548. s->privatekey_encrypted =
  8549. ssh2_userkey_encrypted(s->keyfile, NULL);
  8550. } else {
  8551. char *msgbuf;
  8552. logeventf(ssh, "Unable to load key (%s)",
  8553. error);
  8554. msgbuf = dupprintf(MPEXT_BOM "Unable to load key file "
  8555. "\"%.150s\" (%s)\r\n",
  8556. filename_to_str(s->keyfile),
  8557. error);
  8558. c_write_str(ssh, msgbuf);
  8559. sfree(msgbuf);
  8560. }
  8561. } else {
  8562. char *msgbuf;
  8563. logeventf(ssh, "Unable to use this key file (%s)",
  8564. key_type_to_str(keytype));
  8565. msgbuf = dupprintf(MPEXT_BOM "Unable to use key file \"%.150s\""
  8566. " (%s)\r\n",
  8567. filename_to_str(s->keyfile),
  8568. key_type_to_str(keytype));
  8569. c_write_str(ssh, msgbuf);
  8570. sfree(msgbuf);
  8571. s->publickey_blob = NULL;
  8572. }
  8573. }
  8574. /*
  8575. * Find out about any keys Pageant has (but if there's a
  8576. * public key configured, filter out all others).
  8577. */
  8578. s->nkeys = 0;
  8579. s->agent_response = NULL;
  8580. s->pkblob_in_agent = NULL;
  8581. if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
  8582. void *r;
  8583. logevent("Pageant is running. Requesting keys.");
  8584. /* Request the keys held by the agent. */
  8585. PUT_32BIT(s->agent_request, 1);
  8586. s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
  8587. ssh->auth_agent_query = agent_query(
  8588. s->agent_request, 5, &r, &s->agent_responselen,
  8589. ssh_agent_callback, ssh);
  8590. if (ssh->auth_agent_query) {
  8591. do {
  8592. crReturnV;
  8593. if (pktin) {
  8594. bombout(("Unexpected data from server while"
  8595. " waiting for agent response"));
  8596. crStopV;
  8597. }
  8598. } while (pktin || inlen > 0);
  8599. r = ssh->agent_response;
  8600. s->agent_responselen = ssh->agent_response_len;
  8601. }
  8602. s->agent_response = (unsigned char *) r;
  8603. if (s->agent_response && s->agent_responselen >= 5 &&
  8604. s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
  8605. int keyi;
  8606. unsigned char *p;
  8607. p = s->agent_response + 5;
  8608. s->nkeys = toint(GET_32BIT(p));
  8609. /*
  8610. * Vet the Pageant response to ensure that the key
  8611. * count and blob lengths make sense.
  8612. */
  8613. if (s->nkeys < 0) {
  8614. logeventf(ssh, "Pageant response contained a negative"
  8615. " key count %d", s->nkeys);
  8616. s->nkeys = 0;
  8617. goto done_agent_query;
  8618. } else {
  8619. unsigned char *q = p + 4;
  8620. int lenleft = s->agent_responselen - 5 - 4;
  8621. for (keyi = 0; keyi < s->nkeys; keyi++) {
  8622. int bloblen, commentlen;
  8623. if (lenleft < 4) {
  8624. logeventf(ssh, "Pageant response was truncated");
  8625. s->nkeys = 0;
  8626. goto done_agent_query;
  8627. }
  8628. bloblen = toint(GET_32BIT(q));
  8629. lenleft -= 4;
  8630. q += 4;
  8631. if (bloblen < 0 || bloblen > lenleft) {
  8632. logeventf(ssh, "Pageant response was truncated");
  8633. s->nkeys = 0;
  8634. goto done_agent_query;
  8635. }
  8636. lenleft -= bloblen;
  8637. q += bloblen;
  8638. commentlen = toint(GET_32BIT(q));
  8639. lenleft -= 4;
  8640. q += 4;
  8641. if (commentlen < 0 || commentlen > lenleft) {
  8642. logeventf(ssh, "Pageant response was truncated");
  8643. s->nkeys = 0;
  8644. goto done_agent_query;
  8645. }
  8646. lenleft -= commentlen;
  8647. q += commentlen;
  8648. }
  8649. }
  8650. p += 4;
  8651. logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
  8652. if (s->publickey_blob) {
  8653. /* See if configured key is in agent. */
  8654. for (keyi = 0; keyi < s->nkeys; keyi++) {
  8655. s->pklen = toint(GET_32BIT(p));
  8656. if (s->pklen == s->publickey_bloblen &&
  8657. !memcmp(p+4, s->publickey_blob,
  8658. s->publickey_bloblen)) {
  8659. logeventf(ssh, "Pageant key #%d matches "
  8660. "configured key file", keyi);
  8661. s->keyi = keyi;
  8662. s->pkblob_in_agent = p;
  8663. break;
  8664. }
  8665. p += 4 + s->pklen;
  8666. p += toint(GET_32BIT(p)) + 4; /* comment */
  8667. }
  8668. if (!s->pkblob_in_agent) {
  8669. logevent("Configured key file not in Pageant");
  8670. s->nkeys = 0;
  8671. }
  8672. }
  8673. } else {
  8674. logevent("Failed to get reply from Pageant");
  8675. }
  8676. done_agent_query:;
  8677. }
  8678. }
  8679. /*
  8680. * We repeat this whole loop, including the username prompt,
  8681. * until we manage a successful authentication. If the user
  8682. * types the wrong _password_, they can be sent back to the
  8683. * beginning to try another username, if this is configured on.
  8684. * (If they specify a username in the config, they are never
  8685. * asked, even if they do give a wrong password.)
  8686. *
  8687. * I think this best serves the needs of
  8688. *
  8689. * - the people who have no configuration, no keys, and just
  8690. * want to try repeated (username,password) pairs until they
  8691. * type both correctly
  8692. *
  8693. * - people who have keys and configuration but occasionally
  8694. * need to fall back to passwords
  8695. *
  8696. * - people with a key held in Pageant, who might not have
  8697. * logged in to a particular machine before; so they want to
  8698. * type a username, and then _either_ their key will be
  8699. * accepted, _or_ they will type a password. If they mistype
  8700. * the username they will want to be able to get back and
  8701. * retype it!
  8702. */
  8703. s->got_username = FALSE;
  8704. while (!s->we_are_in) {
  8705. /*
  8706. * Get a username.
  8707. */
  8708. if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
  8709. /*
  8710. * We got a username last time round this loop, and
  8711. * with change_username turned off we don't try to get
  8712. * it again.
  8713. */
  8714. } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
  8715. int ret; /* need not be kept over crReturn */
  8716. s->cur_prompt = new_prompts(ssh->frontend);
  8717. s->cur_prompt->to_server = TRUE;
  8718. s->cur_prompt->name = dupstr("SSH login name");
  8719. add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
  8720. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  8721. while (ret < 0) {
  8722. ssh->send_ok = 1;
  8723. crWaitUntilV(!pktin);
  8724. ret = get_userpass_input(s->cur_prompt, in, inlen);
  8725. ssh->send_ok = 0;
  8726. }
  8727. if (!ret) {
  8728. /*
  8729. * get_userpass_input() failed to get a username.
  8730. * Terminate.
  8731. */
  8732. free_prompts(s->cur_prompt);
  8733. ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
  8734. crStopV;
  8735. }
  8736. ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
  8737. free_prompts(s->cur_prompt);
  8738. } else {
  8739. char *stuff;
  8740. if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
  8741. stuff = dupprintf(MPEXT_BOM "Using username \"%s\".\r\n", ssh->username);
  8742. c_write_str(ssh, stuff);
  8743. sfree(stuff);
  8744. }
  8745. }
  8746. s->got_username = TRUE;
  8747. /*
  8748. * Send an authentication request using method "none": (a)
  8749. * just in case it succeeds, and (b) so that we know what
  8750. * authentication methods we can usefully try next.
  8751. */
  8752. ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
  8753. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  8754. ssh2_pkt_addstring(s->pktout, ssh->username);
  8755. ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
  8756. ssh2_pkt_addstring(s->pktout, "none"); /* method */
  8757. ssh2_pkt_send(ssh, s->pktout);
  8758. s->type = AUTH_TYPE_NONE;
  8759. s->gotit = FALSE;
  8760. s->we_are_in = FALSE;
  8761. s->tried_pubkey_config = FALSE;
  8762. s->kbd_inter_refused = FALSE;
  8763. /* Reset agent request state. */
  8764. s->done_agent = FALSE;
  8765. if (s->agent_response) {
  8766. if (s->pkblob_in_agent) {
  8767. s->agentp = s->pkblob_in_agent;
  8768. } else {
  8769. s->agentp = s->agent_response + 5 + 4;
  8770. s->keyi = 0;
  8771. }
  8772. }
  8773. while (1) {
  8774. char *methods = NULL;
  8775. int methlen = 0;
  8776. /*
  8777. * Wait for the result of the last authentication request.
  8778. */
  8779. if (!s->gotit)
  8780. crWaitUntilV(pktin);
  8781. /*
  8782. * Now is a convenient point to spew any banner material
  8783. * that we've accumulated. (This should ensure that when
  8784. * we exit the auth loop, we haven't any left to deal
  8785. * with.)
  8786. */
  8787. {
  8788. int size = bufchain_size(&ssh->banner);
  8789. /*
  8790. * Don't show the banner if we're operating in
  8791. * non-verbose non-interactive mode. (It's probably
  8792. * a script, which means nobody will read the
  8793. * banner _anyway_, and moreover the printing of
  8794. * the banner will screw up processing on the
  8795. * output of (say) plink.)
  8796. */
  8797. if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
  8798. char *banner = snewn(size, char);
  8799. bufchain_fetch(&ssh->banner, banner, size);
  8800. #ifdef MPEXT
  8801. display_banner(ssh->frontend, banner, size);
  8802. #endif
  8803. c_write_untrusted(ssh, banner, size);
  8804. sfree(banner);
  8805. }
  8806. bufchain_clear(&ssh->banner);
  8807. }
  8808. if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
  8809. logevent("Access granted");
  8810. s->we_are_in = s->userauth_success = TRUE;
  8811. break;
  8812. }
  8813. if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
  8814. bombout(("Strange packet received during authentication: "
  8815. "type %d", pktin->type));
  8816. crStopV;
  8817. }
  8818. s->gotit = FALSE;
  8819. /*
  8820. * OK, we're now sitting on a USERAUTH_FAILURE message, so
  8821. * we can look at the string in it and know what we can
  8822. * helpfully try next.
  8823. */
  8824. if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
  8825. ssh_pkt_getstring(pktin, &methods, &methlen);
  8826. if (!ssh2_pkt_getbool(pktin)) {
  8827. /*
  8828. * We have received an unequivocal Access
  8829. * Denied. This can translate to a variety of
  8830. * messages, or no message at all.
  8831. *
  8832. * For forms of authentication which are attempted
  8833. * implicitly, by which I mean without printing
  8834. * anything in the window indicating that we're
  8835. * trying them, we should never print 'Access
  8836. * denied'.
  8837. *
  8838. * If we do print a message saying that we're
  8839. * attempting some kind of authentication, it's OK
  8840. * to print a followup message saying it failed -
  8841. * but the message may sometimes be more specific
  8842. * than simply 'Access denied'.
  8843. *
  8844. * Additionally, if we'd just tried password
  8845. * authentication, we should break out of this
  8846. * whole loop so as to go back to the username
  8847. * prompt (iff we're configured to allow
  8848. * username change attempts).
  8849. */
  8850. if (s->type == AUTH_TYPE_NONE) {
  8851. /* do nothing */
  8852. } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
  8853. s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
  8854. if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
  8855. c_write_str(ssh, "Server refused our key\r\n");
  8856. logevent("Server refused our key");
  8857. } else if (s->type == AUTH_TYPE_PUBLICKEY) {
  8858. /* This _shouldn't_ happen except by a
  8859. * protocol bug causing client and server to
  8860. * disagree on what is a correct signature. */
  8861. c_write_str(ssh, "Server refused public-key signature"
  8862. " despite accepting key!\r\n");
  8863. logevent("Server refused public-key signature"
  8864. " despite accepting key!");
  8865. } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
  8866. /* quiet, so no c_write */
  8867. logevent("Server refused keyboard-interactive authentication");
  8868. } else if (s->type==AUTH_TYPE_GSSAPI) {
  8869. /* always quiet, so no c_write */
  8870. /* also, the code down in the GSSAPI block has
  8871. * already logged this in the Event Log */
  8872. } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
  8873. logevent("Keyboard-interactive authentication failed");
  8874. c_write_str(ssh, "Access denied\r\n");
  8875. } else {
  8876. assert(s->type == AUTH_TYPE_PASSWORD);
  8877. logevent("Password authentication failed");
  8878. c_write_str(ssh, "Access denied\r\n");
  8879. if (conf_get_int(ssh->conf, CONF_change_username)) {
  8880. /* XXX perhaps we should allow
  8881. * keyboard-interactive to do this too? */
  8882. s->we_are_in = FALSE;
  8883. break;
  8884. }
  8885. }
  8886. } else {
  8887. c_write_str(ssh, "Further authentication required\r\n");
  8888. logevent("Further authentication required");
  8889. }
  8890. #ifdef MPEXT
  8891. logeventf(ssh, "Server offered these authentication methods: %s", methods);
  8892. #endif
  8893. s->can_pubkey =
  8894. in_commasep_string("publickey", methods, methlen);
  8895. s->can_passwd =
  8896. in_commasep_string("password", methods, methlen);
  8897. s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
  8898. in_commasep_string("keyboard-interactive", methods, methlen);
  8899. #ifndef NO_GSSAPI
  8900. if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
  8901. in_commasep_string("gssapi-with-mic", methods, methlen)) {
  8902. /* Try loading the GSS libraries and see if we
  8903. * have any. */
  8904. if (!ssh->gsslibs)
  8905. ssh->gsslibs = ssh_gss_setup(ssh->conf, ssh->frontend); // MPEXT
  8906. s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
  8907. } else {
  8908. /* No point in even bothering to try to load the
  8909. * GSS libraries, if the user configuration and
  8910. * server aren't both prepared to attempt GSSAPI
  8911. * auth in the first place. */
  8912. s->can_gssapi = FALSE;
  8913. }
  8914. #endif
  8915. }
  8916. ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
  8917. if (s->can_pubkey && !s->done_agent && s->nkeys) {
  8918. /*
  8919. * Attempt public-key authentication using a key from Pageant.
  8920. */
  8921. ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
  8922. logeventf(ssh, "Trying Pageant key #%d", s->keyi);
  8923. /* Unpack key from agent response */
  8924. s->pklen = toint(GET_32BIT(s->agentp));
  8925. s->agentp += 4;
  8926. s->pkblob = (char *)s->agentp;
  8927. s->agentp += s->pklen;
  8928. s->alglen = toint(GET_32BIT(s->pkblob));
  8929. s->alg = s->pkblob + 4;
  8930. s->commentlen = toint(GET_32BIT(s->agentp));
  8931. s->agentp += 4;
  8932. s->commentp = (char *)s->agentp;
  8933. s->agentp += s->commentlen;
  8934. /* s->agentp now points at next key, if any */
  8935. /* See if server will accept it */
  8936. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  8937. ssh2_pkt_addstring(s->pktout, ssh->username);
  8938. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  8939. /* service requested */
  8940. ssh2_pkt_addstring(s->pktout, "publickey");
  8941. /* method */
  8942. ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
  8943. ssh2_pkt_addstring_start(s->pktout);
  8944. ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
  8945. ssh2_pkt_addstring_start(s->pktout);
  8946. ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
  8947. ssh2_pkt_send(ssh, s->pktout);
  8948. s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
  8949. crWaitUntilV(pktin);
  8950. if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
  8951. /* Offer of key refused. */
  8952. s->gotit = TRUE;
  8953. } else {
  8954. void *vret;
  8955. if (flags & FLAG_VERBOSE) {
  8956. c_write_str(ssh, "Authenticating with "
  8957. "public key \"");
  8958. c_write(ssh, s->commentp, s->commentlen);
  8959. c_write_str(ssh, "\" from agent\r\n");
  8960. }
  8961. /*
  8962. * Server is willing to accept the key.
  8963. * Construct a SIGN_REQUEST.
  8964. */
  8965. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  8966. ssh2_pkt_addstring(s->pktout, ssh->username);
  8967. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  8968. /* service requested */
  8969. ssh2_pkt_addstring(s->pktout, "publickey");
  8970. /* method */
  8971. ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
  8972. ssh2_pkt_addstring_start(s->pktout);
  8973. ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
  8974. ssh2_pkt_addstring_start(s->pktout);
  8975. ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
  8976. /* Ask agent for signature. */
  8977. s->siglen = s->pktout->length - 5 + 4 +
  8978. ssh->v2_session_id_len;
  8979. if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
  8980. s->siglen -= 4;
  8981. s->len = 1; /* message type */
  8982. s->len += 4 + s->pklen; /* key blob */
  8983. s->len += 4 + s->siglen; /* data to sign */
  8984. s->len += 4; /* flags */
  8985. s->agentreq = snewn(4 + s->len, char);
  8986. PUT_32BIT(s->agentreq, s->len);
  8987. s->q = s->agentreq + 4;
  8988. *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
  8989. PUT_32BIT(s->q, s->pklen);
  8990. s->q += 4;
  8991. memcpy(s->q, s->pkblob, s->pklen);
  8992. s->q += s->pklen;
  8993. PUT_32BIT(s->q, s->siglen);
  8994. s->q += 4;
  8995. /* Now the data to be signed... */
  8996. if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
  8997. PUT_32BIT(s->q, ssh->v2_session_id_len);
  8998. s->q += 4;
  8999. }
  9000. memcpy(s->q, ssh->v2_session_id,
  9001. ssh->v2_session_id_len);
  9002. s->q += ssh->v2_session_id_len;
  9003. memcpy(s->q, s->pktout->data + 5,
  9004. s->pktout->length - 5);
  9005. s->q += s->pktout->length - 5;
  9006. /* And finally the (zero) flags word. */
  9007. PUT_32BIT(s->q, 0);
  9008. ssh->auth_agent_query = agent_query(
  9009. s->agentreq, s->len + 4, &vret, &s->retlen,
  9010. ssh_agent_callback, ssh);
  9011. if (ssh->auth_agent_query) {
  9012. do {
  9013. crReturnV;
  9014. if (pktin) {
  9015. bombout(("Unexpected data from server"
  9016. " while waiting for agent"
  9017. " response"));
  9018. crStopV;
  9019. }
  9020. } while (pktin || inlen > 0);
  9021. vret = ssh->agent_response;
  9022. s->retlen = ssh->agent_response_len;
  9023. }
  9024. s->ret = vret;
  9025. sfree(s->agentreq);
  9026. if (s->ret) {
  9027. if (s->retlen >= 9 &&
  9028. s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
  9029. GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
  9030. logevent("Sending Pageant's response");
  9031. ssh2_add_sigblob(ssh, s->pktout,
  9032. s->pkblob, s->pklen,
  9033. s->ret + 9,
  9034. GET_32BIT(s->ret + 5));
  9035. ssh2_pkt_send(ssh, s->pktout);
  9036. s->type = AUTH_TYPE_PUBLICKEY;
  9037. #ifdef MPEXT
  9038. sfree(s->ret);
  9039. #endif
  9040. } else {
  9041. /* FIXME: less drastic response */
  9042. bombout(("Pageant failed to answer challenge"));
  9043. crStopV;
  9044. }
  9045. }
  9046. }
  9047. /* Do we have any keys left to try? */
  9048. if (s->pkblob_in_agent) {
  9049. s->done_agent = TRUE;
  9050. s->tried_pubkey_config = TRUE;
  9051. } else {
  9052. s->keyi++;
  9053. if (s->keyi >= s->nkeys)
  9054. s->done_agent = TRUE;
  9055. }
  9056. } else if (s->can_pubkey && s->publickey_blob &&
  9057. s->privatekey_available && !s->tried_pubkey_config) {
  9058. struct ssh2_userkey *key; /* not live over crReturn */
  9059. char *passphrase; /* not live over crReturn */
  9060. ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
  9061. s->tried_pubkey_config = TRUE;
  9062. /*
  9063. * Try the public key supplied in the configuration.
  9064. *
  9065. * First, offer the public blob to see if the server is
  9066. * willing to accept it.
  9067. */
  9068. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9069. ssh2_pkt_addstring(s->pktout, ssh->username);
  9070. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9071. /* service requested */
  9072. ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
  9073. ssh2_pkt_addbool(s->pktout, FALSE);
  9074. /* no signature included */
  9075. ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
  9076. ssh2_pkt_addstring_start(s->pktout);
  9077. ssh2_pkt_addstring_data(s->pktout,
  9078. (char *)s->publickey_blob,
  9079. s->publickey_bloblen);
  9080. ssh2_pkt_send(ssh, s->pktout);
  9081. logevent("Offered public key");
  9082. crWaitUntilV(pktin);
  9083. if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
  9084. /* Key refused. Give up. */
  9085. s->gotit = TRUE; /* reconsider message next loop */
  9086. s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
  9087. continue; /* process this new message */
  9088. }
  9089. logevent("Offer of public key accepted");
  9090. /*
  9091. * Actually attempt a serious authentication using
  9092. * the key.
  9093. */
  9094. if (flags & FLAG_VERBOSE) {
  9095. c_write_str(ssh, "Authenticating with public key \"");
  9096. c_write_str(ssh, s->publickey_comment);
  9097. c_write_str(ssh, "\"\r\n");
  9098. }
  9099. key = NULL;
  9100. while (!key) {
  9101. const char *error; /* not live over crReturn */
  9102. if (s->privatekey_encrypted) {
  9103. /*
  9104. * Get a passphrase from the user.
  9105. */
  9106. int ret; /* need not be kept over crReturn */
  9107. s->cur_prompt = new_prompts(ssh->frontend);
  9108. s->cur_prompt->to_server = FALSE;
  9109. s->cur_prompt->name = dupstr("SSH key passphrase");
  9110. add_prompt(s->cur_prompt,
  9111. dupprintf("Passphrase for key \"%.100s\": ",
  9112. s->publickey_comment),
  9113. FALSE);
  9114. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  9115. while (ret < 0) {
  9116. ssh->send_ok = 1;
  9117. crWaitUntilV(!pktin);
  9118. ret = get_userpass_input(s->cur_prompt,
  9119. in, inlen);
  9120. ssh->send_ok = 0;
  9121. }
  9122. if (!ret) {
  9123. /* Failed to get a passphrase. Terminate. */
  9124. free_prompts(s->cur_prompt);
  9125. ssh_disconnect(ssh, NULL,
  9126. "Unable to authenticate",
  9127. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  9128. TRUE);
  9129. crStopV;
  9130. }
  9131. passphrase =
  9132. dupstr(s->cur_prompt->prompts[0]->result);
  9133. free_prompts(s->cur_prompt);
  9134. } else {
  9135. passphrase = NULL; /* no passphrase needed */
  9136. }
  9137. /*
  9138. * Try decrypting the key.
  9139. */
  9140. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  9141. key = ssh2_load_userkey(s->keyfile, passphrase, &error);
  9142. if (passphrase) {
  9143. /* burn the evidence */
  9144. smemclr(passphrase, strlen(passphrase));
  9145. sfree(passphrase);
  9146. }
  9147. if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
  9148. if (passphrase &&
  9149. (key == SSH2_WRONG_PASSPHRASE)) {
  9150. c_write_str(ssh, "Wrong passphrase\r\n");
  9151. key = NULL;
  9152. /* and loop again */
  9153. } else {
  9154. c_write_str(ssh, "Unable to load private key (");
  9155. c_write_str(ssh, error);
  9156. c_write_str(ssh, ")\r\n");
  9157. key = NULL;
  9158. break; /* try something else */
  9159. }
  9160. }
  9161. }
  9162. if (key) {
  9163. unsigned char *pkblob, *sigblob, *sigdata;
  9164. int pkblob_len, sigblob_len, sigdata_len;
  9165. int p;
  9166. /*
  9167. * We have loaded the private key and the server
  9168. * has announced that it's willing to accept it.
  9169. * Hallelujah. Generate a signature and send it.
  9170. */
  9171. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9172. ssh2_pkt_addstring(s->pktout, ssh->username);
  9173. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9174. /* service requested */
  9175. ssh2_pkt_addstring(s->pktout, "publickey");
  9176. /* method */
  9177. ssh2_pkt_addbool(s->pktout, TRUE);
  9178. /* signature follows */
  9179. ssh2_pkt_addstring(s->pktout, key->alg->name);
  9180. pkblob = key->alg->public_blob(key->data,
  9181. &pkblob_len);
  9182. ssh2_pkt_addstring_start(s->pktout);
  9183. ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
  9184. pkblob_len);
  9185. /*
  9186. * The data to be signed is:
  9187. *
  9188. * string session-id
  9189. *
  9190. * followed by everything so far placed in the
  9191. * outgoing packet.
  9192. */
  9193. sigdata_len = s->pktout->length - 5 + 4 +
  9194. ssh->v2_session_id_len;
  9195. if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
  9196. sigdata_len -= 4;
  9197. sigdata = snewn(sigdata_len, unsigned char);
  9198. p = 0;
  9199. if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
  9200. PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
  9201. p += 4;
  9202. }
  9203. memcpy(sigdata+p, ssh->v2_session_id,
  9204. ssh->v2_session_id_len);
  9205. p += ssh->v2_session_id_len;
  9206. memcpy(sigdata+p, s->pktout->data + 5,
  9207. s->pktout->length - 5);
  9208. p += s->pktout->length - 5;
  9209. assert(p == sigdata_len);
  9210. sigblob = key->alg->sign(key->data, (char *)sigdata,
  9211. sigdata_len, &sigblob_len);
  9212. ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
  9213. sigblob, sigblob_len);
  9214. sfree(pkblob);
  9215. sfree(sigblob);
  9216. sfree(sigdata);
  9217. ssh2_pkt_send(ssh, s->pktout);
  9218. logevent("Sent public key signature");
  9219. s->type = AUTH_TYPE_PUBLICKEY;
  9220. key->alg->freekey(key->data);
  9221. sfree(key->comment);
  9222. sfree(key);
  9223. }
  9224. #ifndef NO_GSSAPI
  9225. } else if (s->can_gssapi && !s->tried_gssapi) {
  9226. /* GSSAPI Authentication */
  9227. int micoffset, len;
  9228. char *data;
  9229. Ssh_gss_buf mic;
  9230. #ifdef MPEXT
  9231. const char * fullhostname;
  9232. char *loghost;
  9233. #endif
  9234. s->type = AUTH_TYPE_GSSAPI;
  9235. s->tried_gssapi = TRUE;
  9236. s->gotit = TRUE;
  9237. ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
  9238. /*
  9239. * Pick the highest GSS library on the preference
  9240. * list.
  9241. */
  9242. {
  9243. int i, j;
  9244. s->gsslib = NULL;
  9245. for (i = 0; i < ngsslibs; i++) {
  9246. int want_id = conf_get_int_int(ssh->conf,
  9247. CONF_ssh_gsslist, i);
  9248. for (j = 0; j < ssh->gsslibs->nlibraries; j++)
  9249. if (ssh->gsslibs->libraries[j].id == want_id) {
  9250. s->gsslib = &ssh->gsslibs->libraries[j];
  9251. goto got_gsslib; /* double break */
  9252. }
  9253. }
  9254. got_gsslib:
  9255. /*
  9256. * We always expect to have found something in
  9257. * the above loop: we only came here if there
  9258. * was at least one viable GSS library, and the
  9259. * preference list should always mention
  9260. * everything and only change the order.
  9261. */
  9262. assert(s->gsslib);
  9263. }
  9264. if (s->gsslib->gsslogmsg)
  9265. logevent(s->gsslib->gsslogmsg);
  9266. /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
  9267. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9268. ssh2_pkt_addstring(s->pktout, ssh->username);
  9269. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9270. ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
  9271. logevent("Attempting GSSAPI authentication");
  9272. /* add mechanism info */
  9273. s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
  9274. /* number of GSSAPI mechanisms */
  9275. ssh2_pkt_adduint32(s->pktout,1);
  9276. /* length of OID + 2 */
  9277. ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
  9278. ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
  9279. /* length of OID */
  9280. ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
  9281. ssh_pkt_adddata(s->pktout, s->gss_buf.value,
  9282. s->gss_buf.length);
  9283. ssh2_pkt_send(ssh, s->pktout);
  9284. crWaitUntilV(pktin);
  9285. if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
  9286. logevent("GSSAPI authentication request refused");
  9287. continue;
  9288. }
  9289. /* check returned packet ... */
  9290. ssh_pkt_getstring(pktin, &data, &len);
  9291. s->gss_rcvtok.value = data;
  9292. s->gss_rcvtok.length = len;
  9293. if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
  9294. ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
  9295. ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
  9296. memcmp((char *)s->gss_rcvtok.value + 2,
  9297. s->gss_buf.value,s->gss_buf.length) ) {
  9298. logevent("GSSAPI authentication - wrong response from server");
  9299. continue;
  9300. }
  9301. /* now start running */
  9302. #ifdef MPEXT
  9303. fullhostname = ssh->fullhostname;
  9304. loghost = conf_get_str(ssh->conf, CONF_loghost);
  9305. if (loghost[0] != '\0')
  9306. {
  9307. fullhostname = loghost;
  9308. }
  9309. #endif
  9310. s->gss_stat = s->gsslib->import_name(s->gsslib,
  9311. #ifdef MPEXT
  9312. fullhostname,
  9313. #else
  9314. ssh->fullhostname,
  9315. #endif
  9316. &s->gss_srv_name);
  9317. if (s->gss_stat != SSH_GSS_OK) {
  9318. if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
  9319. logevent("GSSAPI import name failed - Bad service name");
  9320. else
  9321. logevent("GSSAPI import name failed");
  9322. continue;
  9323. }
  9324. /* fetch TGT into GSS engine */
  9325. s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
  9326. if (s->gss_stat != SSH_GSS_OK) {
  9327. logevent("GSSAPI authentication failed to get credentials");
  9328. s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
  9329. continue;
  9330. }
  9331. /* initial tokens are empty */
  9332. SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
  9333. SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
  9334. /* now enter the loop */
  9335. do {
  9336. s->gss_stat = s->gsslib->init_sec_context
  9337. (s->gsslib,
  9338. &s->gss_ctx,
  9339. s->gss_srv_name,
  9340. conf_get_int(ssh->conf, CONF_gssapifwd),
  9341. &s->gss_rcvtok,
  9342. &s->gss_sndtok);
  9343. if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
  9344. s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
  9345. logevent("GSSAPI authentication initialisation failed");
  9346. if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
  9347. &s->gss_buf) == SSH_GSS_OK) {
  9348. logevent(s->gss_buf.value);
  9349. sfree(s->gss_buf.value);
  9350. }
  9351. break;
  9352. }
  9353. logevent("GSSAPI authentication initialised");
  9354. /* Client and server now exchange tokens until GSSAPI
  9355. * no longer says CONTINUE_NEEDED */
  9356. if (s->gss_sndtok.length != 0) {
  9357. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
  9358. ssh_pkt_addstring_start(s->pktout);
  9359. ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
  9360. ssh2_pkt_send(ssh, s->pktout);
  9361. s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
  9362. }
  9363. if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
  9364. crWaitUntilV(pktin);
  9365. if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
  9366. logevent("GSSAPI authentication - bad server response");
  9367. s->gss_stat = SSH_GSS_FAILURE;
  9368. break;
  9369. }
  9370. ssh_pkt_getstring(pktin, &data, &len);
  9371. s->gss_rcvtok.value = data;
  9372. s->gss_rcvtok.length = len;
  9373. }
  9374. } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
  9375. if (s->gss_stat != SSH_GSS_OK) {
  9376. s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
  9377. s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
  9378. continue;
  9379. }
  9380. logevent("GSSAPI authentication loop finished OK");
  9381. /* Now send the MIC */
  9382. s->pktout = ssh2_pkt_init(0);
  9383. micoffset = s->pktout->length;
  9384. ssh_pkt_addstring_start(s->pktout);
  9385. ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
  9386. ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
  9387. ssh_pkt_addstring(s->pktout, ssh->username);
  9388. ssh_pkt_addstring(s->pktout, "ssh-connection");
  9389. ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
  9390. s->gss_buf.value = (char *)s->pktout->data + micoffset;
  9391. s->gss_buf.length = s->pktout->length - micoffset;
  9392. s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
  9393. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
  9394. ssh_pkt_addstring_start(s->pktout);
  9395. ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
  9396. ssh2_pkt_send(ssh, s->pktout);
  9397. s->gsslib->free_mic(s->gsslib, &mic);
  9398. s->gotit = FALSE;
  9399. s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
  9400. s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
  9401. continue;
  9402. #endif
  9403. } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
  9404. /*
  9405. * Keyboard-interactive authentication.
  9406. */
  9407. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
  9408. ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
  9409. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9410. ssh2_pkt_addstring(s->pktout, ssh->username);
  9411. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9412. /* service requested */
  9413. ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
  9414. /* method */
  9415. ssh2_pkt_addstring(s->pktout, ""); /* lang */
  9416. ssh2_pkt_addstring(s->pktout, ""); /* submethods */
  9417. ssh2_pkt_send(ssh, s->pktout);
  9418. logevent("Attempting keyboard-interactive authentication");
  9419. crWaitUntilV(pktin);
  9420. if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
  9421. /* Server is not willing to do keyboard-interactive
  9422. * at all (or, bizarrely but legally, accepts the
  9423. * user without actually issuing any prompts).
  9424. * Give up on it entirely. */
  9425. s->gotit = TRUE;
  9426. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
  9427. s->kbd_inter_refused = TRUE; /* don't try it again */
  9428. continue;
  9429. }
  9430. /*
  9431. * Loop while the server continues to send INFO_REQUESTs.
  9432. */
  9433. while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
  9434. char *name, *inst, *lang;
  9435. int name_len, inst_len, lang_len;
  9436. int i;
  9437. /*
  9438. * We've got a fresh USERAUTH_INFO_REQUEST.
  9439. * Get the preamble and start building a prompt.
  9440. */
  9441. ssh_pkt_getstring(pktin, &name, &name_len);
  9442. ssh_pkt_getstring(pktin, &inst, &inst_len);
  9443. ssh_pkt_getstring(pktin, &lang, &lang_len);
  9444. s->cur_prompt = new_prompts(ssh->frontend);
  9445. s->cur_prompt->to_server = TRUE;
  9446. /*
  9447. * Get any prompt(s) from the packet.
  9448. */
  9449. s->num_prompts = ssh_pkt_getuint32(pktin);
  9450. for (i = 0; i < s->num_prompts; i++) {
  9451. char *prompt;
  9452. int prompt_len;
  9453. int echo;
  9454. static char noprompt[] =
  9455. "<server failed to send prompt>: ";
  9456. ssh_pkt_getstring(pktin, &prompt, &prompt_len);
  9457. echo = ssh2_pkt_getbool(pktin);
  9458. if (!prompt_len) {
  9459. prompt = noprompt;
  9460. prompt_len = lenof(noprompt)-1;
  9461. }
  9462. add_prompt(s->cur_prompt,
  9463. dupprintf("%.*s", prompt_len, prompt),
  9464. echo);
  9465. }
  9466. if (name_len) {
  9467. /* FIXME: better prefix to distinguish from
  9468. * local prompts? */
  9469. s->cur_prompt->name =
  9470. dupprintf("SSH server: %.*s", name_len, name);
  9471. s->cur_prompt->name_reqd = TRUE;
  9472. } else {
  9473. s->cur_prompt->name =
  9474. dupstr("SSH server authentication");
  9475. s->cur_prompt->name_reqd = FALSE;
  9476. }
  9477. /* We add a prefix to try to make it clear that a prompt
  9478. * has come from the server.
  9479. * FIXME: ugly to print "Using..." in prompt _every_
  9480. * time round. Can this be done more subtly? */
  9481. /* Special case: for reasons best known to themselves,
  9482. * some servers send k-i requests with no prompts and
  9483. * nothing to display. Keep quiet in this case. */
  9484. if (s->num_prompts || name_len || inst_len) {
  9485. s->cur_prompt->instruction =
  9486. dupprintf("Using keyboard-interactive authentication.%s%.*s",
  9487. inst_len ? "\n" : "", inst_len, inst);
  9488. s->cur_prompt->instr_reqd = TRUE;
  9489. } else {
  9490. s->cur_prompt->instr_reqd = FALSE;
  9491. }
  9492. /*
  9493. * Display any instructions, and get the user's
  9494. * response(s).
  9495. */
  9496. {
  9497. int ret; /* not live over crReturn */
  9498. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  9499. while (ret < 0) {
  9500. ssh->send_ok = 1;
  9501. crWaitUntilV(!pktin);
  9502. ret = get_userpass_input(s->cur_prompt, in, inlen);
  9503. ssh->send_ok = 0;
  9504. }
  9505. if (!ret) {
  9506. /*
  9507. * Failed to get responses. Terminate.
  9508. */
  9509. free_prompts(s->cur_prompt);
  9510. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  9511. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  9512. TRUE);
  9513. crStopV;
  9514. }
  9515. }
  9516. /*
  9517. * Send the response(s) to the server.
  9518. */
  9519. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
  9520. ssh2_pkt_adduint32(s->pktout, s->num_prompts);
  9521. for (i=0; i < s->num_prompts; i++) {
  9522. ssh2_pkt_addstring(s->pktout,
  9523. s->cur_prompt->prompts[i]->result);
  9524. }
  9525. ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
  9526. /*
  9527. * Free the prompts structure from this iteration.
  9528. * If there's another, a new one will be allocated
  9529. * when we return to the top of this while loop.
  9530. */
  9531. free_prompts(s->cur_prompt);
  9532. /*
  9533. * Get the next packet in case it's another
  9534. * INFO_REQUEST.
  9535. */
  9536. crWaitUntilV(pktin);
  9537. }
  9538. /*
  9539. * We should have SUCCESS or FAILURE now.
  9540. */
  9541. s->gotit = TRUE;
  9542. } else if (s->can_passwd) {
  9543. /*
  9544. * Plain old password authentication.
  9545. */
  9546. int ret; /* not live over crReturn */
  9547. int changereq_first_time; /* not live over crReturn */
  9548. ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
  9549. #ifdef MPEXT
  9550. s->change_password = conf_get_int(ssh->conf, CONF_change_password);
  9551. if (s->change_password != 0)
  9552. {
  9553. s->password = dupstr("");
  9554. s->type = AUTH_TYPE_PASSWORD;
  9555. }
  9556. else
  9557. {
  9558. /* no indentation to ease merges */
  9559. #endif
  9560. s->cur_prompt = new_prompts(ssh->frontend);
  9561. s->cur_prompt->to_server = TRUE;
  9562. s->cur_prompt->name = dupstr("SSH password");
  9563. #ifdef _DEBUG
  9564. // To suppress CodeGuard warning
  9565. add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
  9566. #else
  9567. add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
  9568. #endif
  9569. ssh->username,
  9570. ssh->savedhost),
  9571. FALSE);
  9572. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  9573. while (ret < 0) {
  9574. ssh->send_ok = 1;
  9575. crWaitUntilV(!pktin);
  9576. ret = get_userpass_input(s->cur_prompt, in, inlen);
  9577. ssh->send_ok = 0;
  9578. }
  9579. if (!ret) {
  9580. /*
  9581. * Failed to get responses. Terminate.
  9582. */
  9583. free_prompts(s->cur_prompt);
  9584. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  9585. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  9586. TRUE);
  9587. crStopV;
  9588. }
  9589. /*
  9590. * Squirrel away the password. (We may need it later if
  9591. * asked to change it.)
  9592. */
  9593. s->password = dupstr(s->cur_prompt->prompts[0]->result);
  9594. free_prompts(s->cur_prompt);
  9595. /*
  9596. * Send the password packet.
  9597. *
  9598. * We pad out the password packet to 256 bytes to make
  9599. * it harder for an attacker to find the length of the
  9600. * user's password.
  9601. *
  9602. * Anyone using a password longer than 256 bytes
  9603. * probably doesn't have much to worry about from
  9604. * people who find out how long their password is!
  9605. */
  9606. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9607. ssh2_pkt_addstring(s->pktout, ssh->username);
  9608. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9609. /* service requested */
  9610. ssh2_pkt_addstring(s->pktout, "password");
  9611. ssh2_pkt_addbool(s->pktout, FALSE);
  9612. ssh2_pkt_addstring(s->pktout, s->password);
  9613. ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
  9614. logevent("Sent password");
  9615. s->type = AUTH_TYPE_PASSWORD;
  9616. /*
  9617. * Wait for next packet, in case it's a password change
  9618. * request.
  9619. */
  9620. crWaitUntilV(pktin);
  9621. #ifdef MPEXT
  9622. }
  9623. #endif
  9624. changereq_first_time = TRUE;
  9625. while ((pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ)
  9626. #ifdef MPEXT
  9627. || (s->change_password != 0)
  9628. #endif
  9629. ) {
  9630. /*
  9631. * We're being asked for a new password
  9632. * (perhaps not for the first time).
  9633. * Loop until the server accepts it.
  9634. */
  9635. int got_new = FALSE; /* not live over crReturn */
  9636. char *prompt; /* not live over crReturn */
  9637. int prompt_len; /* not live over crReturn */
  9638. #ifdef MPEXT
  9639. if (s->change_password == 0)
  9640. #endif
  9641. {
  9642. const char *msg;
  9643. if (changereq_first_time)
  9644. msg = "Server requested password change";
  9645. else
  9646. msg = "Server rejected new password";
  9647. logevent(msg);
  9648. c_write_str(ssh, msg);
  9649. c_write_str(ssh, "\r\n");
  9650. }
  9651. #ifdef MPEXT
  9652. s->change_password = 0;
  9653. #endif
  9654. ssh_pkt_getstring(pktin, &prompt, &prompt_len);
  9655. s->cur_prompt = new_prompts(ssh->frontend);
  9656. s->cur_prompt->to_server = TRUE;
  9657. s->cur_prompt->name = dupstr("New SSH password");
  9658. s->cur_prompt->instruction =
  9659. dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
  9660. s->cur_prompt->instr_reqd = TRUE;
  9661. /*
  9662. * There's no explicit requirement in the protocol
  9663. * for the "old" passwords in the original and
  9664. * password-change messages to be the same, and
  9665. * apparently some Cisco kit supports password change
  9666. * by the user entering a blank password originally
  9667. * and the real password subsequently, so,
  9668. * reluctantly, we prompt for the old password again.
  9669. *
  9670. * (On the other hand, some servers don't even bother
  9671. * to check this field.)
  9672. */
  9673. add_prompt(s->cur_prompt,
  9674. dupstr("Current password (blank for previously entered password): "),
  9675. FALSE);
  9676. add_prompt(s->cur_prompt, dupstr("Enter new password: "),
  9677. FALSE);
  9678. add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
  9679. FALSE);
  9680. /*
  9681. * Loop until the user manages to enter the same
  9682. * password twice.
  9683. */
  9684. while (!got_new) {
  9685. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  9686. while (ret < 0) {
  9687. ssh->send_ok = 1;
  9688. crWaitUntilV(!pktin);
  9689. ret = get_userpass_input(s->cur_prompt, in, inlen);
  9690. ssh->send_ok = 0;
  9691. }
  9692. if (!ret) {
  9693. /*
  9694. * Failed to get responses. Terminate.
  9695. */
  9696. /* burn the evidence */
  9697. free_prompts(s->cur_prompt);
  9698. smemclr(s->password, strlen(s->password));
  9699. sfree(s->password);
  9700. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  9701. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  9702. TRUE);
  9703. crStopV;
  9704. }
  9705. /*
  9706. * If the user specified a new original password
  9707. * (IYSWIM), overwrite any previously specified
  9708. * one.
  9709. * (A side effect is that the user doesn't have to
  9710. * re-enter it if they louse up the new password.)
  9711. */
  9712. if (s->cur_prompt->prompts[0]->result[0]) {
  9713. smemclr(s->password, strlen(s->password));
  9714. /* burn the evidence */
  9715. sfree(s->password);
  9716. s->password =
  9717. dupstr(s->cur_prompt->prompts[0]->result);
  9718. }
  9719. /*
  9720. * Check the two new passwords match.
  9721. */
  9722. got_new = (strcmp(s->cur_prompt->prompts[1]->result,
  9723. s->cur_prompt->prompts[2]->result)
  9724. == 0);
  9725. if (!got_new)
  9726. /* They don't. Silly user. */
  9727. c_write_str(ssh, "Passwords do not match\r\n");
  9728. }
  9729. /*
  9730. * Send the new password (along with the old one).
  9731. * (see above for padding rationale)
  9732. */
  9733. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9734. ssh2_pkt_addstring(s->pktout, ssh->username);
  9735. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9736. /* service requested */
  9737. ssh2_pkt_addstring(s->pktout, "password");
  9738. ssh2_pkt_addbool(s->pktout, TRUE);
  9739. ssh2_pkt_addstring(s->pktout, s->password);
  9740. ssh2_pkt_addstring(s->pktout,
  9741. s->cur_prompt->prompts[1]->result);
  9742. free_prompts(s->cur_prompt);
  9743. ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
  9744. logevent("Sent new password");
  9745. /*
  9746. * Now see what the server has to say about it.
  9747. * (If it's CHANGEREQ again, it's not happy with the
  9748. * new password.)
  9749. */
  9750. crWaitUntilV(pktin);
  9751. changereq_first_time = FALSE;
  9752. }
  9753. /*
  9754. * We need to reexamine the current pktin at the top
  9755. * of the loop. Either:
  9756. * - we weren't asked to change password at all, in
  9757. * which case it's a SUCCESS or FAILURE with the
  9758. * usual meaning
  9759. * - we sent a new password, and the server was
  9760. * either OK with it (SUCCESS or FAILURE w/partial
  9761. * success) or unhappy with the _old_ password
  9762. * (FAILURE w/o partial success)
  9763. * In any of these cases, we go back to the top of
  9764. * the loop and start again.
  9765. */
  9766. s->gotit = TRUE;
  9767. /*
  9768. * We don't need the old password any more, in any
  9769. * case. Burn the evidence.
  9770. */
  9771. smemclr(s->password, strlen(s->password));
  9772. sfree(s->password);
  9773. } else {
  9774. char *str = dupprintf("No supported authentication methods available"
  9775. " (server sent: %.*s)",
  9776. methlen, methods);
  9777. ssh_disconnect(ssh, str,
  9778. "No supported authentication methods available",
  9779. SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
  9780. FALSE);
  9781. sfree(str);
  9782. crStopV;
  9783. }
  9784. }
  9785. }
  9786. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
  9787. /* Clear up various bits and pieces from authentication. */
  9788. if (s->publickey_blob) {
  9789. sfree(s->publickey_algorithm);
  9790. sfree(s->publickey_blob);
  9791. sfree(s->publickey_comment);
  9792. }
  9793. if (s->agent_response)
  9794. sfree(s->agent_response);
  9795. if (s->userauth_success && !ssh->bare_connection) {
  9796. /*
  9797. * We've just received USERAUTH_SUCCESS, and we haven't sent any
  9798. * packets since. Signal the transport layer to consider enacting
  9799. * delayed compression.
  9800. *
  9801. * (Relying on we_are_in is not sufficient, as
  9802. * draft-miller-secsh-compression-delayed is quite clear that it
  9803. * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
  9804. * become set for other reasons.)
  9805. */
  9806. do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
  9807. }
  9808. ssh->channels = newtree234(ssh_channelcmp);
  9809. /*
  9810. * Set up handlers for some connection protocol messages, so we
  9811. * don't have to handle them repeatedly in this coroutine.
  9812. */
  9813. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
  9814. ssh2_msg_channel_window_adjust;
  9815. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
  9816. ssh2_msg_global_request;
  9817. /*
  9818. * Create the main session channel.
  9819. */
  9820. if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
  9821. ssh->mainchan = NULL;
  9822. } else {
  9823. ssh->mainchan = snew(struct ssh_channel);
  9824. ssh->mainchan->ssh = ssh;
  9825. ssh_channel_init(ssh->mainchan);
  9826. if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
  9827. /*
  9828. * Just start a direct-tcpip channel and use it as the main
  9829. * channel.
  9830. */
  9831. ssh_send_port_open(ssh->mainchan,
  9832. conf_get_str(ssh->conf, CONF_ssh_nc_host),
  9833. conf_get_int(ssh->conf, CONF_ssh_nc_port),
  9834. "main channel");
  9835. ssh->ncmode = TRUE;
  9836. } else {
  9837. s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
  9838. logevent("Opening session as main channel");
  9839. ssh2_pkt_send(ssh, s->pktout);
  9840. ssh->ncmode = FALSE;
  9841. }
  9842. crWaitUntilV(pktin);
  9843. if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
  9844. pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE) {
  9845. bombout(("Server sent strange packet %d in response to main "
  9846. "channel open request", pktin->type));
  9847. crStopV;
  9848. }
  9849. if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
  9850. bombout(("Server's response to main channel open cited wrong"
  9851. " channel number"));
  9852. crStopV;
  9853. }
  9854. if (pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
  9855. char *errtext = ssh2_channel_open_failure_error_text(pktin);
  9856. bombout(("Server refused to open main channel: %s", errtext));
  9857. sfree(errtext);
  9858. crStopV;
  9859. }
  9860. ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
  9861. ssh->mainchan->halfopen = FALSE;
  9862. ssh->mainchan->type = CHAN_MAINSESSION;
  9863. ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
  9864. ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
  9865. update_specials_menu(ssh->frontend);
  9866. logevent("Opened main channel");
  9867. }
  9868. /*
  9869. * Now we have a channel, make dispatch table entries for
  9870. * general channel-based messages.
  9871. */
  9872. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
  9873. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
  9874. ssh2_msg_channel_data;
  9875. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
  9876. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
  9877. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
  9878. ssh2_msg_channel_open_confirmation;
  9879. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
  9880. ssh2_msg_channel_open_failure;
  9881. ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
  9882. ssh2_msg_channel_request;
  9883. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
  9884. ssh2_msg_channel_open;
  9885. ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
  9886. ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
  9887. /*
  9888. * Now the connection protocol is properly up and running, with
  9889. * all those dispatch table entries, so it's safe to let
  9890. * downstreams start trying to open extra channels through us.
  9891. */
  9892. if (ssh->connshare)
  9893. share_activate(ssh->connshare, ssh->v_s);
  9894. if (ssh->mainchan && ssh_is_simple(ssh)) {
  9895. /*
  9896. * This message indicates to the server that we promise
  9897. * not to try to run any other channel in parallel with
  9898. * this one, so it's safe for it to advertise a very large
  9899. * window and leave the flow control to TCP.
  9900. */
  9901. s->pktout = ssh2_chanreq_init(ssh->mainchan,
  9902. "[email protected]",
  9903. NULL, NULL);
  9904. ssh2_pkt_send(ssh, s->pktout);
  9905. }
  9906. /*
  9907. * Enable port forwardings.
  9908. */
  9909. ssh_setup_portfwd(ssh, ssh->conf);
  9910. if (ssh->mainchan && !ssh->ncmode) {
  9911. /*
  9912. * Send the CHANNEL_REQUESTS for the main session channel.
  9913. * Each one is handled by its own little asynchronous
  9914. * co-routine.
  9915. */
  9916. /* Potentially enable X11 forwarding. */
  9917. if (conf_get_int(ssh->conf, CONF_x11_forward)) {
  9918. ssh->x11disp =
  9919. x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
  9920. ssh->conf);
  9921. if (!ssh->x11disp) {
  9922. /* FIXME: return an error message from x11_setup_display */
  9923. logevent("X11 forwarding not enabled: unable to"
  9924. " initialise X display");
  9925. } else {
  9926. ssh->x11auth = x11_invent_fake_auth
  9927. (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
  9928. ssh->x11auth->disp = ssh->x11disp;
  9929. ssh2_setup_x11(ssh->mainchan, NULL, NULL);
  9930. }
  9931. }
  9932. /* Potentially enable agent forwarding. */
  9933. if (ssh_agent_forwarding_permitted(ssh))
  9934. ssh2_setup_agent(ssh->mainchan, NULL, NULL);
  9935. /* Now allocate a pty for the session. */
  9936. if (!conf_get_int(ssh->conf, CONF_nopty))
  9937. ssh2_setup_pty(ssh->mainchan, NULL, NULL);
  9938. /* Send environment variables. */
  9939. ssh2_setup_env(ssh->mainchan, NULL, NULL);
  9940. /*
  9941. * Start a shell or a remote command. We may have to attempt
  9942. * this twice if the config data has provided a second choice
  9943. * of command.
  9944. */
  9945. while (1) {
  9946. int subsys;
  9947. char *cmd;
  9948. if (ssh->fallback_cmd) {
  9949. subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
  9950. cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
  9951. } else {
  9952. subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
  9953. cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
  9954. }
  9955. if (subsys) {
  9956. s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
  9957. ssh2_response_authconn, NULL);
  9958. ssh2_pkt_addstring(s->pktout, cmd);
  9959. } else if (*cmd) {
  9960. s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
  9961. ssh2_response_authconn, NULL);
  9962. ssh2_pkt_addstring(s->pktout, cmd);
  9963. } else {
  9964. s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
  9965. ssh2_response_authconn, NULL);
  9966. }
  9967. ssh2_pkt_send(ssh, s->pktout);
  9968. crWaitUntilV(pktin);
  9969. if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
  9970. if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
  9971. bombout(("Unexpected response to shell/command request:"
  9972. " packet type %d", pktin->type));
  9973. crStopV;
  9974. }
  9975. /*
  9976. * We failed to start the command. If this is the
  9977. * fallback command, we really are finished; if it's
  9978. * not, and if the fallback command exists, try falling
  9979. * back to it before complaining.
  9980. */
  9981. if (!ssh->fallback_cmd &&
  9982. (*conf_get_str(ssh->conf, CONF_remote_cmd2)
  9983. #ifdef MPEXT
  9984. ||
  9985. conf_get_int(ssh->conf, CONF_force_remote_cmd2)
  9986. #endif
  9987. )
  9988. ) {
  9989. logevent("Primary command failed; attempting fallback");
  9990. ssh->fallback_cmd = TRUE;
  9991. continue;
  9992. }
  9993. bombout(("Server refused to start a shell/command"));
  9994. crStopV;
  9995. } else {
  9996. logevent("Started a shell/command");
  9997. }
  9998. break;
  9999. }
  10000. } else {
  10001. ssh->editing = ssh->echoing = TRUE;
  10002. }
  10003. ssh->state = SSH_STATE_SESSION;
  10004. if (ssh->size_needed)
  10005. ssh_size(ssh, ssh->term_width, ssh->term_height);
  10006. if (ssh->eof_needed)
  10007. ssh_special(ssh, TS_EOF);
  10008. /*
  10009. * Transfer data!
  10010. */
  10011. if (ssh->ldisc)
  10012. ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
  10013. if (ssh->mainchan)
  10014. ssh->send_ok = 1;
  10015. while (1) {
  10016. crReturnV;
  10017. if (pktin) {
  10018. /*
  10019. * _All_ the connection-layer packets we expect to
  10020. * receive are now handled by the dispatch table.
  10021. * Anything that reaches here must be bogus.
  10022. */
  10023. bombout(("Strange packet received: type %d", pktin->type));
  10024. crStopV;
  10025. } else if (ssh->mainchan) {
  10026. /*
  10027. * We have spare data. Add it to the channel buffer.
  10028. */
  10029. ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
  10030. }
  10031. }
  10032. crFinishV;
  10033. }
  10034. /*
  10035. * Handlers for SSH-2 messages that might arrive at any moment.
  10036. */
  10037. static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
  10038. {
  10039. /* log reason code in disconnect message */
  10040. char *buf, *msg;
  10041. int reason, msglen;
  10042. reason = ssh_pkt_getuint32(pktin);
  10043. ssh_pkt_getstring(pktin, &msg, &msglen);
  10044. if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
  10045. buf = dupprintf("Received disconnect message (%s)",
  10046. ssh2_disconnect_reasons[reason]);
  10047. } else {
  10048. buf = dupprintf("Received disconnect message (unknown"
  10049. " type %d)", reason);
  10050. }
  10051. logevent(buf);
  10052. sfree(buf);
  10053. buf = dupprintf("Disconnection message text: %.*s",
  10054. msglen, NULLTOEMPTY(msg));
  10055. logevent(buf);
  10056. bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
  10057. reason,
  10058. (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
  10059. ssh2_disconnect_reasons[reason] : "unknown",
  10060. msglen, NULLTOEMPTY(msg)));
  10061. sfree(buf);
  10062. }
  10063. static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
  10064. {
  10065. /* log the debug message */
  10066. char *msg;
  10067. int msglen;
  10068. /* XXX maybe we should actually take notice of the return value */
  10069. ssh2_pkt_getbool(pktin);
  10070. ssh_pkt_getstring(pktin, &msg, &msglen);
  10071. logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
  10072. }
  10073. static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
  10074. {
  10075. do_ssh2_transport(ssh, NULL, 0, pktin);
  10076. }
  10077. /*
  10078. * Called if we receive a packet that isn't allowed by the protocol.
  10079. * This only applies to packets whose meaning PuTTY understands.
  10080. * Entirely unknown packets are handled below.
  10081. */
  10082. static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
  10083. {
  10084. char *buf = dupprintf("Server protocol violation: unexpected %s packet",
  10085. ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
  10086. pktin->type));
  10087. ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
  10088. sfree(buf);
  10089. }
  10090. static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
  10091. {
  10092. struct Packet *pktout;
  10093. pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
  10094. ssh2_pkt_adduint32(pktout, pktin->sequence);
  10095. /*
  10096. * UNIMPLEMENTED messages MUST appear in the same order as the
  10097. * messages they respond to. Hence, never queue them.
  10098. */
  10099. ssh2_pkt_send_noqueue(ssh, pktout);
  10100. }
  10101. /*
  10102. * Handle the top-level SSH-2 protocol.
  10103. */
  10104. static void ssh2_protocol_setup(Ssh ssh)
  10105. {
  10106. int i;
  10107. /*
  10108. * Most messages cause SSH2_MSG_UNIMPLEMENTED.
  10109. */
  10110. for (i = 0; i < 256; i++)
  10111. ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
  10112. /*
  10113. * Initially, we only accept transport messages (and a few generic
  10114. * ones). do_ssh2_authconn will add more when it starts.
  10115. * Messages that are understood but not currently acceptable go to
  10116. * ssh2_msg_unexpected.
  10117. */
  10118. ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
  10119. ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
  10120. ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
  10121. ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
  10122. ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
  10123. ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
  10124. ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
  10125. /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
  10126. /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
  10127. ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
  10128. ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
  10129. ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
  10130. ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
  10131. ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
  10132. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
  10133. ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
  10134. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
  10135. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
  10136. ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
  10137. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
  10138. ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
  10139. ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
  10140. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
  10141. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
  10142. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
  10143. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
  10144. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
  10145. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
  10146. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
  10147. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
  10148. ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
  10149. ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
  10150. ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
  10151. /*
  10152. * These messages have a special handler from the start.
  10153. */
  10154. ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
  10155. ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
  10156. ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
  10157. }
  10158. static void ssh2_bare_connection_protocol_setup(Ssh ssh)
  10159. {
  10160. int i;
  10161. /*
  10162. * Most messages cause SSH2_MSG_UNIMPLEMENTED.
  10163. */
  10164. for (i = 0; i < 256; i++)
  10165. ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
  10166. /*
  10167. * Initially, we set all ssh-connection messages to 'unexpected';
  10168. * do_ssh2_authconn will fill things in properly. We also handle a
  10169. * couple of messages from the transport protocol which aren't
  10170. * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
  10171. * DISCONNECT).
  10172. */
  10173. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
  10174. ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
  10175. ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
  10176. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
  10177. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
  10178. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
  10179. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
  10180. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
  10181. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
  10182. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
  10183. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
  10184. ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
  10185. ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
  10186. ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
  10187. ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
  10188. /*
  10189. * These messages have a special handler from the start.
  10190. */
  10191. ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
  10192. ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
  10193. ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
  10194. }
  10195. static void ssh2_timer(void *ctx, unsigned long now)
  10196. {
  10197. Ssh ssh = (Ssh)ctx;
  10198. if (ssh->state == SSH_STATE_CLOSED)
  10199. return;
  10200. if (!ssh->kex_in_progress && !ssh->bare_connection &&
  10201. conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
  10202. #ifdef MPEXT
  10203. // our call from call_ssh_timer() does not guarantee the `now` to be exactly as scheduled
  10204. (now >= ssh->next_rekey)) {
  10205. #else
  10206. now == ssh->next_rekey) {
  10207. #endif
  10208. do_ssh2_transport(ssh, "timeout", -1, NULL);
  10209. }
  10210. }
  10211. static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
  10212. struct Packet *pktin)
  10213. {
  10214. const unsigned char *in = (const unsigned char *)vin;
  10215. if (ssh->state == SSH_STATE_CLOSED)
  10216. return;
  10217. if (pktin) {
  10218. ssh->incoming_data_size += pktin->encrypted_len;
  10219. if (!ssh->kex_in_progress &&
  10220. ssh->max_data_size != 0 &&
  10221. ssh->incoming_data_size > ssh->max_data_size)
  10222. do_ssh2_transport(ssh, "too much data received", -1, NULL);
  10223. }
  10224. if (pktin)
  10225. ssh->packet_dispatch[pktin->type](ssh, pktin);
  10226. else if (!ssh->protocol_initial_phase_done)
  10227. do_ssh2_transport(ssh, in, inlen, pktin);
  10228. else
  10229. do_ssh2_authconn(ssh, in, inlen, pktin);
  10230. }
  10231. static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
  10232. struct Packet *pktin)
  10233. {
  10234. const unsigned char *in = (const unsigned char *)vin;
  10235. if (ssh->state == SSH_STATE_CLOSED)
  10236. return;
  10237. if (pktin)
  10238. ssh->packet_dispatch[pktin->type](ssh, pktin);
  10239. else
  10240. do_ssh2_authconn(ssh, in, inlen, pktin);
  10241. }
  10242. static void ssh_cache_conf_values(Ssh ssh)
  10243. {
  10244. ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
  10245. }
  10246. /*
  10247. * Called to set up the connection.
  10248. *
  10249. * Returns an error message, or NULL on success.
  10250. */
  10251. static const char *ssh_init(void *frontend_handle, void **backend_handle,
  10252. Conf *conf,
  10253. const char *host, int port, char **realhost,
  10254. int nodelay, int keepalive)
  10255. {
  10256. const char *p;
  10257. Ssh ssh;
  10258. ssh = snew(struct ssh_tag);
  10259. ssh->conf = conf_copy(conf);
  10260. ssh_cache_conf_values(ssh);
  10261. ssh->version = 0; /* when not ready yet */
  10262. ssh->s = NULL;
  10263. ssh->cipher = NULL;
  10264. ssh->v1_cipher_ctx = NULL;
  10265. ssh->crcda_ctx = NULL;
  10266. ssh->cscipher = NULL;
  10267. ssh->cs_cipher_ctx = NULL;
  10268. ssh->sccipher = NULL;
  10269. ssh->sc_cipher_ctx = NULL;
  10270. ssh->csmac = NULL;
  10271. ssh->cs_mac_ctx = NULL;
  10272. ssh->scmac = NULL;
  10273. ssh->sc_mac_ctx = NULL;
  10274. ssh->cscomp = NULL;
  10275. ssh->cs_comp_ctx = NULL;
  10276. ssh->sccomp = NULL;
  10277. ssh->sc_comp_ctx = NULL;
  10278. ssh->kex = NULL;
  10279. ssh->kex_ctx = NULL;
  10280. ssh->hostkey = NULL;
  10281. ssh->hostkey_str = NULL;
  10282. ssh->exitcode = -1;
  10283. ssh->close_expected = FALSE;
  10284. ssh->clean_exit = FALSE;
  10285. ssh->state = SSH_STATE_PREPACKET;
  10286. ssh->size_needed = FALSE;
  10287. ssh->eof_needed = FALSE;
  10288. ssh->ldisc = NULL;
  10289. ssh->logctx = NULL;
  10290. ssh->deferred_send_data = NULL;
  10291. ssh->deferred_len = 0;
  10292. ssh->deferred_size = 0;
  10293. ssh->fallback_cmd = 0;
  10294. ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
  10295. ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
  10296. ssh->x11disp = NULL;
  10297. ssh->x11auth = NULL;
  10298. ssh->x11authtree = newtree234(x11_authcmp);
  10299. ssh->v1_compressing = FALSE;
  10300. ssh->v2_outgoing_sequence = 0;
  10301. ssh->ssh1_rdpkt_crstate = 0;
  10302. ssh->ssh2_rdpkt_crstate = 0;
  10303. ssh->ssh2_bare_rdpkt_crstate = 0;
  10304. ssh->ssh_gotdata_crstate = 0;
  10305. ssh->do_ssh1_connection_crstate = 0;
  10306. ssh->do_ssh_init_state = NULL;
  10307. ssh->do_ssh_connection_init_state = NULL;
  10308. ssh->do_ssh1_login_state = NULL;
  10309. ssh->do_ssh2_transport_state = NULL;
  10310. ssh->do_ssh2_authconn_state = NULL;
  10311. ssh->v_c = NULL;
  10312. ssh->v_s = NULL;
  10313. ssh->mainchan = NULL;
  10314. ssh->throttled_all = 0;
  10315. ssh->v1_stdout_throttling = 0;
  10316. ssh->queue = NULL;
  10317. ssh->queuelen = ssh->queuesize = 0;
  10318. ssh->queueing = FALSE;
  10319. ssh->qhead = ssh->qtail = NULL;
  10320. ssh->deferred_rekey_reason = NULL;
  10321. bufchain_init(&ssh->queued_incoming_data);
  10322. ssh->frozen = FALSE;
  10323. ssh->username = NULL;
  10324. ssh->sent_console_eof = FALSE;
  10325. ssh->got_pty = FALSE;
  10326. ssh->bare_connection = FALSE;
  10327. ssh->X11_fwd_enabled = FALSE;
  10328. ssh->connshare = NULL;
  10329. ssh->attempting_connshare = FALSE;
  10330. ssh->session_started = FALSE;
  10331. ssh->specials = NULL;
  10332. ssh->n_uncert_hostkeys = 0;
  10333. ssh->cross_certifying = FALSE;
  10334. *backend_handle = ssh;
  10335. #ifdef MPEXT
  10336. // random_unref is always called from ssh_free,
  10337. // so we must call random_ref also always, even if we fail, to match it
  10338. random_ref();
  10339. #endif
  10340. #ifdef MSCRYPTOAPI
  10341. if (crypto_startup() == 0)
  10342. return "Microsoft high encryption pack not installed!";
  10343. #endif
  10344. ssh->frontend = frontend_handle;
  10345. ssh->term_width = conf_get_int(ssh->conf, CONF_width);
  10346. ssh->term_height = conf_get_int(ssh->conf, CONF_height);
  10347. ssh->channels = NULL;
  10348. ssh->rportfwds = NULL;
  10349. ssh->portfwds = NULL;
  10350. ssh->send_ok = 0;
  10351. ssh->editing = 0;
  10352. ssh->echoing = 0;
  10353. ssh->conn_throttle_count = 0;
  10354. ssh->overall_bufsize = 0;
  10355. ssh->fallback_cmd = 0;
  10356. ssh->protocol = NULL;
  10357. ssh->protocol_initial_phase_done = FALSE;
  10358. ssh->pinger = NULL;
  10359. ssh->incoming_data_size = ssh->outgoing_data_size =
  10360. ssh->deferred_data_size = 0L;
  10361. ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
  10362. CONF_ssh_rekey_data));
  10363. ssh->kex_in_progress = FALSE;
  10364. ssh->auth_agent_query = NULL;
  10365. #ifndef NO_GSSAPI
  10366. ssh->gsslibs = NULL;
  10367. #endif
  10368. random_ref(); /* do this now - may be needed by sharing setup code */
  10369. p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
  10370. if (p != NULL) {
  10371. random_unref();
  10372. return p;
  10373. }
  10374. random_ref();
  10375. return NULL;
  10376. }
  10377. static void ssh_free(void *handle)
  10378. {
  10379. Ssh ssh = (Ssh) handle;
  10380. struct ssh_channel *c;
  10381. struct ssh_rportfwd *pf;
  10382. struct X11FakeAuth *auth;
  10383. if (ssh->v1_cipher_ctx)
  10384. ssh->cipher->free_context(ssh->v1_cipher_ctx);
  10385. if (ssh->cs_cipher_ctx)
  10386. ssh->cscipher->free_context(ssh->cs_cipher_ctx);
  10387. if (ssh->sc_cipher_ctx)
  10388. ssh->sccipher->free_context(ssh->sc_cipher_ctx);
  10389. if (ssh->cs_mac_ctx)
  10390. ssh->csmac->free_context(ssh->cs_mac_ctx);
  10391. if (ssh->sc_mac_ctx)
  10392. ssh->scmac->free_context(ssh->sc_mac_ctx);
  10393. if (ssh->cs_comp_ctx) {
  10394. if (ssh->cscomp)
  10395. ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
  10396. else
  10397. zlib_compress_cleanup(ssh->cs_comp_ctx);
  10398. }
  10399. if (ssh->sc_comp_ctx) {
  10400. if (ssh->sccomp)
  10401. ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
  10402. else
  10403. zlib_decompress_cleanup(ssh->sc_comp_ctx);
  10404. }
  10405. if (ssh->kex_ctx)
  10406. dh_cleanup(ssh->kex_ctx);
  10407. sfree(ssh->savedhost);
  10408. while (ssh->queuelen-- > 0)
  10409. ssh_free_packet(ssh->queue[ssh->queuelen]);
  10410. sfree(ssh->queue);
  10411. while (ssh->qhead) {
  10412. struct queued_handler *qh = ssh->qhead;
  10413. ssh->qhead = qh->next;
  10414. sfree(qh);
  10415. }
  10416. ssh->qhead = ssh->qtail = NULL;
  10417. if (ssh->channels) {
  10418. while ((c = delpos234(ssh->channels, 0)) != NULL) {
  10419. ssh_channel_close_local(c, NULL);
  10420. if (ssh->version == 2) {
  10421. struct outstanding_channel_request *ocr, *nocr;
  10422. ocr = c->v.v2.chanreq_head;
  10423. while (ocr) {
  10424. ocr->handler(c, NULL, ocr->ctx);
  10425. nocr = ocr->next;
  10426. sfree(ocr);
  10427. ocr = nocr;
  10428. }
  10429. bufchain_clear(&c->v.v2.outbuffer);
  10430. }
  10431. sfree(c);
  10432. }
  10433. freetree234(ssh->channels);
  10434. ssh->channels = NULL;
  10435. }
  10436. if (ssh->connshare)
  10437. sharestate_free(ssh->connshare);
  10438. if (ssh->rportfwds) {
  10439. while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
  10440. free_rportfwd(pf);
  10441. freetree234(ssh->rportfwds);
  10442. ssh->rportfwds = NULL;
  10443. }
  10444. sfree(ssh->deferred_send_data);
  10445. if (ssh->x11disp)
  10446. x11_free_display(ssh->x11disp);
  10447. while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
  10448. x11_free_fake_auth(auth);
  10449. freetree234(ssh->x11authtree);
  10450. sfree(ssh->do_ssh_init_state);
  10451. sfree(ssh->do_ssh1_login_state);
  10452. sfree(ssh->do_ssh2_transport_state);
  10453. sfree(ssh->do_ssh2_authconn_state);
  10454. sfree(ssh->v_c);
  10455. sfree(ssh->v_s);
  10456. sfree(ssh->fullhostname);
  10457. sfree(ssh->hostkey_str);
  10458. sfree(ssh->specials);
  10459. if (ssh->crcda_ctx) {
  10460. crcda_free_context(ssh->crcda_ctx);
  10461. ssh->crcda_ctx = NULL;
  10462. }
  10463. if (ssh->s)
  10464. ssh_do_close(ssh, TRUE);
  10465. expire_timer_context(ssh);
  10466. if (ssh->pinger)
  10467. pinger_free(ssh->pinger);
  10468. bufchain_clear(&ssh->queued_incoming_data);
  10469. sfree(ssh->username);
  10470. conf_free(ssh->conf);
  10471. if (ssh->auth_agent_query)
  10472. agent_cancel_query(ssh->auth_agent_query);
  10473. #ifndef NO_GSSAPI
  10474. if (ssh->gsslibs)
  10475. ssh_gss_cleanup(ssh->gsslibs);
  10476. #endif
  10477. sfree(ssh);
  10478. random_unref();
  10479. }
  10480. /*
  10481. * Reconfigure the SSH backend.
  10482. */
  10483. static void ssh_reconfig(void *handle, Conf *conf)
  10484. {
  10485. Ssh ssh = (Ssh) handle;
  10486. const char *rekeying = NULL;
  10487. int rekey_mandatory = FALSE;
  10488. unsigned long old_max_data_size;
  10489. int i, rekey_time;
  10490. pinger_reconfig(ssh->pinger, ssh->conf, conf);
  10491. if (ssh->portfwds)
  10492. ssh_setup_portfwd(ssh, conf);
  10493. rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
  10494. if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
  10495. rekey_time != 0) {
  10496. unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
  10497. unsigned long now = GETTICKCOUNT();
  10498. if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
  10499. rekeying = "timeout shortened";
  10500. } else {
  10501. ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
  10502. }
  10503. }
  10504. old_max_data_size = ssh->max_data_size;
  10505. ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
  10506. CONF_ssh_rekey_data));
  10507. if (old_max_data_size != ssh->max_data_size &&
  10508. ssh->max_data_size != 0) {
  10509. if (ssh->outgoing_data_size > ssh->max_data_size ||
  10510. ssh->incoming_data_size > ssh->max_data_size)
  10511. rekeying = "data limit lowered";
  10512. }
  10513. if (conf_get_int(ssh->conf, CONF_compression) !=
  10514. conf_get_int(conf, CONF_compression)) {
  10515. rekeying = "compression setting changed";
  10516. rekey_mandatory = TRUE;
  10517. }
  10518. for (i = 0; i < CIPHER_MAX; i++)
  10519. if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
  10520. conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
  10521. rekeying = "cipher settings changed";
  10522. rekey_mandatory = TRUE;
  10523. }
  10524. if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
  10525. conf_get_int(conf, CONF_ssh2_des_cbc)) {
  10526. rekeying = "cipher settings changed";
  10527. rekey_mandatory = TRUE;
  10528. }
  10529. conf_free(ssh->conf);
  10530. ssh->conf = conf_copy(conf);
  10531. ssh_cache_conf_values(ssh);
  10532. if (!ssh->bare_connection && rekeying) {
  10533. if (!ssh->kex_in_progress) {
  10534. do_ssh2_transport(ssh, rekeying, -1, NULL);
  10535. } else if (rekey_mandatory) {
  10536. ssh->deferred_rekey_reason = rekeying;
  10537. }
  10538. }
  10539. }
  10540. /*
  10541. * Called to send data down the SSH connection.
  10542. */
  10543. static int ssh_send(void *handle, const char *buf, int len)
  10544. {
  10545. Ssh ssh = (Ssh) handle;
  10546. if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
  10547. return 0;
  10548. ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
  10549. return ssh_sendbuffer(ssh);
  10550. }
  10551. /*
  10552. * Called to query the current amount of buffered stdin data.
  10553. */
  10554. static int ssh_sendbuffer(void *handle)
  10555. {
  10556. Ssh ssh = (Ssh) handle;
  10557. int override_value;
  10558. if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
  10559. return 0;
  10560. /*
  10561. * If the SSH socket itself has backed up, add the total backup
  10562. * size on that to any individual buffer on the stdin channel.
  10563. */
  10564. override_value = 0;
  10565. if (ssh->throttled_all)
  10566. override_value = ssh->overall_bufsize;
  10567. if (ssh->version == 1) {
  10568. return override_value;
  10569. } else if (ssh->version == 2) {
  10570. if (!ssh->mainchan)
  10571. return override_value;
  10572. else
  10573. return (override_value +
  10574. bufchain_size(&ssh->mainchan->v.v2.outbuffer));
  10575. }
  10576. return 0;
  10577. }
  10578. /*
  10579. * Called to set the size of the window from SSH's POV.
  10580. */
  10581. static void ssh_size(void *handle, int width, int height)
  10582. {
  10583. Ssh ssh = (Ssh) handle;
  10584. struct Packet *pktout;
  10585. ssh->term_width = width;
  10586. ssh->term_height = height;
  10587. switch (ssh->state) {
  10588. case SSH_STATE_BEFORE_SIZE:
  10589. case SSH_STATE_PREPACKET:
  10590. case SSH_STATE_CLOSED:
  10591. break; /* do nothing */
  10592. case SSH_STATE_INTERMED:
  10593. ssh->size_needed = TRUE; /* buffer for later */
  10594. break;
  10595. case SSH_STATE_SESSION:
  10596. if (!conf_get_int(ssh->conf, CONF_nopty)) {
  10597. if (ssh->version == 1) {
  10598. send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
  10599. PKT_INT, ssh->term_height,
  10600. PKT_INT, ssh->term_width,
  10601. PKT_INT, 0, PKT_INT, 0, PKT_END);
  10602. } else if (ssh->mainchan) {
  10603. pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
  10604. NULL, NULL);
  10605. ssh2_pkt_adduint32(pktout, ssh->term_width);
  10606. ssh2_pkt_adduint32(pktout, ssh->term_height);
  10607. ssh2_pkt_adduint32(pktout, 0);
  10608. ssh2_pkt_adduint32(pktout, 0);
  10609. ssh2_pkt_send(ssh, pktout);
  10610. }
  10611. }
  10612. break;
  10613. }
  10614. }
  10615. /*
  10616. * Return a list of the special codes that make sense in this
  10617. * protocol.
  10618. */
  10619. static const struct telnet_special *ssh_get_specials(void *handle)
  10620. {
  10621. static const struct telnet_special ssh1_ignore_special[] = {
  10622. {"IGNORE message", TS_NOP}
  10623. };
  10624. static const struct telnet_special ssh2_ignore_special[] = {
  10625. {"IGNORE message", TS_NOP},
  10626. };
  10627. static const struct telnet_special ssh2_rekey_special[] = {
  10628. {"Repeat key exchange", TS_REKEY},
  10629. };
  10630. static const struct telnet_special ssh2_session_specials[] = {
  10631. {NULL, TS_SEP},
  10632. {"Break", TS_BRK},
  10633. /* These are the signal names defined by RFC 4254.
  10634. * They include all the ISO C signals, but are a subset of the POSIX
  10635. * required signals. */
  10636. {"SIGINT (Interrupt)", TS_SIGINT},
  10637. {"SIGTERM (Terminate)", TS_SIGTERM},
  10638. {"SIGKILL (Kill)", TS_SIGKILL},
  10639. {"SIGQUIT (Quit)", TS_SIGQUIT},
  10640. {"SIGHUP (Hangup)", TS_SIGHUP},
  10641. {"More signals", TS_SUBMENU},
  10642. {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
  10643. {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
  10644. {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
  10645. {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
  10646. {NULL, TS_EXITMENU}
  10647. };
  10648. static const struct telnet_special specials_end[] = {
  10649. {NULL, TS_EXITMENU}
  10650. };
  10651. struct telnet_special *specials = NULL;
  10652. int nspecials = 0, specialsize = 0;
  10653. Ssh ssh = (Ssh) handle;
  10654. sfree(ssh->specials);
  10655. #define ADD_SPECIALS(name) do \
  10656. { \
  10657. int len = lenof(name); \
  10658. if (nspecials + len > specialsize) { \
  10659. specialsize = (nspecials + len) * 5 / 4 + 32; \
  10660. specials = sresize(specials, specialsize, struct telnet_special); \
  10661. } \
  10662. memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
  10663. nspecials += len; \
  10664. } while (0)
  10665. if (ssh->version == 1) {
  10666. /* Don't bother offering IGNORE if we've decided the remote
  10667. * won't cope with it, since we wouldn't bother sending it if
  10668. * asked anyway. */
  10669. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
  10670. ADD_SPECIALS(ssh1_ignore_special);
  10671. } else if (ssh->version == 2) {
  10672. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
  10673. ADD_SPECIALS(ssh2_ignore_special);
  10674. if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
  10675. ADD_SPECIALS(ssh2_rekey_special);
  10676. if (ssh->mainchan)
  10677. ADD_SPECIALS(ssh2_session_specials);
  10678. if (ssh->n_uncert_hostkeys) {
  10679. static const struct telnet_special uncert_start[] = {
  10680. {NULL, TS_SEP},
  10681. {"Cache new host key type", TS_SUBMENU},
  10682. };
  10683. static const struct telnet_special uncert_end[] = {
  10684. {NULL, TS_EXITMENU},
  10685. };
  10686. int i;
  10687. ADD_SPECIALS(uncert_start);
  10688. for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
  10689. struct telnet_special uncert[1];
  10690. const struct ssh_signkey *alg =
  10691. hostkey_algs[ssh->uncert_hostkeys[i]].alg;
  10692. uncert[0].name = alg->name;
  10693. uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
  10694. ADD_SPECIALS(uncert);
  10695. }
  10696. ADD_SPECIALS(uncert_end);
  10697. }
  10698. } /* else we're not ready yet */
  10699. if (nspecials)
  10700. ADD_SPECIALS(specials_end);
  10701. ssh->specials = specials;
  10702. if (nspecials) {
  10703. return specials;
  10704. } else {
  10705. return NULL;
  10706. }
  10707. #undef ADD_SPECIALS
  10708. }
  10709. /*
  10710. * Send special codes. TS_EOF is useful for `plink', so you
  10711. * can send an EOF and collect resulting output (e.g. `plink
  10712. * hostname sort').
  10713. */
  10714. static void ssh_special(void *handle, Telnet_Special code)
  10715. {
  10716. Ssh ssh = (Ssh) handle;
  10717. struct Packet *pktout;
  10718. if (code == TS_EOF) {
  10719. if (ssh->state != SSH_STATE_SESSION) {
  10720. /*
  10721. * Buffer the EOF in case we are pre-SESSION, so we can
  10722. * send it as soon as we reach SESSION.
  10723. */
  10724. if (code == TS_EOF)
  10725. ssh->eof_needed = TRUE;
  10726. return;
  10727. }
  10728. if (ssh->version == 1) {
  10729. send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
  10730. } else if (ssh->mainchan) {
  10731. sshfwd_write_eof(ssh->mainchan);
  10732. ssh->send_ok = 0; /* now stop trying to read from stdin */
  10733. }
  10734. logevent("Sent EOF message");
  10735. } else if (code == TS_PING || code == TS_NOP) {
  10736. if (ssh->state == SSH_STATE_CLOSED
  10737. || ssh->state == SSH_STATE_PREPACKET) return;
  10738. if (ssh->version == 1) {
  10739. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
  10740. send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
  10741. } else {
  10742. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
  10743. pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
  10744. ssh2_pkt_addstring_start(pktout);
  10745. ssh2_pkt_send_noqueue(ssh, pktout);
  10746. }
  10747. }
  10748. } else if (code == TS_REKEY) {
  10749. if (!ssh->kex_in_progress && !ssh->bare_connection &&
  10750. ssh->version == 2) {
  10751. do_ssh2_transport(ssh, "at user request", -1, NULL);
  10752. }
  10753. } else if (code >= TS_LOCALSTART) {
  10754. ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
  10755. ssh->cross_certifying = TRUE;
  10756. if (!ssh->kex_in_progress && !ssh->bare_connection &&
  10757. ssh->version == 2) {
  10758. do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
  10759. }
  10760. } else if (code == TS_BRK) {
  10761. if (ssh->state == SSH_STATE_CLOSED
  10762. || ssh->state == SSH_STATE_PREPACKET) return;
  10763. if (ssh->version == 1) {
  10764. logevent("Unable to send BREAK signal in SSH-1");
  10765. } else if (ssh->mainchan) {
  10766. pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
  10767. ssh2_pkt_adduint32(pktout, 0); /* default break length */
  10768. ssh2_pkt_send(ssh, pktout);
  10769. }
  10770. } else {
  10771. /* Is is a POSIX signal? */
  10772. const char *signame = NULL;
  10773. if (code == TS_SIGABRT) signame = "ABRT";
  10774. if (code == TS_SIGALRM) signame = "ALRM";
  10775. if (code == TS_SIGFPE) signame = "FPE";
  10776. if (code == TS_SIGHUP) signame = "HUP";
  10777. if (code == TS_SIGILL) signame = "ILL";
  10778. if (code == TS_SIGINT) signame = "INT";
  10779. if (code == TS_SIGKILL) signame = "KILL";
  10780. if (code == TS_SIGPIPE) signame = "PIPE";
  10781. if (code == TS_SIGQUIT) signame = "QUIT";
  10782. if (code == TS_SIGSEGV) signame = "SEGV";
  10783. if (code == TS_SIGTERM) signame = "TERM";
  10784. if (code == TS_SIGUSR1) signame = "USR1";
  10785. if (code == TS_SIGUSR2) signame = "USR2";
  10786. /* The SSH-2 protocol does in principle support arbitrary named
  10787. * signals, including signame@domain, but we don't support those. */
  10788. if (signame) {
  10789. /* It's a signal. */
  10790. if (ssh->version == 2 && ssh->mainchan) {
  10791. pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
  10792. ssh2_pkt_addstring(pktout, signame);
  10793. ssh2_pkt_send(ssh, pktout);
  10794. logeventf(ssh, "Sent signal SIG%s", signame);
  10795. }
  10796. } else {
  10797. /* Never heard of it. Do nothing */
  10798. }
  10799. }
  10800. }
  10801. void *new_sock_channel(void *handle, struct PortForwarding *pf)
  10802. {
  10803. Ssh ssh = (Ssh) handle;
  10804. struct ssh_channel *c;
  10805. c = snew(struct ssh_channel);
  10806. c->ssh = ssh;
  10807. ssh_channel_init(c);
  10808. c->halfopen = TRUE;
  10809. c->type = CHAN_SOCKDATA;/* identify channel type */
  10810. c->u.pfd.pf = pf;
  10811. return c;
  10812. }
  10813. unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
  10814. {
  10815. struct ssh_channel *c;
  10816. c = snew(struct ssh_channel);
  10817. c->ssh = ssh;
  10818. ssh_channel_init(c);
  10819. c->type = CHAN_SHARING;
  10820. c->u.sharing.ctx = sharing_ctx;
  10821. return c->localid;
  10822. }
  10823. void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
  10824. {
  10825. struct ssh_channel *c;
  10826. c = find234(ssh->channels, &localid, ssh_channelfind);
  10827. if (c)
  10828. ssh_channel_destroy(c);
  10829. }
  10830. void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
  10831. const void *data, int datalen,
  10832. const char *additional_log_text)
  10833. {
  10834. struct Packet *pkt;
  10835. pkt = ssh2_pkt_init(type);
  10836. pkt->downstream_id = id;
  10837. pkt->additional_log_text = additional_log_text;
  10838. ssh2_pkt_adddata(pkt, data, datalen);
  10839. ssh2_pkt_send(ssh, pkt);
  10840. }
  10841. /*
  10842. * This is called when stdout/stderr (the entity to which
  10843. * from_backend sends data) manages to clear some backlog.
  10844. */
  10845. static void ssh_unthrottle(void *handle, int bufsize)
  10846. {
  10847. Ssh ssh = (Ssh) handle;
  10848. if (ssh->version == 1) {
  10849. if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
  10850. ssh->v1_stdout_throttling = 0;
  10851. ssh_throttle_conn(ssh, -1);
  10852. }
  10853. } else {
  10854. if (ssh->mainchan)
  10855. ssh_channel_unthrottle(ssh->mainchan, bufsize);
  10856. }
  10857. /*
  10858. * Now process any SSH connection data that was stashed in our
  10859. * queue while we were frozen.
  10860. */
  10861. ssh_process_queued_incoming_data(ssh);
  10862. }
  10863. void ssh_send_port_open(void *channel, const char *hostname, int port,
  10864. const char *org)
  10865. {
  10866. struct ssh_channel *c = (struct ssh_channel *)channel;
  10867. Ssh ssh = c->ssh;
  10868. struct Packet *pktout;
  10869. logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
  10870. if (ssh->version == 1) {
  10871. send_packet(ssh, SSH1_MSG_PORT_OPEN,
  10872. PKT_INT, c->localid,
  10873. PKT_STR, hostname,
  10874. PKT_INT, port,
  10875. /* PKT_STR, <org:orgport>, */
  10876. PKT_END);
  10877. } else {
  10878. pktout = ssh2_chanopen_init(c, "direct-tcpip");
  10879. {
  10880. char *trimmed_host = host_strduptrim(hostname);
  10881. ssh2_pkt_addstring(pktout, trimmed_host);
  10882. sfree(trimmed_host);
  10883. }
  10884. ssh2_pkt_adduint32(pktout, port);
  10885. /*
  10886. * We make up values for the originator data; partly it's
  10887. * too much hassle to keep track, and partly I'm not
  10888. * convinced the server should be told details like that
  10889. * about my local network configuration.
  10890. * The "originator IP address" is syntactically a numeric
  10891. * IP address, and some servers (e.g., Tectia) get upset
  10892. * if it doesn't match this syntax.
  10893. */
  10894. ssh2_pkt_addstring(pktout, "0.0.0.0");
  10895. ssh2_pkt_adduint32(pktout, 0);
  10896. ssh2_pkt_send(ssh, pktout);
  10897. }
  10898. }
  10899. static int ssh_connected(void *handle)
  10900. {
  10901. Ssh ssh = (Ssh) handle;
  10902. return ssh->s != NULL;
  10903. }
  10904. static int ssh_sendok(void *handle)
  10905. {
  10906. Ssh ssh = (Ssh) handle;
  10907. return ssh->send_ok;
  10908. }
  10909. static int ssh_ldisc(void *handle, int option)
  10910. {
  10911. Ssh ssh = (Ssh) handle;
  10912. if (option == LD_ECHO)
  10913. return ssh->echoing;
  10914. if (option == LD_EDIT)
  10915. return ssh->editing;
  10916. return FALSE;
  10917. }
  10918. static void ssh_provide_ldisc(void *handle, void *ldisc)
  10919. {
  10920. Ssh ssh = (Ssh) handle;
  10921. ssh->ldisc = ldisc;
  10922. }
  10923. static void ssh_provide_logctx(void *handle, void *logctx)
  10924. {
  10925. Ssh ssh = (Ssh) handle;
  10926. ssh->logctx = logctx;
  10927. }
  10928. static int ssh_return_exitcode(void *handle)
  10929. {
  10930. Ssh ssh = (Ssh) handle;
  10931. if (ssh->s != NULL)
  10932. return -1;
  10933. else
  10934. return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
  10935. }
  10936. /*
  10937. * cfg_info for SSH is the protocol running in this session.
  10938. * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
  10939. * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
  10940. */
  10941. static int ssh_cfg_info(void *handle)
  10942. {
  10943. Ssh ssh = (Ssh) handle;
  10944. if (ssh->version == 0)
  10945. return 0; /* don't know yet */
  10946. else if (ssh->bare_connection)
  10947. return -1;
  10948. else
  10949. return ssh->version;
  10950. }
  10951. /*
  10952. * Gross hack: pscp will try to start SFTP but fall back to scp1 if
  10953. * that fails. This variable is the means by which scp.c can reach
  10954. * into the SSH code and find out which one it got.
  10955. */
  10956. extern int ssh_fallback_cmd(void *handle)
  10957. {
  10958. Ssh ssh = (Ssh) handle;
  10959. return ssh->fallback_cmd;
  10960. }
  10961. Backend ssh_backend = {
  10962. ssh_init,
  10963. ssh_free,
  10964. ssh_reconfig,
  10965. ssh_send,
  10966. ssh_sendbuffer,
  10967. ssh_size,
  10968. ssh_special,
  10969. ssh_get_specials,
  10970. ssh_connected,
  10971. ssh_return_exitcode,
  10972. ssh_sendok,
  10973. ssh_ldisc,
  10974. ssh_provide_ldisc,
  10975. ssh_provide_logctx,
  10976. ssh_unthrottle,
  10977. ssh_cfg_info,
  10978. ssh_test_for_upstream,
  10979. "ssh",
  10980. PROT_SSH,
  10981. 22
  10982. };
  10983. #ifdef MPEXT
  10984. #include "puttyexp.h"
  10985. void ssh_close(void * handle)
  10986. {
  10987. ssh_do_close((Ssh)handle, FALSE);
  10988. }
  10989. int is_ssh(void * handle)
  10990. {
  10991. Plug fn = (Plug)handle;
  10992. return (*fn)->closing == ssh_closing;
  10993. }
  10994. void call_ssh_timer(void * handle)
  10995. {
  10996. if (((Ssh)handle)->version == 2)
  10997. {
  10998. ssh2_timer(handle, GETTICKCOUNT());
  10999. }
  11000. }
  11001. int get_ssh_version(void * handle)
  11002. {
  11003. return ((Ssh)handle)->version;
  11004. }
  11005. void * get_ssh_frontend(void * handle)
  11006. {
  11007. return ((Ssh)handle)->frontend;
  11008. }
  11009. int get_ssh1_compressing(void * handle)
  11010. {
  11011. return ((Ssh)handle)->v1_compressing;
  11012. }
  11013. const struct ssh_cipher * get_cipher(void * handle)
  11014. {
  11015. return ((Ssh)handle)->cipher;
  11016. }
  11017. const struct ssh2_cipher * get_cscipher(void * handle)
  11018. {
  11019. return ((Ssh)handle)->cscipher;
  11020. }
  11021. const struct ssh2_cipher * get_sccipher(void * handle)
  11022. {
  11023. return ((Ssh)handle)->sccipher;
  11024. }
  11025. const struct ssh_compress * get_cscomp(void * handle)
  11026. {
  11027. return ((Ssh)handle)->cscomp;
  11028. }
  11029. const struct ssh_compress * get_sccomp(void * handle)
  11030. {
  11031. return ((Ssh)handle)->sccomp;
  11032. }
  11033. int get_ssh_state(void * handle)
  11034. {
  11035. return ((Ssh)handle)->state;
  11036. }
  11037. int get_ssh_state_closed(void * handle)
  11038. {
  11039. return ((Ssh)handle)->state == SSH_STATE_CLOSED;
  11040. }
  11041. int get_ssh_state_session(void * handle)
  11042. {
  11043. return ((Ssh)handle)->state == SSH_STATE_SESSION;
  11044. }
  11045. int get_ssh_exitcode(void * handle)
  11046. {
  11047. return ssh_return_exitcode(handle);
  11048. }
  11049. const unsigned int * ssh2_remmaxpkt(void * handle)
  11050. {
  11051. return &((Ssh)handle)->mainchan->v.v2.remmaxpkt;
  11052. }
  11053. const unsigned int * ssh2_remwindow(void * handle)
  11054. {
  11055. return &((Ssh)handle)->mainchan->v.v2.remwindow;
  11056. }
  11057. void md5checksum(const char * buffer, int len, unsigned char output[16])
  11058. {
  11059. struct MD5Context md5c;
  11060. MD5Init(&md5c);
  11061. MD5Update(&md5c, buffer, len);
  11062. MD5Final(output, &md5c);
  11063. }
  11064. void get_hostkey_algs(int * count, cp_ssh_signkey * SignKeys)
  11065. {
  11066. int i;
  11067. assert(lenof(hostkey_algs) <= *count);
  11068. *count = lenof(hostkey_algs);
  11069. for (i = 0; i < *count; i++)
  11070. {
  11071. *(SignKeys + i) = hostkey_algs[i].alg;
  11072. }
  11073. }
  11074. #endif