ssh.c 384 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236
  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. /* Changed order to match WinSCP default preference list for SshHostKeyList() */
  410. { &ssh_rsa, HK_RSA },
  411. { &ssh_dss, HK_DSA },
  412. };
  413. const static struct ssh_mac *const macs[] = {
  414. &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
  415. };
  416. const static struct ssh_mac *const buggymacs[] = {
  417. &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
  418. };
  419. static void *ssh_comp_none_init(void)
  420. {
  421. return NULL;
  422. }
  423. static void ssh_comp_none_cleanup(void *handle)
  424. {
  425. }
  426. static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
  427. unsigned char **outblock, int *outlen)
  428. {
  429. return 0;
  430. }
  431. static int ssh_comp_none_disable(void *handle)
  432. {
  433. return 0;
  434. }
  435. const static struct ssh_compress ssh_comp_none = {
  436. "none", NULL,
  437. ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
  438. ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
  439. ssh_comp_none_disable, NULL
  440. };
  441. extern const struct ssh_compress ssh_zlib;
  442. const static struct ssh_compress *const compressions[] = {
  443. &ssh_zlib, &ssh_comp_none
  444. };
  445. enum { /* channel types */
  446. CHAN_MAINSESSION,
  447. CHAN_X11,
  448. CHAN_AGENT,
  449. CHAN_SOCKDATA,
  450. /*
  451. * CHAN_SHARING indicates a channel which is tracked here on
  452. * behalf of a connection-sharing downstream. We do almost nothing
  453. * with these channels ourselves: all messages relating to them
  454. * get thrown straight to sshshare.c and passed on almost
  455. * unmodified to downstream.
  456. */
  457. CHAN_SHARING,
  458. /*
  459. * CHAN_ZOMBIE is used to indicate a channel for which we've
  460. * already destroyed the local data source: for instance, if a
  461. * forwarded port experiences a socket error on the local side, we
  462. * immediately destroy its local socket and turn the SSH channel
  463. * into CHAN_ZOMBIE.
  464. */
  465. CHAN_ZOMBIE
  466. };
  467. typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
  468. typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
  469. typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
  470. /*
  471. * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
  472. * handlers.
  473. */
  474. struct outstanding_channel_request {
  475. cchandler_fn_t handler;
  476. void *ctx;
  477. struct outstanding_channel_request *next;
  478. };
  479. /*
  480. * 2-3-4 tree storing channels.
  481. */
  482. struct ssh_channel {
  483. Ssh ssh; /* pointer back to main context */
  484. unsigned remoteid, localid;
  485. int type;
  486. /* True if we opened this channel but server hasn't confirmed. */
  487. int halfopen;
  488. /*
  489. * In SSH-1, this value contains four bits:
  490. *
  491. * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
  492. * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
  493. * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
  494. * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
  495. *
  496. * A channel is completely finished with when all four bits are set.
  497. *
  498. * In SSH-2, the four bits mean:
  499. *
  500. * 1 We have sent SSH2_MSG_CHANNEL_EOF.
  501. * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
  502. * 4 We have received SSH2_MSG_CHANNEL_EOF.
  503. * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
  504. *
  505. * A channel is completely finished with when we have both sent
  506. * and received CLOSE.
  507. *
  508. * The symbolic constants below use the SSH-2 terminology, which
  509. * is a bit confusing in SSH-1, but we have to use _something_.
  510. */
  511. #define CLOSES_SENT_EOF 1
  512. #define CLOSES_SENT_CLOSE 2
  513. #define CLOSES_RCVD_EOF 4
  514. #define CLOSES_RCVD_CLOSE 8
  515. int closes;
  516. /*
  517. * This flag indicates that an EOF is pending on the outgoing side
  518. * of the channel: that is, wherever we're getting the data for
  519. * this channel has sent us some data followed by EOF. We can't
  520. * actually send the EOF until we've finished sending the data, so
  521. * we set this flag instead to remind us to do so once our buffer
  522. * is clear.
  523. */
  524. int pending_eof;
  525. /*
  526. * True if this channel is causing the underlying connection to be
  527. * throttled.
  528. */
  529. int throttling_conn;
  530. union {
  531. struct ssh2_data_channel {
  532. bufchain outbuffer;
  533. unsigned remwindow, remmaxpkt;
  534. /* locwindow is signed so we can cope with excess data. */
  535. int locwindow, locmaxwin;
  536. /*
  537. * remlocwin is the amount of local window that we think
  538. * the remote end had available to it after it sent the
  539. * last data packet or window adjust ack.
  540. */
  541. int remlocwin;
  542. /*
  543. * These store the list of channel requests that haven't
  544. * been acked.
  545. */
  546. struct outstanding_channel_request *chanreq_head, *chanreq_tail;
  547. enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
  548. } v2;
  549. } v;
  550. union {
  551. struct ssh_agent_channel {
  552. bufchain inbuffer;
  553. agent_pending_query *pending;
  554. } a;
  555. struct ssh_x11_channel {
  556. struct X11Connection *xconn;
  557. int initial;
  558. } x11;
  559. struct ssh_pfd_channel {
  560. struct PortForwarding *pf;
  561. } pfd;
  562. struct ssh_sharing_channel {
  563. void *ctx;
  564. } sharing;
  565. } u;
  566. };
  567. /*
  568. * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
  569. * use this structure in different ways, reflecting SSH-2's
  570. * altogether saner approach to port forwarding.
  571. *
  572. * In SSH-1, you arrange a remote forwarding by sending the server
  573. * the remote port number, and the local destination host:port.
  574. * When a connection comes in, the server sends you back that
  575. * host:port pair, and you connect to it. This is a ready-made
  576. * security hole if you're not on the ball: a malicious server
  577. * could send you back _any_ host:port pair, so if you trustingly
  578. * connect to the address it gives you then you've just opened the
  579. * entire inside of your corporate network just by connecting
  580. * through it to a dodgy SSH server. Hence, we must store a list of
  581. * host:port pairs we _are_ trying to forward to, and reject a
  582. * connection request from the server if it's not in the list.
  583. *
  584. * In SSH-2, each side of the connection minds its own business and
  585. * doesn't send unnecessary information to the other. You arrange a
  586. * remote forwarding by sending the server just the remote port
  587. * number. When a connection comes in, the server tells you which
  588. * of its ports was connected to; and _you_ have to remember what
  589. * local host:port pair went with that port number.
  590. *
  591. * Hence, in SSH-1 this structure is indexed by destination
  592. * host:port pair, whereas in SSH-2 it is indexed by source port.
  593. */
  594. struct ssh_portfwd; /* forward declaration */
  595. struct ssh_rportfwd {
  596. unsigned sport, dport;
  597. char *shost, *dhost;
  598. char *sportdesc;
  599. void *share_ctx;
  600. struct ssh_portfwd *pfrec;
  601. };
  602. static void free_rportfwd(struct ssh_rportfwd *pf)
  603. {
  604. if (pf) {
  605. sfree(pf->sportdesc);
  606. sfree(pf->shost);
  607. sfree(pf->dhost);
  608. sfree(pf);
  609. }
  610. }
  611. /*
  612. * Separately to the rportfwd tree (which is for looking up port
  613. * open requests from the server), a tree of _these_ structures is
  614. * used to keep track of all the currently open port forwardings,
  615. * so that we can reconfigure in mid-session if the user requests
  616. * it.
  617. */
  618. struct ssh_portfwd {
  619. enum { DESTROY, KEEP, CREATE } status;
  620. int type;
  621. unsigned sport, dport;
  622. char *saddr, *daddr;
  623. char *sserv, *dserv;
  624. struct ssh_rportfwd *remote;
  625. int addressfamily;
  626. struct PortListener *local;
  627. };
  628. #define free_portfwd(pf) ( \
  629. ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
  630. sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
  631. struct Packet {
  632. long length; /* length of packet: see below */
  633. long forcepad; /* SSH-2: force padding to at least this length */
  634. int type; /* only used for incoming packets */
  635. unsigned long sequence; /* SSH-2 incoming sequence number */
  636. unsigned char *data; /* allocated storage */
  637. unsigned char *body; /* offset of payload within `data' */
  638. long savedpos; /* dual-purpose saved packet position: see below */
  639. long maxlen; /* amount of storage allocated for `data' */
  640. long encrypted_len; /* for SSH-2 total-size counting */
  641. /*
  642. * A note on the 'length' and 'savedpos' fields above.
  643. *
  644. * Incoming packets are set up so that pkt->length is measured
  645. * relative to pkt->body, which itself points to a few bytes after
  646. * pkt->data (skipping some uninteresting header fields including
  647. * the packet type code). The ssh_pkt_get* functions all expect
  648. * this setup, and they also use pkt->savedpos to indicate how far
  649. * through the packet being decoded they've got - and that, too,
  650. * is an offset from pkt->body rather than pkt->data.
  651. *
  652. * During construction of an outgoing packet, however, pkt->length
  653. * is measured relative to the base pointer pkt->data, and
  654. * pkt->body is not really used for anything until the packet is
  655. * ready for sending. In this mode, pkt->savedpos is reused as a
  656. * temporary variable by the addstring functions, which write out
  657. * a string length field and then keep going back and updating it
  658. * as more data is appended to the subsequent string data field;
  659. * pkt->savedpos stores the offset (again relative to pkt->data)
  660. * of the start of the string data field.
  661. */
  662. /* Extra metadata used in SSH packet logging mode, allowing us to
  663. * log in the packet header line that the packet came from a
  664. * connection-sharing downstream and what if anything unusual was
  665. * done to it. The additional_log_text field is expected to be a
  666. * static string - it will not be freed. */
  667. unsigned downstream_id;
  668. const char *additional_log_text;
  669. };
  670. static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
  671. struct Packet *pktin);
  672. static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
  673. struct Packet *pktin);
  674. static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
  675. struct Packet *pktin);
  676. static void ssh1_protocol_setup(Ssh ssh);
  677. static void ssh2_protocol_setup(Ssh ssh);
  678. static void ssh2_bare_connection_protocol_setup(Ssh ssh);
  679. static void ssh_size(void *handle, int width, int height);
  680. static void ssh_special(void *handle, Telnet_Special);
  681. static int ssh2_try_send(struct ssh_channel *c);
  682. static int ssh_send_channel_data(struct ssh_channel *c,
  683. const char *buf, int len);
  684. static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
  685. static void ssh2_set_window(struct ssh_channel *c, int newwin);
  686. static int ssh_sendbuffer(void *handle);
  687. static int ssh_do_close(Ssh ssh, int notify_exit);
  688. static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
  689. static int ssh2_pkt_getbool(struct Packet *pkt);
  690. static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
  691. static void ssh2_timer(void *ctx, unsigned long now);
  692. static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
  693. struct Packet *pktin);
  694. static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
  695. struct rdpkt1_state_tag {
  696. long len, pad, biglen, to_read;
  697. unsigned long realcrc, gotcrc;
  698. unsigned char *p;
  699. int i;
  700. int chunk;
  701. struct Packet *pktin;
  702. };
  703. struct rdpkt2_state_tag {
  704. long len, pad, payload, packetlen, maclen;
  705. int i;
  706. int cipherblk;
  707. unsigned long incoming_sequence;
  708. struct Packet *pktin;
  709. };
  710. struct rdpkt2_bare_state_tag {
  711. char length[4];
  712. long packetlen;
  713. int i;
  714. unsigned long incoming_sequence;
  715. struct Packet *pktin;
  716. };
  717. struct queued_handler;
  718. struct queued_handler {
  719. int msg1, msg2;
  720. chandler_fn_t handler;
  721. void *ctx;
  722. struct queued_handler *next;
  723. };
  724. struct ssh_tag {
  725. const struct plug_function_table *fn;
  726. /* the above field _must_ be first in the structure */
  727. char *v_c, *v_s;
  728. void *exhash;
  729. Socket s;
  730. void *ldisc;
  731. void *logctx;
  732. unsigned char session_key[32];
  733. int v1_compressing;
  734. int v1_remote_protoflags;
  735. int v1_local_protoflags;
  736. int agentfwd_enabled;
  737. int X11_fwd_enabled;
  738. int remote_bugs;
  739. const struct ssh_cipher *cipher;
  740. void *v1_cipher_ctx;
  741. void *crcda_ctx;
  742. const struct ssh2_cipher *cscipher, *sccipher;
  743. void *cs_cipher_ctx, *sc_cipher_ctx;
  744. const struct ssh_mac *csmac, *scmac;
  745. int csmac_etm, scmac_etm;
  746. void *cs_mac_ctx, *sc_mac_ctx;
  747. const struct ssh_compress *cscomp, *sccomp;
  748. void *cs_comp_ctx, *sc_comp_ctx;
  749. const struct ssh_kex *kex;
  750. const struct ssh_signkey *hostkey;
  751. char *hostkey_str; /* string representation, for easy checking in rekeys */
  752. unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
  753. int v2_session_id_len;
  754. void *kex_ctx;
  755. int bare_connection;
  756. int attempting_connshare;
  757. void *connshare;
  758. char *savedhost;
  759. int savedport;
  760. int send_ok;
  761. int echoing, editing;
  762. int session_started;
  763. void *frontend;
  764. int ospeed, ispeed; /* temporaries */
  765. int term_width, term_height;
  766. tree234 *channels; /* indexed by local id */
  767. struct ssh_channel *mainchan; /* primary session channel */
  768. int ncmode; /* is primary channel direct-tcpip? */
  769. int exitcode;
  770. int close_expected;
  771. int clean_exit;
  772. tree234 *rportfwds, *portfwds;
  773. enum {
  774. SSH_STATE_PREPACKET,
  775. SSH_STATE_BEFORE_SIZE,
  776. SSH_STATE_INTERMED,
  777. SSH_STATE_SESSION,
  778. SSH_STATE_CLOSED
  779. } state;
  780. int size_needed, eof_needed;
  781. int sent_console_eof;
  782. int got_pty; /* affects EOF behaviour on main channel */
  783. struct Packet **queue;
  784. int queuelen, queuesize;
  785. int queueing;
  786. unsigned char *deferred_send_data;
  787. int deferred_len, deferred_size;
  788. /*
  789. * Gross hack: pscp will try to start SFTP but fall back to
  790. * scp1 if that fails. This variable is the means by which
  791. * scp.c can reach into the SSH code and find out which one it
  792. * got.
  793. */
  794. int fallback_cmd;
  795. bufchain banner; /* accumulates banners during do_ssh2_authconn */
  796. Pkt_KCtx pkt_kctx;
  797. Pkt_ACtx pkt_actx;
  798. struct X11Display *x11disp;
  799. struct X11FakeAuth *x11auth;
  800. tree234 *x11authtree;
  801. int version;
  802. int conn_throttle_count;
  803. int overall_bufsize;
  804. int throttled_all;
  805. int v1_stdout_throttling;
  806. unsigned long v2_outgoing_sequence;
  807. int ssh1_rdpkt_crstate;
  808. int ssh2_rdpkt_crstate;
  809. int ssh2_bare_rdpkt_crstate;
  810. int ssh_gotdata_crstate;
  811. int do_ssh1_connection_crstate;
  812. void *do_ssh_init_state;
  813. void *do_ssh1_login_state;
  814. void *do_ssh2_transport_state;
  815. void *do_ssh2_authconn_state;
  816. void *do_ssh_connection_init_state;
  817. struct rdpkt1_state_tag rdpkt1_state;
  818. struct rdpkt2_state_tag rdpkt2_state;
  819. struct rdpkt2_bare_state_tag rdpkt2_bare_state;
  820. /* SSH-1 and SSH-2 use this for different things, but both use it */
  821. int protocol_initial_phase_done;
  822. void (*protocol) (Ssh ssh, const void *vin, int inlen,
  823. struct Packet *pkt);
  824. struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
  825. int *datalen);
  826. int (*do_ssh_init)(Ssh ssh, unsigned char c);
  827. /*
  828. * We maintain our own copy of a Conf structure here. That way,
  829. * when we're passed a new one for reconfiguration, we can check
  830. * the differences and potentially reconfigure port forwardings
  831. * etc in mid-session.
  832. */
  833. Conf *conf;
  834. /*
  835. * Values cached out of conf so as to avoid the tree234 lookup
  836. * cost every time they're used.
  837. */
  838. int logomitdata;
  839. /*
  840. * Dynamically allocated username string created during SSH
  841. * login. Stored in here rather than in the coroutine state so
  842. * that it'll be reliably freed if we shut down the SSH session
  843. * at some unexpected moment.
  844. */
  845. char *username;
  846. /*
  847. * Used to transfer data back from async callbacks.
  848. */
  849. void *agent_response;
  850. int agent_response_len;
  851. int user_response;
  852. /*
  853. * The SSH connection can be set as `frozen', meaning we are
  854. * not currently accepting incoming data from the network. This
  855. * is slightly more serious than setting the _socket_ as
  856. * frozen, because we may already have had data passed to us
  857. * from the network which we need to delay processing until
  858. * after the freeze is lifted, so we also need a bufchain to
  859. * store that data.
  860. */
  861. int frozen;
  862. bufchain queued_incoming_data;
  863. /*
  864. * Dispatch table for packet types that we may have to deal
  865. * with at any time.
  866. */
  867. handler_fn_t packet_dispatch[256];
  868. /*
  869. * Queues of one-off handler functions for success/failure
  870. * indications from a request.
  871. */
  872. struct queued_handler *qhead, *qtail;
  873. handler_fn_t q_saved_handler1, q_saved_handler2;
  874. /*
  875. * This module deals with sending keepalives.
  876. */
  877. Pinger pinger;
  878. /*
  879. * Track incoming and outgoing data sizes and time, for
  880. * size-based rekeys.
  881. */
  882. unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
  883. unsigned long max_data_size;
  884. int kex_in_progress;
  885. unsigned long next_rekey, last_rekey;
  886. const char *deferred_rekey_reason;
  887. /*
  888. * Fully qualified host name, which we need if doing GSSAPI.
  889. */
  890. char *fullhostname;
  891. #ifndef NO_GSSAPI
  892. /*
  893. * GSSAPI libraries for this session.
  894. */
  895. struct ssh_gss_liblist *gsslibs;
  896. #endif
  897. /*
  898. * The last list returned from get_specials.
  899. */
  900. struct telnet_special *specials;
  901. /*
  902. * List of host key algorithms for which we _don't_ have a stored
  903. * host key. These are indices into the main hostkey_algs[] array
  904. */
  905. int uncert_hostkeys[lenof(hostkey_algs)];
  906. int n_uncert_hostkeys;
  907. /*
  908. * Flag indicating that the current rekey is intended to finish
  909. * with a newly cross-certified host key.
  910. */
  911. int cross_certifying;
  912. /*
  913. * Any asynchronous query to our SSH agent that we might have in
  914. * flight from the main authentication loop. (Queries from
  915. * agent-forwarding channels live in their channel structure.)
  916. */
  917. agent_pending_query *auth_agent_query;
  918. };
  919. static const char *ssh_pkt_type(Ssh ssh, int type)
  920. {
  921. if (ssh->version == 1)
  922. return ssh1_pkt_type(type);
  923. else
  924. return ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, type);
  925. }
  926. #define logevent(s) logevent(ssh->frontend, s)
  927. /* logevent, only printf-formatted. */
  928. static void logeventf(Ssh ssh, const char *fmt, ...)
  929. {
  930. va_list ap;
  931. char *buf;
  932. va_start(ap, fmt);
  933. buf = dupvprintf(fmt, ap);
  934. va_end(ap);
  935. logevent(buf);
  936. sfree(buf);
  937. }
  938. static void bomb_out(Ssh ssh, char *text)
  939. {
  940. ssh_do_close(ssh, FALSE);
  941. logevent(text);
  942. connection_fatal(ssh->frontend, "%s", text);
  943. sfree(text);
  944. }
  945. #define bombout(msg) bomb_out(ssh, dupprintf msg)
  946. /* Helper function for common bits of parsing ttymodes. */
  947. static void parse_ttymodes(Ssh ssh,
  948. void (*do_mode)(void *data,
  949. const struct ssh_ttymode *mode,
  950. char *val),
  951. void *data)
  952. {
  953. int i;
  954. const struct ssh_ttymode *mode;
  955. char *val;
  956. for (i = 0; i < lenof(ssh_ttymodes); i++) {
  957. mode = ssh_ttymodes + i;
  958. /* Every mode known to the current version of the code should be
  959. * mentioned; this was ensured when settings were loaded. */
  960. val = conf_get_str_str(ssh->conf, CONF_ttymodes, mode->mode);
  961. /*
  962. * val[0] can be
  963. * - 'V', indicating that an explicit value follows it;
  964. * - 'A', indicating that we should pass the value through from
  965. * the local environment via get_ttymode; or
  966. * - 'N', indicating that we should explicitly not send this
  967. * mode.
  968. */
  969. if (val[0] == 'A') {
  970. val = get_ttymode(ssh->frontend, mode->mode);
  971. if (val) {
  972. do_mode(data, mode, val);
  973. sfree(val);
  974. }
  975. } else if (val[0] == 'V') {
  976. do_mode(data, mode, val + 1); /* skip the 'V' */
  977. } /* else 'N', or something from the future we don't understand */
  978. }
  979. }
  980. static int ssh_channelcmp(void *av, void *bv)
  981. {
  982. struct ssh_channel *a = (struct ssh_channel *) av;
  983. struct ssh_channel *b = (struct ssh_channel *) bv;
  984. if (a->localid < b->localid)
  985. return -1;
  986. if (a->localid > b->localid)
  987. return +1;
  988. return 0;
  989. }
  990. static int ssh_channelfind(void *av, void *bv)
  991. {
  992. unsigned *a = (unsigned *) av;
  993. struct ssh_channel *b = (struct ssh_channel *) bv;
  994. if (*a < b->localid)
  995. return -1;
  996. if (*a > b->localid)
  997. return +1;
  998. return 0;
  999. }
  1000. static int ssh_rportcmp_ssh1(void *av, void *bv)
  1001. {
  1002. struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
  1003. struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
  1004. int i;
  1005. if ( (i = strcmp(a->dhost, b->dhost)) != 0)
  1006. return i < 0 ? -1 : +1;
  1007. if (a->dport > b->dport)
  1008. return +1;
  1009. if (a->dport < b->dport)
  1010. return -1;
  1011. return 0;
  1012. }
  1013. static int ssh_rportcmp_ssh2(void *av, void *bv)
  1014. {
  1015. struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
  1016. struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
  1017. int i;
  1018. if ( (i = strcmp(a->shost, b->shost)) != 0)
  1019. return i < 0 ? -1 : +1;
  1020. if (a->sport > b->sport)
  1021. return +1;
  1022. if (a->sport < b->sport)
  1023. return -1;
  1024. return 0;
  1025. }
  1026. /*
  1027. * Special form of strcmp which can cope with NULL inputs. NULL is
  1028. * defined to sort before even the empty string.
  1029. */
  1030. static int nullstrcmp(const char *a, const char *b)
  1031. {
  1032. if (a == NULL && b == NULL)
  1033. return 0;
  1034. if (a == NULL)
  1035. return -1;
  1036. if (b == NULL)
  1037. return +1;
  1038. return strcmp(a, b);
  1039. }
  1040. static int ssh_portcmp(void *av, void *bv)
  1041. {
  1042. struct ssh_portfwd *a = (struct ssh_portfwd *) av;
  1043. struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
  1044. int i;
  1045. if (a->type > b->type)
  1046. return +1;
  1047. if (a->type < b->type)
  1048. return -1;
  1049. if (a->addressfamily > b->addressfamily)
  1050. return +1;
  1051. if (a->addressfamily < b->addressfamily)
  1052. return -1;
  1053. if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
  1054. return i < 0 ? -1 : +1;
  1055. if (a->sport > b->sport)
  1056. return +1;
  1057. if (a->sport < b->sport)
  1058. return -1;
  1059. if (a->type != 'D') {
  1060. if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
  1061. return i < 0 ? -1 : +1;
  1062. if (a->dport > b->dport)
  1063. return +1;
  1064. if (a->dport < b->dport)
  1065. return -1;
  1066. }
  1067. return 0;
  1068. }
  1069. static int alloc_channel_id(Ssh ssh)
  1070. {
  1071. const unsigned CHANNEL_NUMBER_OFFSET = 256;
  1072. unsigned low, high, mid;
  1073. int tsize;
  1074. struct ssh_channel *c;
  1075. /*
  1076. * First-fit allocation of channel numbers: always pick the
  1077. * lowest unused one. To do this, binary-search using the
  1078. * counted B-tree to find the largest channel ID which is in a
  1079. * contiguous sequence from the beginning. (Precisely
  1080. * everything in that sequence must have ID equal to its tree
  1081. * index plus CHANNEL_NUMBER_OFFSET.)
  1082. */
  1083. tsize = count234(ssh->channels);
  1084. low = -1;
  1085. high = tsize;
  1086. while (high - low > 1) {
  1087. mid = (high + low) / 2;
  1088. c = index234(ssh->channels, mid);
  1089. if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
  1090. low = mid; /* this one is fine */
  1091. else
  1092. high = mid; /* this one is past it */
  1093. }
  1094. /*
  1095. * Now low points to either -1, or the tree index of the
  1096. * largest ID in the initial sequence.
  1097. */
  1098. {
  1099. unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
  1100. assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
  1101. }
  1102. return low + 1 + CHANNEL_NUMBER_OFFSET;
  1103. }
  1104. static void c_write_stderr(int trusted, const char *buf, int len)
  1105. {
  1106. int i;
  1107. for (i = 0; i < len; i++)
  1108. if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
  1109. fputc(buf[i], stderr);
  1110. }
  1111. static void c_write(Ssh ssh, const char *buf, int len)
  1112. {
  1113. if (flags & FLAG_STDERR)
  1114. c_write_stderr(1, buf, len);
  1115. else
  1116. #ifdef MPEXT
  1117. from_backend(ssh->frontend, -1, buf, len);
  1118. #else
  1119. from_backend(ssh->frontend, 1, buf, len);
  1120. #endif
  1121. }
  1122. static void c_write_untrusted(Ssh ssh, const char *buf, int len)
  1123. {
  1124. if (flags & FLAG_STDERR)
  1125. c_write_stderr(0, buf, len);
  1126. else
  1127. from_backend_untrusted(ssh->frontend, buf, len);
  1128. }
  1129. static void c_write_str(Ssh ssh, const char *buf)
  1130. {
  1131. c_write(ssh, buf, strlen(buf));
  1132. }
  1133. static void ssh_free_packet(struct Packet *pkt)
  1134. {
  1135. sfree(pkt->data);
  1136. sfree(pkt);
  1137. }
  1138. static struct Packet *ssh_new_packet(void)
  1139. {
  1140. struct Packet *pkt = snew(struct Packet);
  1141. pkt->body = pkt->data = NULL;
  1142. pkt->maxlen = 0;
  1143. return pkt;
  1144. }
  1145. static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
  1146. {
  1147. int nblanks = 0;
  1148. struct logblank_t blanks[4];
  1149. char *str;
  1150. int slen;
  1151. pkt->savedpos = 0;
  1152. if (ssh->logomitdata &&
  1153. (pkt->type == SSH1_SMSG_STDOUT_DATA ||
  1154. pkt->type == SSH1_SMSG_STDERR_DATA ||
  1155. pkt->type == SSH1_MSG_CHANNEL_DATA)) {
  1156. /* "Session data" packets - omit the data string. */
  1157. if (pkt->type == SSH1_MSG_CHANNEL_DATA)
  1158. ssh_pkt_getuint32(pkt); /* skip channel id */
  1159. blanks[nblanks].offset = pkt->savedpos + 4;
  1160. blanks[nblanks].type = PKTLOG_OMIT;
  1161. ssh_pkt_getstring(pkt, &str, &slen);
  1162. if (str) {
  1163. blanks[nblanks].len = slen;
  1164. nblanks++;
  1165. }
  1166. }
  1167. log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
  1168. ssh1_pkt_type(pkt->type),
  1169. pkt->body, pkt->length, nblanks, blanks, NULL,
  1170. 0, NULL);
  1171. }
  1172. static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
  1173. {
  1174. int nblanks = 0;
  1175. struct logblank_t blanks[4];
  1176. char *str;
  1177. int slen;
  1178. /*
  1179. * For outgoing packets, pkt->length represents the length of the
  1180. * whole packet starting at pkt->data (including some header), and
  1181. * pkt->body refers to the point within that where the log-worthy
  1182. * payload begins. However, incoming packets expect pkt->length to
  1183. * represent only the payload length (that is, it's measured from
  1184. * pkt->body not from pkt->data). Temporarily adjust our outgoing
  1185. * packet to conform to the incoming-packet semantics, so that we
  1186. * can analyse it with the ssh_pkt_get functions.
  1187. */
  1188. pkt->length -= (pkt->body - pkt->data);
  1189. pkt->savedpos = 0;
  1190. if (ssh->logomitdata &&
  1191. (pkt->type == SSH1_CMSG_STDIN_DATA ||
  1192. pkt->type == SSH1_MSG_CHANNEL_DATA)) {
  1193. /* "Session data" packets - omit the data string. */
  1194. if (pkt->type == SSH1_MSG_CHANNEL_DATA)
  1195. ssh_pkt_getuint32(pkt); /* skip channel id */
  1196. blanks[nblanks].offset = pkt->savedpos + 4;
  1197. blanks[nblanks].type = PKTLOG_OMIT;
  1198. ssh_pkt_getstring(pkt, &str, &slen);
  1199. if (str) {
  1200. blanks[nblanks].len = slen;
  1201. nblanks++;
  1202. }
  1203. }
  1204. if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
  1205. pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
  1206. pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
  1207. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1208. /* If this is a password or similar packet, blank the password(s). */
  1209. blanks[nblanks].offset = 0;
  1210. blanks[nblanks].len = pkt->length;
  1211. blanks[nblanks].type = PKTLOG_BLANK;
  1212. nblanks++;
  1213. } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
  1214. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1215. /*
  1216. * If this is an X forwarding request packet, blank the fake
  1217. * auth data.
  1218. *
  1219. * Note that while we blank the X authentication data here, we
  1220. * don't take any special action to blank the start of an X11
  1221. * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
  1222. * an X connection without having session blanking enabled is
  1223. * likely to leak your cookie into the log.
  1224. */
  1225. pkt->savedpos = 0;
  1226. ssh_pkt_getstring(pkt, &str, &slen);
  1227. blanks[nblanks].offset = pkt->savedpos;
  1228. blanks[nblanks].type = PKTLOG_BLANK;
  1229. ssh_pkt_getstring(pkt, &str, &slen);
  1230. if (str) {
  1231. blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
  1232. nblanks++;
  1233. }
  1234. }
  1235. log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
  1236. ssh1_pkt_type(pkt->data[12]),
  1237. pkt->body, pkt->length,
  1238. nblanks, blanks, NULL, 0, NULL);
  1239. /*
  1240. * Undo the above adjustment of pkt->length, to put the packet
  1241. * back in the state we found it.
  1242. */
  1243. pkt->length += (pkt->body - pkt->data);
  1244. }
  1245. /*
  1246. * Collect incoming data in the incoming packet buffer.
  1247. * Decipher and verify the packet when it is completely read.
  1248. * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
  1249. * Update the *data and *datalen variables.
  1250. * Return a Packet structure when a packet is completed.
  1251. */
  1252. static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
  1253. int *datalen)
  1254. {
  1255. struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
  1256. crBegin(ssh->ssh1_rdpkt_crstate);
  1257. st->pktin = ssh_new_packet();
  1258. st->pktin->type = 0;
  1259. st->pktin->length = 0;
  1260. for (st->i = st->len = 0; st->i < 4; st->i++) {
  1261. while ((*datalen) == 0)
  1262. crReturn(NULL);
  1263. st->len = (st->len << 8) + **data;
  1264. (*data)++, (*datalen)--;
  1265. }
  1266. st->pad = 8 - (st->len % 8);
  1267. st->biglen = st->len + st->pad;
  1268. st->pktin->length = st->len - 5;
  1269. if (st->biglen < 0) {
  1270. bombout(("Extremely large packet length from server suggests"
  1271. " data stream corruption"));
  1272. ssh_free_packet(st->pktin);
  1273. crStop(NULL);
  1274. }
  1275. st->pktin->maxlen = st->biglen;
  1276. st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
  1277. st->to_read = st->biglen;
  1278. st->p = st->pktin->data;
  1279. while (st->to_read > 0) {
  1280. st->chunk = st->to_read;
  1281. while ((*datalen) == 0)
  1282. crReturn(NULL);
  1283. if (st->chunk > (*datalen))
  1284. st->chunk = (*datalen);
  1285. memcpy(st->p, *data, st->chunk);
  1286. *data += st->chunk;
  1287. *datalen -= st->chunk;
  1288. st->p += st->chunk;
  1289. st->to_read -= st->chunk;
  1290. }
  1291. if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
  1292. st->biglen, NULL)) {
  1293. bombout(("Network attack (CRC compensation) detected!"));
  1294. ssh_free_packet(st->pktin);
  1295. crStop(NULL);
  1296. }
  1297. if (ssh->cipher)
  1298. ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
  1299. st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
  1300. st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
  1301. if (st->gotcrc != st->realcrc) {
  1302. bombout(("Incorrect CRC received on packet"));
  1303. ssh_free_packet(st->pktin);
  1304. crStop(NULL);
  1305. }
  1306. st->pktin->body = st->pktin->data + st->pad + 1;
  1307. if (ssh->v1_compressing) {
  1308. unsigned char *decompblk;
  1309. int decomplen;
  1310. if (!zlib_decompress_block(ssh->sc_comp_ctx,
  1311. st->pktin->body - 1, st->pktin->length + 1,
  1312. &decompblk, &decomplen)) {
  1313. bombout(("Zlib decompression encountered invalid data"));
  1314. ssh_free_packet(st->pktin);
  1315. crStop(NULL);
  1316. }
  1317. if (st->pktin->maxlen < st->pad + decomplen) {
  1318. st->pktin->maxlen = st->pad + decomplen;
  1319. st->pktin->data = sresize(st->pktin->data,
  1320. st->pktin->maxlen + APIEXTRA,
  1321. unsigned char);
  1322. st->pktin->body = st->pktin->data + st->pad + 1;
  1323. }
  1324. memcpy(st->pktin->body - 1, decompblk, decomplen);
  1325. sfree(decompblk);
  1326. st->pktin->length = decomplen - 1;
  1327. }
  1328. st->pktin->type = st->pktin->body[-1];
  1329. /*
  1330. * Now pktin->body and pktin->length identify the semantic content
  1331. * of the packet, excluding the initial type byte.
  1332. */
  1333. if (ssh->logctx)
  1334. ssh1_log_incoming_packet(ssh, st->pktin);
  1335. st->pktin->savedpos = 0;
  1336. crFinish(st->pktin);
  1337. }
  1338. static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
  1339. {
  1340. int nblanks = 0;
  1341. struct logblank_t blanks[4];
  1342. char *str;
  1343. int slen;
  1344. pkt->savedpos = 0;
  1345. if (ssh->logomitdata &&
  1346. (pkt->type == SSH2_MSG_CHANNEL_DATA ||
  1347. pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
  1348. /* "Session data" packets - omit the data string. */
  1349. ssh_pkt_getuint32(pkt); /* skip channel id */
  1350. if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
  1351. ssh_pkt_getuint32(pkt); /* skip extended data type */
  1352. blanks[nblanks].offset = pkt->savedpos + 4;
  1353. blanks[nblanks].type = PKTLOG_OMIT;
  1354. ssh_pkt_getstring(pkt, &str, &slen);
  1355. if (str) {
  1356. blanks[nblanks].len = slen;
  1357. nblanks++;
  1358. }
  1359. }
  1360. log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
  1361. ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
  1362. pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
  1363. 0, NULL);
  1364. }
  1365. static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
  1366. {
  1367. int nblanks = 0;
  1368. struct logblank_t blanks[4];
  1369. char *str;
  1370. int slen;
  1371. /*
  1372. * For outgoing packets, pkt->length represents the length of the
  1373. * whole packet starting at pkt->data (including some header), and
  1374. * pkt->body refers to the point within that where the log-worthy
  1375. * payload begins. However, incoming packets expect pkt->length to
  1376. * represent only the payload length (that is, it's measured from
  1377. * pkt->body not from pkt->data). Temporarily adjust our outgoing
  1378. * packet to conform to the incoming-packet semantics, so that we
  1379. * can analyse it with the ssh_pkt_get functions.
  1380. */
  1381. pkt->length -= (pkt->body - pkt->data);
  1382. pkt->savedpos = 0;
  1383. if (ssh->logomitdata &&
  1384. (pkt->type == SSH2_MSG_CHANNEL_DATA ||
  1385. pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
  1386. /* "Session data" packets - omit the data string. */
  1387. ssh_pkt_getuint32(pkt); /* skip channel id */
  1388. if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
  1389. ssh_pkt_getuint32(pkt); /* skip extended data type */
  1390. blanks[nblanks].offset = pkt->savedpos + 4;
  1391. blanks[nblanks].type = PKTLOG_OMIT;
  1392. ssh_pkt_getstring(pkt, &str, &slen);
  1393. if (str) {
  1394. blanks[nblanks].len = slen;
  1395. nblanks++;
  1396. }
  1397. }
  1398. if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
  1399. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1400. /* If this is a password packet, blank the password(s). */
  1401. pkt->savedpos = 0;
  1402. ssh_pkt_getstring(pkt, &str, &slen);
  1403. ssh_pkt_getstring(pkt, &str, &slen);
  1404. ssh_pkt_getstring(pkt, &str, &slen);
  1405. if (slen == 8 && !memcmp(str, "password", 8)) {
  1406. ssh2_pkt_getbool(pkt);
  1407. /* Blank the password field. */
  1408. blanks[nblanks].offset = pkt->savedpos;
  1409. blanks[nblanks].type = PKTLOG_BLANK;
  1410. ssh_pkt_getstring(pkt, &str, &slen);
  1411. if (str) {
  1412. blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
  1413. nblanks++;
  1414. /* If there's another password field beyond it (change of
  1415. * password), blank that too. */
  1416. ssh_pkt_getstring(pkt, &str, &slen);
  1417. if (str)
  1418. blanks[nblanks-1].len =
  1419. pkt->savedpos - blanks[nblanks].offset;
  1420. }
  1421. }
  1422. } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
  1423. pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
  1424. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1425. /* If this is a keyboard-interactive response packet, blank
  1426. * the responses. */
  1427. pkt->savedpos = 0;
  1428. ssh_pkt_getuint32(pkt);
  1429. blanks[nblanks].offset = pkt->savedpos;
  1430. blanks[nblanks].type = PKTLOG_BLANK;
  1431. while (1) {
  1432. ssh_pkt_getstring(pkt, &str, &slen);
  1433. if (!str)
  1434. break;
  1435. }
  1436. blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
  1437. nblanks++;
  1438. } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
  1439. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1440. /*
  1441. * If this is an X forwarding request packet, blank the fake
  1442. * auth data.
  1443. *
  1444. * Note that while we blank the X authentication data here, we
  1445. * don't take any special action to blank the start of an X11
  1446. * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
  1447. * an X connection without having session blanking enabled is
  1448. * likely to leak your cookie into the log.
  1449. */
  1450. pkt->savedpos = 0;
  1451. ssh_pkt_getuint32(pkt);
  1452. ssh_pkt_getstring(pkt, &str, &slen);
  1453. if (slen == 7 && !memcmp(str, "x11-req", 0)) {
  1454. ssh2_pkt_getbool(pkt);
  1455. ssh2_pkt_getbool(pkt);
  1456. ssh_pkt_getstring(pkt, &str, &slen);
  1457. blanks[nblanks].offset = pkt->savedpos;
  1458. blanks[nblanks].type = PKTLOG_BLANK;
  1459. ssh_pkt_getstring(pkt, &str, &slen);
  1460. if (str) {
  1461. blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
  1462. nblanks++;
  1463. }
  1464. }
  1465. }
  1466. log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
  1467. ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
  1468. pkt->body, pkt->length, nblanks, blanks,
  1469. &ssh->v2_outgoing_sequence,
  1470. pkt->downstream_id, pkt->additional_log_text);
  1471. /*
  1472. * Undo the above adjustment of pkt->length, to put the packet
  1473. * back in the state we found it.
  1474. */
  1475. pkt->length += (pkt->body - pkt->data);
  1476. }
  1477. static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
  1478. int *datalen)
  1479. {
  1480. struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
  1481. crBegin(ssh->ssh2_rdpkt_crstate);
  1482. st->pktin = ssh_new_packet();
  1483. st->pktin->type = 0;
  1484. st->pktin->length = 0;
  1485. if (ssh->sccipher)
  1486. st->cipherblk = ssh->sccipher->blksize;
  1487. else
  1488. st->cipherblk = 8;
  1489. if (st->cipherblk < 8)
  1490. st->cipherblk = 8;
  1491. st->maclen = ssh->scmac ? ssh->scmac->len : 0;
  1492. if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
  1493. ssh->scmac && !ssh->scmac_etm) {
  1494. /*
  1495. * When dealing with a CBC-mode cipher, we want to avoid the
  1496. * possibility of an attacker's tweaking the ciphertext stream
  1497. * so as to cause us to feed the same block to the block
  1498. * cipher more than once and thus leak information
  1499. * (VU#958563). The way we do this is not to take any
  1500. * decisions on the basis of anything we've decrypted until
  1501. * we've verified it with a MAC. That includes the packet
  1502. * length, so we just read data and check the MAC repeatedly,
  1503. * and when the MAC passes, see if the length we've got is
  1504. * plausible.
  1505. *
  1506. * This defence is unnecessary in OpenSSH ETM mode, because
  1507. * the whole point of ETM mode is that the attacker can't
  1508. * tweak the ciphertext stream at all without the MAC
  1509. * detecting it before we decrypt anything.
  1510. */
  1511. /* May as well allocate the whole lot now. */
  1512. st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
  1513. unsigned char);
  1514. /* Read an amount corresponding to the MAC. */
  1515. for (st->i = 0; st->i < st->maclen; st->i++) {
  1516. while ((*datalen) == 0)
  1517. crReturn(NULL);
  1518. st->pktin->data[st->i] = *(*data)++;
  1519. (*datalen)--;
  1520. }
  1521. st->packetlen = 0;
  1522. {
  1523. unsigned char seq[4];
  1524. ssh->scmac->start(ssh->sc_mac_ctx);
  1525. PUT_32BIT(seq, st->incoming_sequence);
  1526. ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
  1527. }
  1528. for (;;) { /* Once around this loop per cipher block. */
  1529. /* Read another cipher-block's worth, and tack it onto the end. */
  1530. for (st->i = 0; st->i < st->cipherblk; st->i++) {
  1531. while ((*datalen) == 0)
  1532. crReturn(NULL);
  1533. st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
  1534. (*datalen)--;
  1535. }
  1536. /* Decrypt one more block (a little further back in the stream). */
  1537. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  1538. st->pktin->data + st->packetlen,
  1539. st->cipherblk);
  1540. /* Feed that block to the MAC. */
  1541. ssh->scmac->bytes(ssh->sc_mac_ctx,
  1542. st->pktin->data + st->packetlen, st->cipherblk);
  1543. st->packetlen += st->cipherblk;
  1544. /* See if that gives us a valid packet. */
  1545. if (ssh->scmac->verresult(ssh->sc_mac_ctx,
  1546. st->pktin->data + st->packetlen) &&
  1547. ((st->len = toint(GET_32BIT(st->pktin->data))) ==
  1548. st->packetlen-4))
  1549. break;
  1550. if (st->packetlen >= OUR_V2_PACKETLIMIT) {
  1551. bombout(("No valid incoming packet found"));
  1552. ssh_free_packet(st->pktin);
  1553. crStop(NULL);
  1554. }
  1555. }
  1556. st->pktin->maxlen = st->packetlen + st->maclen;
  1557. st->pktin->data = sresize(st->pktin->data,
  1558. st->pktin->maxlen + APIEXTRA,
  1559. unsigned char);
  1560. } else if (ssh->scmac && ssh->scmac_etm) {
  1561. st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
  1562. /*
  1563. * OpenSSH encrypt-then-MAC mode: the packet length is
  1564. * unencrypted, unless the cipher supports length encryption.
  1565. */
  1566. for (st->i = st->len = 0; st->i < 4; st->i++) {
  1567. while ((*datalen) == 0)
  1568. crReturn(NULL);
  1569. st->pktin->data[st->i] = *(*data)++;
  1570. (*datalen)--;
  1571. }
  1572. /* Cipher supports length decryption, so do it */
  1573. if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
  1574. /* Keep the packet the same though, so the MAC passes */
  1575. unsigned char len[4];
  1576. memcpy(len, st->pktin->data, 4);
  1577. ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
  1578. st->len = toint(GET_32BIT(len));
  1579. } else {
  1580. st->len = toint(GET_32BIT(st->pktin->data));
  1581. }
  1582. /*
  1583. * _Completely_ silly lengths should be stomped on before they
  1584. * do us any more damage.
  1585. */
  1586. if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
  1587. st->len % st->cipherblk != 0) {
  1588. bombout(("Incoming packet length field was garbled"));
  1589. ssh_free_packet(st->pktin);
  1590. crStop(NULL);
  1591. }
  1592. /*
  1593. * So now we can work out the total packet length.
  1594. */
  1595. st->packetlen = st->len + 4;
  1596. /*
  1597. * Allocate memory for the rest of the packet.
  1598. */
  1599. st->pktin->maxlen = st->packetlen + st->maclen;
  1600. st->pktin->data = sresize(st->pktin->data,
  1601. st->pktin->maxlen + APIEXTRA,
  1602. unsigned char);
  1603. /*
  1604. * Read the remainder of the packet.
  1605. */
  1606. for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
  1607. while ((*datalen) == 0)
  1608. crReturn(NULL);
  1609. st->pktin->data[st->i] = *(*data)++;
  1610. (*datalen)--;
  1611. }
  1612. /*
  1613. * Check the MAC.
  1614. */
  1615. if (ssh->scmac
  1616. && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
  1617. st->len + 4, st->incoming_sequence)) {
  1618. bombout(("Incorrect MAC received on packet"));
  1619. ssh_free_packet(st->pktin);
  1620. crStop(NULL);
  1621. }
  1622. /* Decrypt everything between the length field and the MAC. */
  1623. if (ssh->sccipher)
  1624. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  1625. st->pktin->data + 4,
  1626. st->packetlen - 4);
  1627. } else {
  1628. st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
  1629. /*
  1630. * Acquire and decrypt the first block of the packet. This will
  1631. * contain the length and padding details.
  1632. */
  1633. for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
  1634. while ((*datalen) == 0)
  1635. crReturn(NULL);
  1636. st->pktin->data[st->i] = *(*data)++;
  1637. (*datalen)--;
  1638. }
  1639. if (ssh->sccipher)
  1640. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  1641. st->pktin->data, st->cipherblk);
  1642. /*
  1643. * Now get the length figure.
  1644. */
  1645. st->len = toint(GET_32BIT(st->pktin->data));
  1646. /*
  1647. * _Completely_ silly lengths should be stomped on before they
  1648. * do us any more damage.
  1649. */
  1650. if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
  1651. (st->len + 4) % st->cipherblk != 0) {
  1652. bombout(("Incoming packet was garbled on decryption"));
  1653. ssh_free_packet(st->pktin);
  1654. crStop(NULL);
  1655. }
  1656. /*
  1657. * So now we can work out the total packet length.
  1658. */
  1659. st->packetlen = st->len + 4;
  1660. /*
  1661. * Allocate memory for the rest of the packet.
  1662. */
  1663. st->pktin->maxlen = st->packetlen + st->maclen;
  1664. st->pktin->data = sresize(st->pktin->data,
  1665. st->pktin->maxlen + APIEXTRA,
  1666. unsigned char);
  1667. /*
  1668. * Read and decrypt the remainder of the packet.
  1669. */
  1670. for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
  1671. st->i++) {
  1672. while ((*datalen) == 0)
  1673. crReturn(NULL);
  1674. st->pktin->data[st->i] = *(*data)++;
  1675. (*datalen)--;
  1676. }
  1677. /* Decrypt everything _except_ the MAC. */
  1678. if (ssh->sccipher)
  1679. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  1680. st->pktin->data + st->cipherblk,
  1681. st->packetlen - st->cipherblk);
  1682. /*
  1683. * Check the MAC.
  1684. */
  1685. if (ssh->scmac
  1686. && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
  1687. st->len + 4, st->incoming_sequence)) {
  1688. bombout(("Incorrect MAC received on packet"));
  1689. ssh_free_packet(st->pktin);
  1690. crStop(NULL);
  1691. }
  1692. }
  1693. /* Get and sanity-check the amount of random padding. */
  1694. st->pad = st->pktin->data[4];
  1695. if (st->pad < 4 || st->len - st->pad < 1) {
  1696. bombout(("Invalid padding length on received packet"));
  1697. ssh_free_packet(st->pktin);
  1698. crStop(NULL);
  1699. }
  1700. /*
  1701. * This enables us to deduce the payload length.
  1702. */
  1703. st->payload = st->len - st->pad - 1;
  1704. st->pktin->length = st->payload + 5;
  1705. st->pktin->encrypted_len = st->packetlen;
  1706. st->pktin->sequence = st->incoming_sequence++;
  1707. st->pktin->length = st->packetlen - st->pad;
  1708. assert(st->pktin->length >= 0);
  1709. /*
  1710. * Decompress packet payload.
  1711. */
  1712. {
  1713. unsigned char *newpayload;
  1714. int newlen;
  1715. if (ssh->sccomp &&
  1716. ssh->sccomp->decompress(ssh->sc_comp_ctx,
  1717. st->pktin->data + 5, st->pktin->length - 5,
  1718. &newpayload, &newlen)) {
  1719. if (st->pktin->maxlen < newlen + 5) {
  1720. st->pktin->maxlen = newlen + 5;
  1721. st->pktin->data = sresize(st->pktin->data,
  1722. st->pktin->maxlen + APIEXTRA,
  1723. unsigned char);
  1724. }
  1725. st->pktin->length = 5 + newlen;
  1726. memcpy(st->pktin->data + 5, newpayload, newlen);
  1727. sfree(newpayload);
  1728. }
  1729. }
  1730. /*
  1731. * RFC 4253 doesn't explicitly say that completely empty packets
  1732. * with no type byte are forbidden, so treat them as deserving
  1733. * an SSH_MSG_UNIMPLEMENTED.
  1734. */
  1735. if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
  1736. ssh2_msg_something_unimplemented(ssh, st->pktin);
  1737. crStop(NULL);
  1738. }
  1739. /*
  1740. * pktin->body and pktin->length should identify the semantic
  1741. * content of the packet, excluding the initial type byte.
  1742. */
  1743. st->pktin->type = st->pktin->data[5];
  1744. st->pktin->body = st->pktin->data + 6;
  1745. st->pktin->length -= 6;
  1746. assert(st->pktin->length >= 0); /* one last double-check */
  1747. if (ssh->logctx)
  1748. ssh2_log_incoming_packet(ssh, st->pktin);
  1749. st->pktin->savedpos = 0;
  1750. crFinish(st->pktin);
  1751. }
  1752. static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
  1753. const unsigned char **data,
  1754. int *datalen)
  1755. {
  1756. struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
  1757. crBegin(ssh->ssh2_bare_rdpkt_crstate);
  1758. /*
  1759. * Read the packet length field.
  1760. */
  1761. for (st->i = 0; st->i < 4; st->i++) {
  1762. while ((*datalen) == 0)
  1763. crReturn(NULL);
  1764. st->length[st->i] = *(*data)++;
  1765. (*datalen)--;
  1766. }
  1767. st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
  1768. if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
  1769. bombout(("Invalid packet length received"));
  1770. crStop(NULL);
  1771. }
  1772. st->pktin = ssh_new_packet();
  1773. st->pktin->data = snewn(st->packetlen, unsigned char);
  1774. st->pktin->encrypted_len = st->packetlen;
  1775. st->pktin->sequence = st->incoming_sequence++;
  1776. /*
  1777. * Read the remainder of the packet.
  1778. */
  1779. for (st->i = 0; st->i < st->packetlen; st->i++) {
  1780. while ((*datalen) == 0)
  1781. crReturn(NULL);
  1782. st->pktin->data[st->i] = *(*data)++;
  1783. (*datalen)--;
  1784. }
  1785. /*
  1786. * pktin->body and pktin->length should identify the semantic
  1787. * content of the packet, excluding the initial type byte.
  1788. */
  1789. st->pktin->type = st->pktin->data[0];
  1790. st->pktin->body = st->pktin->data + 1;
  1791. st->pktin->length = st->packetlen - 1;
  1792. /*
  1793. * Log incoming packet, possibly omitting sensitive fields.
  1794. */
  1795. if (ssh->logctx)
  1796. ssh2_log_incoming_packet(ssh, st->pktin);
  1797. st->pktin->savedpos = 0;
  1798. crFinish(st->pktin);
  1799. }
  1800. static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
  1801. {
  1802. int pad, biglen, i, pktoffs;
  1803. unsigned long crc;
  1804. #ifdef __SC__
  1805. /*
  1806. * XXX various versions of SC (including 8.8.4) screw up the
  1807. * register allocation in this function and use the same register
  1808. * (D6) for len and as a temporary, with predictable results. The
  1809. * following sledgehammer prevents this.
  1810. */
  1811. volatile
  1812. #endif
  1813. int len;
  1814. if (ssh->logctx)
  1815. ssh1_log_outgoing_packet(ssh, pkt);
  1816. if (ssh->v1_compressing) {
  1817. unsigned char *compblk;
  1818. int complen;
  1819. zlib_compress_block(ssh->cs_comp_ctx,
  1820. pkt->data + 12, pkt->length - 12,
  1821. &compblk, &complen);
  1822. ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
  1823. memcpy(pkt->data + 12, compblk, complen);
  1824. sfree(compblk);
  1825. pkt->length = complen + 12;
  1826. }
  1827. ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
  1828. pkt->length += 4;
  1829. len = pkt->length - 4 - 8; /* len(type+data+CRC) */
  1830. pad = 8 - (len % 8);
  1831. pktoffs = 8 - pad;
  1832. biglen = len + pad; /* len(padding+type+data+CRC) */
  1833. for (i = pktoffs; i < 4+8; i++)
  1834. pkt->data[i] = random_byte();
  1835. crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
  1836. PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
  1837. PUT_32BIT(pkt->data + pktoffs, len);
  1838. if (ssh->cipher)
  1839. ssh->cipher->encrypt(ssh->v1_cipher_ctx,
  1840. pkt->data + pktoffs + 4, biglen);
  1841. if (offset_p) *offset_p = pktoffs;
  1842. return biglen + 4; /* len(length+padding+type+data+CRC) */
  1843. }
  1844. static int s_write(Ssh ssh, void *data, int len)
  1845. {
  1846. if (ssh->logctx)
  1847. log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
  1848. 0, NULL, NULL, 0, NULL);
  1849. if (!ssh->s)
  1850. return 0;
  1851. return sk_write(ssh->s, (char *)data, len);
  1852. }
  1853. static void s_wrpkt(Ssh ssh, struct Packet *pkt)
  1854. {
  1855. int len, backlog, offset;
  1856. len = s_wrpkt_prepare(ssh, pkt, &offset);
  1857. backlog = s_write(ssh, pkt->data + offset, len);
  1858. if (backlog > SSH_MAX_BACKLOG)
  1859. {
  1860. ssh_throttle_all(ssh, 1, backlog);
  1861. }
  1862. ssh_free_packet(pkt);
  1863. }
  1864. static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
  1865. {
  1866. int len, offset;
  1867. len = s_wrpkt_prepare(ssh, pkt, &offset);
  1868. if (ssh->deferred_len + len > ssh->deferred_size) {
  1869. ssh->deferred_size = ssh->deferred_len + len + 128;
  1870. ssh->deferred_send_data = sresize(ssh->deferred_send_data,
  1871. ssh->deferred_size,
  1872. unsigned char);
  1873. }
  1874. memcpy(ssh->deferred_send_data + ssh->deferred_len,
  1875. pkt->data + offset, len);
  1876. ssh->deferred_len += len;
  1877. ssh_free_packet(pkt);
  1878. }
  1879. /*
  1880. * Construct a SSH-1 packet with the specified contents.
  1881. * (This all-at-once interface used to be the only one, but now SSH-1
  1882. * packets can also be constructed incrementally.)
  1883. */
  1884. static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
  1885. {
  1886. int argtype;
  1887. Bignum bn;
  1888. struct Packet *pkt;
  1889. pkt = ssh1_pkt_init(pkttype);
  1890. while ((argtype = va_arg(ap, int)) != PKT_END) {
  1891. unsigned char *argp, argchar;
  1892. char *sargp;
  1893. unsigned long argint;
  1894. int arglen;
  1895. switch (argtype) {
  1896. /* Actual fields in the packet */
  1897. case PKT_INT:
  1898. argint = va_arg(ap, int);
  1899. ssh_pkt_adduint32(pkt, argint);
  1900. break;
  1901. case PKT_CHAR:
  1902. argchar = (unsigned char) va_arg(ap, int);
  1903. ssh_pkt_addbyte(pkt, argchar);
  1904. break;
  1905. case PKT_DATA:
  1906. argp = va_arg(ap, unsigned char *);
  1907. arglen = va_arg(ap, int);
  1908. ssh_pkt_adddata(pkt, argp, arglen);
  1909. break;
  1910. case PKT_STR:
  1911. sargp = va_arg(ap, char *);
  1912. ssh_pkt_addstring(pkt, sargp);
  1913. break;
  1914. case PKT_BIGNUM:
  1915. bn = va_arg(ap, Bignum);
  1916. ssh1_pkt_addmp(pkt, bn);
  1917. break;
  1918. }
  1919. }
  1920. return pkt;
  1921. }
  1922. static void send_packet(Ssh ssh, int pkttype, ...)
  1923. {
  1924. struct Packet *pkt;
  1925. va_list ap;
  1926. va_start(ap, pkttype);
  1927. pkt = construct_packet(ssh, pkttype, ap);
  1928. va_end(ap);
  1929. s_wrpkt(ssh, pkt);
  1930. }
  1931. static void defer_packet(Ssh ssh, int pkttype, ...)
  1932. {
  1933. struct Packet *pkt;
  1934. va_list ap;
  1935. va_start(ap, pkttype);
  1936. pkt = construct_packet(ssh, pkttype, ap);
  1937. va_end(ap);
  1938. s_wrpkt_defer(ssh, pkt);
  1939. }
  1940. static int ssh_versioncmp(const char *a, const char *b)
  1941. {
  1942. char *ae, *be;
  1943. unsigned long av, bv;
  1944. av = strtoul(a, &ae, 10);
  1945. bv = strtoul(b, &be, 10);
  1946. if (av != bv)
  1947. return (av < bv ? -1 : +1);
  1948. if (*ae == '.')
  1949. ae++;
  1950. if (*be == '.')
  1951. be++;
  1952. av = strtoul(ae, &ae, 10);
  1953. bv = strtoul(be, &be, 10);
  1954. if (av != bv)
  1955. return (av < bv ? -1 : +1);
  1956. return 0;
  1957. }
  1958. /*
  1959. * Utility routines for putting an SSH-protocol `string' and
  1960. * `uint32' into a hash state.
  1961. */
  1962. static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
  1963. {
  1964. unsigned char lenblk[4];
  1965. PUT_32BIT(lenblk, len);
  1966. h->bytes(s, lenblk, 4);
  1967. h->bytes(s, str, len);
  1968. }
  1969. static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
  1970. {
  1971. unsigned char intblk[4];
  1972. PUT_32BIT(intblk, i);
  1973. h->bytes(s, intblk, 4);
  1974. }
  1975. /*
  1976. * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
  1977. */
  1978. static void ssh_pkt_ensure(struct Packet *pkt, int length)
  1979. {
  1980. if (pkt->maxlen < length) {
  1981. unsigned char *body = pkt->body;
  1982. int offset = body ? body - pkt->data : 0;
  1983. pkt->maxlen = length + 256;
  1984. pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
  1985. if (body) pkt->body = pkt->data + offset;
  1986. }
  1987. }
  1988. static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
  1989. {
  1990. pkt->length += len;
  1991. ssh_pkt_ensure(pkt, pkt->length);
  1992. memcpy(pkt->data + pkt->length - len, data, len);
  1993. }
  1994. static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
  1995. {
  1996. ssh_pkt_adddata(pkt, &byte, 1);
  1997. }
  1998. static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
  1999. {
  2000. ssh_pkt_adddata(pkt, &value, 1);
  2001. }
  2002. static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
  2003. {
  2004. unsigned char x[4];
  2005. PUT_32BIT(x, value);
  2006. ssh_pkt_adddata(pkt, x, 4);
  2007. }
  2008. static void ssh_pkt_addstring_start(struct Packet *pkt)
  2009. {
  2010. ssh_pkt_adduint32(pkt, 0);
  2011. pkt->savedpos = pkt->length;
  2012. }
  2013. static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
  2014. int len)
  2015. {
  2016. ssh_pkt_adddata(pkt, data, len);
  2017. PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
  2018. }
  2019. static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
  2020. {
  2021. ssh_pkt_addstring_data(pkt, data, strlen(data));
  2022. }
  2023. static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
  2024. {
  2025. ssh_pkt_addstring_start(pkt);
  2026. ssh_pkt_addstring_str(pkt, data);
  2027. }
  2028. static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
  2029. {
  2030. int len = ssh1_bignum_length(b);
  2031. unsigned char *data = snewn(len, unsigned char);
  2032. (void) ssh1_write_bignum(data, b);
  2033. ssh_pkt_adddata(pkt, data, len);
  2034. sfree(data);
  2035. }
  2036. static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
  2037. {
  2038. unsigned char *p;
  2039. int i, n = (bignum_bitcount(b) + 7) / 8;
  2040. p = snewn(n + 1, unsigned char);
  2041. p[0] = 0;
  2042. for (i = 1; i <= n; i++)
  2043. p[i] = bignum_byte(b, n - i);
  2044. i = 0;
  2045. while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
  2046. i++;
  2047. memmove(p, p + i, n + 1 - i);
  2048. *len = n + 1 - i;
  2049. return p;
  2050. }
  2051. static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
  2052. {
  2053. unsigned char *p;
  2054. int len;
  2055. p = ssh2_mpint_fmt(b, &len);
  2056. ssh_pkt_addstring_start(pkt);
  2057. ssh_pkt_addstring_data(pkt, (char *)p, len);
  2058. sfree(p);
  2059. }
  2060. static struct Packet *ssh1_pkt_init(int pkt_type)
  2061. {
  2062. struct Packet *pkt = ssh_new_packet();
  2063. pkt->length = 4 + 8; /* space for length + max padding */
  2064. ssh_pkt_addbyte(pkt, pkt_type);
  2065. pkt->body = pkt->data + pkt->length;
  2066. pkt->type = pkt_type;
  2067. pkt->downstream_id = 0;
  2068. pkt->additional_log_text = NULL;
  2069. return pkt;
  2070. }
  2071. /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
  2072. #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
  2073. #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
  2074. #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
  2075. #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
  2076. #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
  2077. #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
  2078. #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
  2079. #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
  2080. static struct Packet *ssh2_pkt_init(int pkt_type)
  2081. {
  2082. struct Packet *pkt = ssh_new_packet();
  2083. pkt->length = 5; /* space for packet length + padding length */
  2084. pkt->forcepad = 0;
  2085. pkt->type = pkt_type;
  2086. ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
  2087. pkt->body = pkt->data + pkt->length; /* after packet type */
  2088. pkt->downstream_id = 0;
  2089. pkt->additional_log_text = NULL;
  2090. return pkt;
  2091. }
  2092. /*
  2093. * Construct an SSH-2 final-form packet: compress it, encrypt it,
  2094. * put the MAC on it. Final packet, ready to be sent, is stored in
  2095. * pkt->data. Total length is returned.
  2096. */
  2097. static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
  2098. {
  2099. int cipherblk, maclen, padding, unencrypted_prefix, i;
  2100. if (ssh->logctx)
  2101. ssh2_log_outgoing_packet(ssh, pkt);
  2102. if (ssh->bare_connection) {
  2103. /*
  2104. * Trivial packet construction for the bare connection
  2105. * protocol.
  2106. */
  2107. PUT_32BIT(pkt->data + 1, pkt->length - 5);
  2108. pkt->body = pkt->data + 1;
  2109. ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
  2110. return pkt->length - 1;
  2111. }
  2112. /*
  2113. * Compress packet payload.
  2114. */
  2115. {
  2116. unsigned char *newpayload;
  2117. int newlen;
  2118. if (ssh->cscomp &&
  2119. ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
  2120. pkt->length - 5,
  2121. &newpayload, &newlen)) {
  2122. pkt->length = 5;
  2123. ssh2_pkt_adddata(pkt, newpayload, newlen);
  2124. sfree(newpayload);
  2125. }
  2126. }
  2127. /*
  2128. * Add padding. At least four bytes, and must also bring total
  2129. * length (minus MAC) up to a multiple of the block size.
  2130. * If pkt->forcepad is set, make sure the packet is at least that size
  2131. * after padding.
  2132. */
  2133. cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
  2134. cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
  2135. padding = 4;
  2136. unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
  2137. if (pkt->length + padding < pkt->forcepad)
  2138. padding = pkt->forcepad - pkt->length;
  2139. padding +=
  2140. (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
  2141. % cipherblk;
  2142. assert(padding <= 255);
  2143. maclen = ssh->csmac ? ssh->csmac->len : 0;
  2144. ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
  2145. pkt->data[4] = padding;
  2146. for (i = 0; i < padding; i++)
  2147. pkt->data[pkt->length + i] = random_byte();
  2148. PUT_32BIT(pkt->data, pkt->length + padding - 4);
  2149. /* Encrypt length if the scheme requires it */
  2150. if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
  2151. ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
  2152. ssh->v2_outgoing_sequence);
  2153. }
  2154. if (ssh->csmac && ssh->csmac_etm) {
  2155. /*
  2156. * OpenSSH-defined encrypt-then-MAC protocol.
  2157. */
  2158. if (ssh->cscipher)
  2159. ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
  2160. pkt->data + 4, pkt->length + padding - 4);
  2161. ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
  2162. pkt->length + padding,
  2163. ssh->v2_outgoing_sequence);
  2164. } else {
  2165. /*
  2166. * SSH-2 standard protocol.
  2167. */
  2168. if (ssh->csmac)
  2169. ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
  2170. pkt->length + padding,
  2171. ssh->v2_outgoing_sequence);
  2172. if (ssh->cscipher)
  2173. ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
  2174. pkt->data, pkt->length + padding);
  2175. }
  2176. ssh->v2_outgoing_sequence++; /* whether or not we MACed */
  2177. pkt->encrypted_len = pkt->length + padding;
  2178. /* Ready-to-send packet starts at pkt->data. We return length. */
  2179. pkt->body = pkt->data;
  2180. return pkt->length + padding + maclen;
  2181. }
  2182. /*
  2183. * Routines called from the main SSH code to send packets. There
  2184. * are quite a few of these, because we have two separate
  2185. * mechanisms for delaying the sending of packets:
  2186. *
  2187. * - In order to send an IGNORE message and a password message in
  2188. * a single fixed-length blob, we require the ability to
  2189. * concatenate the encrypted forms of those two packets _into_ a
  2190. * single blob and then pass it to our <network.h> transport
  2191. * layer in one go. Hence, there's a deferment mechanism which
  2192. * works after packet encryption.
  2193. *
  2194. * - In order to avoid sending any connection-layer messages
  2195. * during repeat key exchange, we have to queue up any such
  2196. * outgoing messages _before_ they are encrypted (and in
  2197. * particular before they're allocated sequence numbers), and
  2198. * then send them once we've finished.
  2199. *
  2200. * I call these mechanisms `defer' and `queue' respectively, so as
  2201. * to distinguish them reasonably easily.
  2202. *
  2203. * The functions send_noqueue() and defer_noqueue() free the packet
  2204. * structure they are passed. Every outgoing packet goes through
  2205. * precisely one of these functions in its life; packets passed to
  2206. * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
  2207. * these or get queued, and then when the queue is later emptied
  2208. * the packets are all passed to defer_noqueue().
  2209. *
  2210. * When using a CBC-mode cipher, it's necessary to ensure that an
  2211. * attacker can't provide data to be encrypted using an IV that they
  2212. * know. We ensure this by prefixing each packet that might contain
  2213. * user data with an SSH_MSG_IGNORE. This is done using the deferral
  2214. * mechanism, so in this case send_noqueue() ends up redirecting to
  2215. * defer_noqueue(). If you don't like this inefficiency, don't use
  2216. * CBC.
  2217. */
  2218. static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
  2219. static void ssh_pkt_defersend(Ssh);
  2220. /*
  2221. * Send an SSH-2 packet immediately, without queuing or deferring.
  2222. */
  2223. static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
  2224. {
  2225. int len;
  2226. int backlog;
  2227. if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
  2228. /* We need to send two packets, so use the deferral mechanism. */
  2229. ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
  2230. ssh_pkt_defersend(ssh);
  2231. return;
  2232. }
  2233. len = ssh2_pkt_construct(ssh, pkt);
  2234. backlog = s_write(ssh, pkt->body, len);
  2235. if (backlog > SSH_MAX_BACKLOG)
  2236. {
  2237. ssh_throttle_all(ssh, 1, backlog);
  2238. }
  2239. ssh->outgoing_data_size += pkt->encrypted_len;
  2240. if (!ssh->kex_in_progress &&
  2241. !ssh->bare_connection &&
  2242. ssh->max_data_size != 0 &&
  2243. ssh->outgoing_data_size > ssh->max_data_size)
  2244. do_ssh2_transport(ssh, "too much data sent", -1, NULL);
  2245. ssh_free_packet(pkt);
  2246. }
  2247. /*
  2248. * Defer an SSH-2 packet.
  2249. */
  2250. static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
  2251. {
  2252. int len;
  2253. if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
  2254. ssh->deferred_len == 0 && !noignore &&
  2255. !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
  2256. /*
  2257. * Interpose an SSH_MSG_IGNORE to ensure that user data don't
  2258. * get encrypted with a known IV.
  2259. */
  2260. struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
  2261. ssh2_pkt_addstring_start(ipkt);
  2262. ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
  2263. }
  2264. len = ssh2_pkt_construct(ssh, pkt);
  2265. if (ssh->deferred_len + len > ssh->deferred_size) {
  2266. ssh->deferred_size = ssh->deferred_len + len + 128;
  2267. ssh->deferred_send_data = sresize(ssh->deferred_send_data,
  2268. ssh->deferred_size,
  2269. unsigned char);
  2270. }
  2271. memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
  2272. ssh->deferred_len += len;
  2273. ssh->deferred_data_size += pkt->encrypted_len;
  2274. ssh_free_packet(pkt);
  2275. }
  2276. /*
  2277. * Queue an SSH-2 packet.
  2278. */
  2279. static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
  2280. {
  2281. assert(ssh->queueing);
  2282. if (ssh->queuelen >= ssh->queuesize) {
  2283. ssh->queuesize = ssh->queuelen + 32;
  2284. ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
  2285. }
  2286. ssh->queue[ssh->queuelen++] = pkt;
  2287. }
  2288. /*
  2289. * Either queue or send a packet, depending on whether queueing is
  2290. * set.
  2291. */
  2292. static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
  2293. {
  2294. if (ssh->queueing)
  2295. ssh2_pkt_queue(ssh, pkt);
  2296. else
  2297. ssh2_pkt_send_noqueue(ssh, pkt);
  2298. }
  2299. /*
  2300. * Either queue or defer a packet, depending on whether queueing is
  2301. * set.
  2302. */
  2303. static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
  2304. {
  2305. if (ssh->queueing)
  2306. ssh2_pkt_queue(ssh, pkt);
  2307. else
  2308. ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
  2309. }
  2310. /*
  2311. * Send the whole deferred data block constructed by
  2312. * ssh2_pkt_defer() or SSH-1's defer_packet().
  2313. *
  2314. * The expected use of the defer mechanism is that you call
  2315. * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
  2316. * not currently queueing, this simply sets up deferred_send_data
  2317. * and then sends it. If we _are_ currently queueing, the calls to
  2318. * ssh2_pkt_defer() put the deferred packets on to the queue
  2319. * instead, and therefore ssh_pkt_defersend() has no deferred data
  2320. * to send. Hence, there's no need to make it conditional on
  2321. * ssh->queueing.
  2322. */
  2323. static void ssh_pkt_defersend(Ssh ssh)
  2324. {
  2325. int backlog;
  2326. backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
  2327. ssh->deferred_len = ssh->deferred_size = 0;
  2328. sfree(ssh->deferred_send_data);
  2329. ssh->deferred_send_data = NULL;
  2330. if (backlog > SSH_MAX_BACKLOG)
  2331. {
  2332. ssh_throttle_all(ssh, 1, backlog);
  2333. }
  2334. if (ssh->version == 2) {
  2335. ssh->outgoing_data_size += ssh->deferred_data_size;
  2336. ssh->deferred_data_size = 0;
  2337. if (!ssh->kex_in_progress &&
  2338. !ssh->bare_connection &&
  2339. ssh->max_data_size != 0 &&
  2340. ssh->outgoing_data_size > ssh->max_data_size)
  2341. do_ssh2_transport(ssh, "too much data sent", -1, NULL);
  2342. }
  2343. }
  2344. /*
  2345. * Send a packet whose length needs to be disguised (typically
  2346. * passwords or keyboard-interactive responses).
  2347. */
  2348. static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
  2349. int padsize)
  2350. {
  2351. #if 0
  2352. if (0) {
  2353. /*
  2354. * The simplest way to do this is to adjust the
  2355. * variable-length padding field in the outgoing packet.
  2356. *
  2357. * Currently compiled out, because some Cisco SSH servers
  2358. * don't like excessively padded packets (bah, why's it
  2359. * always Cisco?)
  2360. */
  2361. pkt->forcepad = padsize;
  2362. ssh2_pkt_send(ssh, pkt);
  2363. } else
  2364. #endif
  2365. {
  2366. /*
  2367. * If we can't do that, however, an alternative approach is
  2368. * to use the pkt_defer mechanism to bundle the packet
  2369. * tightly together with an SSH_MSG_IGNORE such that their
  2370. * combined length is a constant. So first we construct the
  2371. * final form of this packet and defer its sending.
  2372. */
  2373. ssh2_pkt_defer(ssh, pkt);
  2374. /*
  2375. * Now construct an SSH_MSG_IGNORE which includes a string
  2376. * that's an exact multiple of the cipher block size. (If
  2377. * the cipher is NULL so that the block size is
  2378. * unavailable, we don't do this trick at all, because we
  2379. * gain nothing by it.)
  2380. */
  2381. if (ssh->cscipher &&
  2382. !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
  2383. int stringlen, i;
  2384. stringlen = (256 - ssh->deferred_len);
  2385. stringlen += ssh->cscipher->blksize - 1;
  2386. stringlen -= (stringlen % ssh->cscipher->blksize);
  2387. if (ssh->cscomp) {
  2388. /*
  2389. * Temporarily disable actual compression, so we
  2390. * can guarantee to get this string exactly the
  2391. * length we want it. The compression-disabling
  2392. * routine should return an integer indicating how
  2393. * many bytes we should adjust our string length
  2394. * by.
  2395. */
  2396. stringlen -=
  2397. ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
  2398. }
  2399. pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
  2400. ssh2_pkt_addstring_start(pkt);
  2401. for (i = 0; i < stringlen; i++) {
  2402. char c = (char) random_byte();
  2403. ssh2_pkt_addstring_data(pkt, &c, 1);
  2404. }
  2405. ssh2_pkt_defer(ssh, pkt);
  2406. }
  2407. ssh_pkt_defersend(ssh);
  2408. }
  2409. }
  2410. /*
  2411. * Send all queued SSH-2 packets. We send them by means of
  2412. * ssh2_pkt_defer_noqueue(), in case they included a pair of
  2413. * packets that needed to be lumped together.
  2414. */
  2415. static void ssh2_pkt_queuesend(Ssh ssh)
  2416. {
  2417. int i;
  2418. assert(!ssh->queueing);
  2419. for (i = 0; i < ssh->queuelen; i++)
  2420. ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
  2421. ssh->queuelen = 0;
  2422. ssh_pkt_defersend(ssh);
  2423. }
  2424. #if 0
  2425. void bndebug(char *string, Bignum b)
  2426. {
  2427. unsigned char *p;
  2428. int i, len;
  2429. p = ssh2_mpint_fmt(b, &len);
  2430. debug(("%s", string));
  2431. for (i = 0; i < len; i++)
  2432. debug((" %02x", p[i]));
  2433. debug(("\n"));
  2434. sfree(p);
  2435. }
  2436. #endif
  2437. static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
  2438. {
  2439. unsigned char *p;
  2440. int len;
  2441. p = ssh2_mpint_fmt(b, &len);
  2442. hash_string(h, s, p, len);
  2443. sfree(p);
  2444. }
  2445. /*
  2446. * Packet decode functions for both SSH-1 and SSH-2.
  2447. */
  2448. static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
  2449. {
  2450. unsigned long value;
  2451. if (pkt->length - pkt->savedpos < 4)
  2452. return 0; /* arrgh, no way to decline (FIXME?) */
  2453. value = GET_32BIT(pkt->body + pkt->savedpos);
  2454. pkt->savedpos += 4;
  2455. return value;
  2456. }
  2457. static int ssh2_pkt_getbool(struct Packet *pkt)
  2458. {
  2459. unsigned long value;
  2460. if (pkt->length - pkt->savedpos < 1)
  2461. return 0; /* arrgh, no way to decline (FIXME?) */
  2462. value = pkt->body[pkt->savedpos] != 0;
  2463. pkt->savedpos++;
  2464. return value;
  2465. }
  2466. static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
  2467. {
  2468. int len;
  2469. *p = NULL;
  2470. *length = 0;
  2471. if (pkt->length - pkt->savedpos < 4)
  2472. return;
  2473. len = toint(GET_32BIT(pkt->body + pkt->savedpos));
  2474. if (len < 0)
  2475. return;
  2476. *length = len;
  2477. pkt->savedpos += 4;
  2478. if (pkt->length - pkt->savedpos < *length)
  2479. return;
  2480. *p = (char *)(pkt->body + pkt->savedpos);
  2481. pkt->savedpos += *length;
  2482. }
  2483. static void *ssh_pkt_getdata(struct Packet *pkt, int length)
  2484. {
  2485. if (pkt->length - pkt->savedpos < length)
  2486. return NULL;
  2487. pkt->savedpos += length;
  2488. return pkt->body + (pkt->savedpos - length);
  2489. }
  2490. static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
  2491. const unsigned char **keystr)
  2492. {
  2493. int j;
  2494. j = makekey(pkt->body + pkt->savedpos,
  2495. pkt->length - pkt->savedpos,
  2496. key, keystr, 0);
  2497. if (j < 0)
  2498. return FALSE;
  2499. pkt->savedpos += j;
  2500. assert(pkt->savedpos < pkt->length);
  2501. return TRUE;
  2502. }
  2503. static Bignum ssh1_pkt_getmp(struct Packet *pkt)
  2504. {
  2505. int j;
  2506. Bignum b;
  2507. j = ssh1_read_bignum(pkt->body + pkt->savedpos,
  2508. pkt->length - pkt->savedpos, &b);
  2509. if (j < 0)
  2510. return NULL;
  2511. pkt->savedpos += j;
  2512. return b;
  2513. }
  2514. static Bignum ssh2_pkt_getmp(struct Packet *pkt)
  2515. {
  2516. char *p;
  2517. int length;
  2518. Bignum b;
  2519. ssh_pkt_getstring(pkt, &p, &length);
  2520. if (!p)
  2521. return NULL;
  2522. if (p[0] & 0x80)
  2523. return NULL;
  2524. b = bignum_from_bytes((unsigned char *)p, length);
  2525. return b;
  2526. }
  2527. /*
  2528. * Helper function to add an SSH-2 signature blob to a packet.
  2529. * Expects to be shown the public key blob as well as the signature
  2530. * blob. Normally works just like ssh2_pkt_addstring, but will
  2531. * fiddle with the signature packet if necessary for
  2532. * BUG_SSH2_RSA_PADDING.
  2533. */
  2534. static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
  2535. void *pkblob_v, int pkblob_len,
  2536. void *sigblob_v, int sigblob_len)
  2537. {
  2538. unsigned char *pkblob = (unsigned char *)pkblob_v;
  2539. unsigned char *sigblob = (unsigned char *)sigblob_v;
  2540. /* dmemdump(pkblob, pkblob_len); */
  2541. /* dmemdump(sigblob, sigblob_len); */
  2542. /*
  2543. * See if this is in fact an ssh-rsa signature and a buggy
  2544. * server; otherwise we can just do this the easy way.
  2545. */
  2546. if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
  2547. (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
  2548. int pos, len, siglen;
  2549. /*
  2550. * Find the byte length of the modulus.
  2551. */
  2552. pos = 4+7; /* skip over "ssh-rsa" */
  2553. len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
  2554. if (len < 0 || len > pkblob_len - pos - 4)
  2555. goto give_up;
  2556. pos += 4 + len; /* skip over exponent */
  2557. if (pkblob_len - pos < 4)
  2558. goto give_up;
  2559. len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
  2560. if (len < 0 || len > pkblob_len - pos - 4)
  2561. goto give_up;
  2562. pos += 4; /* find modulus itself */
  2563. while (len > 0 && pkblob[pos] == 0)
  2564. len--, pos++;
  2565. /* debug(("modulus length is %d\n", len)); */
  2566. /*
  2567. * Now find the signature integer.
  2568. */
  2569. pos = 4+7; /* skip over "ssh-rsa" */
  2570. if (sigblob_len < pos+4)
  2571. goto give_up;
  2572. siglen = toint(GET_32BIT(sigblob+pos));
  2573. if (siglen != sigblob_len - pos - 4)
  2574. goto give_up;
  2575. /* debug(("signature length is %d\n", siglen)); */
  2576. if (len != siglen) {
  2577. unsigned char newlen[4];
  2578. ssh2_pkt_addstring_start(pkt);
  2579. ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
  2580. /* dmemdump(sigblob, pos); */
  2581. pos += 4; /* point to start of actual sig */
  2582. PUT_32BIT(newlen, len);
  2583. ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
  2584. /* dmemdump(newlen, 4); */
  2585. newlen[0] = 0;
  2586. while (len-- > siglen) {
  2587. ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
  2588. /* dmemdump(newlen, 1); */
  2589. }
  2590. ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
  2591. /* dmemdump(sigblob+pos, siglen); */
  2592. return;
  2593. }
  2594. /* Otherwise fall through and do it the easy way. We also come
  2595. * here as a fallback if we discover above that the key blob
  2596. * is misformatted in some way. */
  2597. give_up:;
  2598. }
  2599. ssh2_pkt_addstring_start(pkt);
  2600. ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
  2601. }
  2602. /*
  2603. * Examine the remote side's version string and compare it against
  2604. * a list of known buggy implementations.
  2605. */
  2606. static void ssh_detect_bugs(Ssh ssh, char *vstring)
  2607. {
  2608. char *imp; /* pointer to implementation part */
  2609. imp = vstring;
  2610. imp += strcspn(imp, "-");
  2611. if (*imp) imp++;
  2612. imp += strcspn(imp, "-");
  2613. if (*imp) imp++;
  2614. ssh->remote_bugs = 0;
  2615. /*
  2616. * General notes on server version strings:
  2617. * - Not all servers reporting "Cisco-1.25" have all the bugs listed
  2618. * here -- in particular, we've heard of one that's perfectly happy
  2619. * with SSH1_MSG_IGNOREs -- but this string never seems to change,
  2620. * so we can't distinguish them.
  2621. */
  2622. if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
  2623. (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
  2624. (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
  2625. !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
  2626. !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
  2627. !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
  2628. /*
  2629. * These versions don't support SSH1_MSG_IGNORE, so we have
  2630. * to use a different defence against password length
  2631. * sniffing.
  2632. */
  2633. ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
  2634. logevent("We believe remote version has SSH-1 ignore bug");
  2635. }
  2636. if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
  2637. (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
  2638. (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
  2639. /*
  2640. * These versions need a plain password sent; they can't
  2641. * handle having a null and a random length of data after
  2642. * the password.
  2643. */
  2644. ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
  2645. logevent("We believe remote version needs a plain SSH-1 password");
  2646. }
  2647. if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
  2648. (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
  2649. (!strcmp(imp, "Cisco-1.25")))) {
  2650. /*
  2651. * These versions apparently have no clue whatever about
  2652. * RSA authentication and will panic and die if they see
  2653. * an AUTH_RSA message.
  2654. */
  2655. ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
  2656. logevent("We believe remote version can't handle SSH-1 RSA authentication");
  2657. }
  2658. if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
  2659. (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
  2660. !wc_match("* VShell", imp) &&
  2661. (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
  2662. wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
  2663. wc_match("2.1 *", imp)))) {
  2664. /*
  2665. * These versions have the HMAC bug.
  2666. */
  2667. ssh->remote_bugs |= BUG_SSH2_HMAC;
  2668. logevent("We believe remote version has SSH-2 HMAC bug");
  2669. }
  2670. if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
  2671. (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
  2672. !wc_match("* VShell", imp) &&
  2673. (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
  2674. /*
  2675. * These versions have the key-derivation bug (failing to
  2676. * include the literal shared secret in the hashes that
  2677. * generate the keys).
  2678. */
  2679. ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
  2680. logevent("We believe remote version has SSH-2 key-derivation bug");
  2681. }
  2682. if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
  2683. (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
  2684. (wc_match("OpenSSH_2.[5-9]*", imp) ||
  2685. wc_match("OpenSSH_3.[0-2]*", imp) ||
  2686. wc_match("mod_sftp/0.[0-8]*", imp) ||
  2687. wc_match("mod_sftp/0.9.[0-8]", imp)))) {
  2688. /*
  2689. * These versions have the SSH-2 RSA padding bug.
  2690. */
  2691. ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
  2692. logevent("We believe remote version has SSH-2 RSA padding bug");
  2693. }
  2694. if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
  2695. (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
  2696. wc_match("OpenSSH_2.[0-2]*", imp))) {
  2697. /*
  2698. * These versions have the SSH-2 session-ID bug in
  2699. * public-key authentication.
  2700. */
  2701. ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
  2702. logevent("We believe remote version has SSH-2 public-key-session-ID bug");
  2703. }
  2704. if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
  2705. (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
  2706. (wc_match("DigiSSH_2.0", imp) ||
  2707. wc_match("OpenSSH_2.[0-4]*", imp) ||
  2708. wc_match("OpenSSH_2.5.[0-3]*", imp) ||
  2709. wc_match("Sun_SSH_1.0", imp) ||
  2710. wc_match("Sun_SSH_1.0.1", imp) ||
  2711. /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
  2712. wc_match("WeOnlyDo-*", imp)))) {
  2713. /*
  2714. * These versions have the SSH-2 rekey bug.
  2715. */
  2716. ssh->remote_bugs |= BUG_SSH2_REKEY;
  2717. logevent("We believe remote version has SSH-2 rekey bug");
  2718. }
  2719. if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
  2720. (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
  2721. (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
  2722. wc_match("1.36 sshlib: GlobalScape", imp)))) {
  2723. /*
  2724. * This version ignores our makpkt and needs to be throttled.
  2725. */
  2726. ssh->remote_bugs |= BUG_SSH2_MAXPKT;
  2727. logevent("We believe remote version ignores SSH-2 maximum packet size");
  2728. }
  2729. if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
  2730. /*
  2731. * Servers that don't support SSH2_MSG_IGNORE. Currently,
  2732. * none detected automatically.
  2733. */
  2734. ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
  2735. logevent("We believe remote version has SSH-2 ignore bug");
  2736. }
  2737. if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
  2738. (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
  2739. (wc_match("OpenSSH_2.[235]*", imp)))) {
  2740. /*
  2741. * These versions only support the original (pre-RFC4419)
  2742. * SSH-2 GEX request, and disconnect with a protocol error if
  2743. * we use the newer version.
  2744. */
  2745. ssh->remote_bugs |= BUG_SSH2_OLDGEX;
  2746. logevent("We believe remote version has outdated SSH-2 GEX");
  2747. }
  2748. if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
  2749. /*
  2750. * Servers that don't support our winadj request for one
  2751. * reason or another. Currently, none detected automatically.
  2752. */
  2753. ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
  2754. logevent("We believe remote version has winadj bug");
  2755. }
  2756. if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
  2757. (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
  2758. (wc_match("OpenSSH_[2-5].*", imp) ||
  2759. wc_match("OpenSSH_6.[0-6]*", imp) ||
  2760. wc_match("dropbear_0.[2-4][0-9]*", imp) ||
  2761. wc_match("dropbear_0.5[01]*", imp)))) {
  2762. /*
  2763. * These versions have the SSH-2 channel request bug.
  2764. * OpenSSH 6.7 and above do not:
  2765. * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
  2766. * dropbear_0.52 and above do not:
  2767. * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
  2768. */
  2769. ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
  2770. logevent("We believe remote version has SSH-2 channel request bug");
  2771. }
  2772. }
  2773. /*
  2774. * The `software version' part of an SSH version string is required
  2775. * to contain no spaces or minus signs.
  2776. */
  2777. static void ssh_fix_verstring(char *str)
  2778. {
  2779. /* Eat "<protoversion>-". */
  2780. while (*str && *str != '-') str++;
  2781. assert(*str == '-'); str++;
  2782. /* Convert minus signs and spaces in the remaining string into
  2783. * underscores. */
  2784. while (*str) {
  2785. if (*str == '-' || *str == ' ')
  2786. *str = '_';
  2787. str++;
  2788. }
  2789. }
  2790. /*
  2791. * Send an appropriate SSH version string.
  2792. */
  2793. static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
  2794. {
  2795. char *verstring;
  2796. if (ssh->version == 2) {
  2797. /*
  2798. * Construct a v2 version string.
  2799. */
  2800. verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
  2801. } else {
  2802. /*
  2803. * Construct a v1 version string.
  2804. */
  2805. assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
  2806. verstring = dupprintf("SSH-%s-%s\012",
  2807. (ssh_versioncmp(svers, "1.5") <= 0 ?
  2808. svers : "1.5"),
  2809. sshver);
  2810. }
  2811. ssh_fix_verstring(verstring + strlen(protoname));
  2812. #ifdef FUZZING
  2813. /* FUZZING make PuTTY insecure, so make live use difficult. */
  2814. verstring[0] = 'I';
  2815. #endif
  2816. if (ssh->version == 2) {
  2817. size_t len;
  2818. /*
  2819. * Record our version string.
  2820. */
  2821. len = strcspn(verstring, "\015\012");
  2822. ssh->v_c = snewn(len + 1, char);
  2823. memcpy(ssh->v_c, verstring, len);
  2824. ssh->v_c[len] = 0;
  2825. }
  2826. logeventf(ssh, "We claim version: %.*s",
  2827. strcspn(verstring, "\015\012"), verstring);
  2828. s_write(ssh, verstring, strlen(verstring));
  2829. sfree(verstring);
  2830. }
  2831. static int do_ssh_init(Ssh ssh, unsigned char c)
  2832. {
  2833. static const char protoname[] = "SSH-";
  2834. struct do_ssh_init_state {
  2835. int crLine;
  2836. int vslen;
  2837. char version[10];
  2838. char *vstring;
  2839. int vstrsize;
  2840. int i;
  2841. int proto1, proto2;
  2842. };
  2843. crState(do_ssh_init_state);
  2844. crBeginState;
  2845. /* Search for a line beginning with the protocol name prefix in
  2846. * the input. */
  2847. for (;;) {
  2848. for (s->i = 0; protoname[s->i]; s->i++) {
  2849. if ((char)c != protoname[s->i]) goto no;
  2850. crReturn(1);
  2851. }
  2852. break;
  2853. no:
  2854. while (c != '\012')
  2855. crReturn(1);
  2856. crReturn(1);
  2857. }
  2858. ssh->session_started = TRUE;
  2859. s->vstrsize = sizeof(protoname) + 16;
  2860. s->vstring = snewn(s->vstrsize, char);
  2861. strcpy(s->vstring, protoname);
  2862. s->vslen = strlen(protoname);
  2863. s->i = 0;
  2864. while (1) {
  2865. if (s->vslen >= s->vstrsize - 1) {
  2866. s->vstrsize += 16;
  2867. s->vstring = sresize(s->vstring, s->vstrsize, char);
  2868. }
  2869. s->vstring[s->vslen++] = c;
  2870. if (s->i >= 0) {
  2871. if (c == '-') {
  2872. s->version[s->i] = '\0';
  2873. s->i = -1;
  2874. } else if (s->i < sizeof(s->version) - 1)
  2875. s->version[s->i++] = c;
  2876. } else if (c == '\012')
  2877. break;
  2878. crReturn(1); /* get another char */
  2879. }
  2880. ssh->agentfwd_enabled = FALSE;
  2881. ssh->rdpkt2_state.incoming_sequence = 0;
  2882. s->vstring[s->vslen] = 0;
  2883. s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
  2884. logeventf(ssh, "Server version: %s", s->vstring);
  2885. ssh_detect_bugs(ssh, s->vstring);
  2886. /*
  2887. * Decide which SSH protocol version to support.
  2888. */
  2889. /* Anything strictly below "2.0" means protocol 1 is supported. */
  2890. s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
  2891. /* Anything greater or equal to "1.99" means protocol 2 is supported. */
  2892. s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
  2893. if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
  2894. if (!s->proto1) {
  2895. bombout(("SSH protocol version 1 required by our configuration "
  2896. "but not provided by server"));
  2897. crStop(0);
  2898. }
  2899. } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
  2900. if (!s->proto2) {
  2901. bombout(("SSH protocol version 2 required by our configuration "
  2902. "but server only provides (old, insecure) SSH-1"));
  2903. crStop(0);
  2904. }
  2905. } else {
  2906. /* No longer support values 1 or 2 for CONF_sshprot */
  2907. assert(!"Unexpected value for CONF_sshprot");
  2908. }
  2909. if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
  2910. ssh->version = 2;
  2911. else
  2912. ssh->version = 1;
  2913. logeventf(ssh, "Using SSH protocol version %d", ssh->version);
  2914. /* Send the version string, if we haven't already */
  2915. if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
  2916. ssh_send_verstring(ssh, protoname, s->version);
  2917. if (ssh->version == 2) {
  2918. size_t len;
  2919. /*
  2920. * Record their version string.
  2921. */
  2922. len = strcspn(s->vstring, "\015\012");
  2923. ssh->v_s = snewn(len + 1, char);
  2924. memcpy(ssh->v_s, s->vstring, len);
  2925. ssh->v_s[len] = 0;
  2926. /*
  2927. * Initialise SSH-2 protocol.
  2928. */
  2929. ssh->protocol = ssh2_protocol;
  2930. ssh2_protocol_setup(ssh);
  2931. ssh->s_rdpkt = ssh2_rdpkt;
  2932. } else {
  2933. /*
  2934. * Initialise SSH-1 protocol.
  2935. */
  2936. ssh->protocol = ssh1_protocol;
  2937. ssh1_protocol_setup(ssh);
  2938. ssh->s_rdpkt = ssh1_rdpkt;
  2939. }
  2940. if (ssh->version == 2)
  2941. do_ssh2_transport(ssh, NULL, -1, NULL);
  2942. update_specials_menu(ssh->frontend);
  2943. ssh->state = SSH_STATE_BEFORE_SIZE;
  2944. ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
  2945. sfree(s->vstring);
  2946. crFinish(0);
  2947. }
  2948. static int do_ssh_connection_init(Ssh ssh, unsigned char c)
  2949. {
  2950. /*
  2951. * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
  2952. * the ssh-connection part, extracted and given a trivial binary
  2953. * packet protocol, so we replace 'SSH-' at the start with a new
  2954. * name. In proper SSH style (though of course this part of the
  2955. * proper SSH protocol _isn't_ subject to this kind of
  2956. * DNS-domain-based extension), we define the new name in our
  2957. * extension space.
  2958. */
  2959. static const char protoname[] =
  2960. "[email protected]";
  2961. struct do_ssh_connection_init_state {
  2962. int crLine;
  2963. int vslen;
  2964. char version[10];
  2965. char *vstring;
  2966. int vstrsize;
  2967. int i;
  2968. };
  2969. crState(do_ssh_connection_init_state);
  2970. crBeginState;
  2971. /* Search for a line beginning with the protocol name prefix in
  2972. * the input. */
  2973. for (;;) {
  2974. for (s->i = 0; protoname[s->i]; s->i++) {
  2975. if ((char)c != protoname[s->i]) goto no;
  2976. crReturn(1);
  2977. }
  2978. break;
  2979. no:
  2980. while (c != '\012')
  2981. crReturn(1);
  2982. crReturn(1);
  2983. }
  2984. s->vstrsize = sizeof(protoname) + 16;
  2985. s->vstring = snewn(s->vstrsize, char);
  2986. strcpy(s->vstring, protoname);
  2987. s->vslen = strlen(protoname);
  2988. s->i = 0;
  2989. while (1) {
  2990. if (s->vslen >= s->vstrsize - 1) {
  2991. s->vstrsize += 16;
  2992. s->vstring = sresize(s->vstring, s->vstrsize, char);
  2993. }
  2994. s->vstring[s->vslen++] = c;
  2995. if (s->i >= 0) {
  2996. if (c == '-') {
  2997. s->version[s->i] = '\0';
  2998. s->i = -1;
  2999. } else if (s->i < sizeof(s->version) - 1)
  3000. s->version[s->i++] = c;
  3001. } else if (c == '\012')
  3002. break;
  3003. crReturn(1); /* get another char */
  3004. }
  3005. ssh->agentfwd_enabled = FALSE;
  3006. ssh->rdpkt2_bare_state.incoming_sequence = 0;
  3007. s->vstring[s->vslen] = 0;
  3008. s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
  3009. logeventf(ssh, "Server version: %s", s->vstring);
  3010. ssh_detect_bugs(ssh, s->vstring);
  3011. /*
  3012. * Decide which SSH protocol version to support. This is easy in
  3013. * bare ssh-connection mode: only 2.0 is legal.
  3014. */
  3015. if (ssh_versioncmp(s->version, "2.0") < 0) {
  3016. bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
  3017. crStop(0);
  3018. }
  3019. if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
  3020. bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
  3021. crStop(0);
  3022. }
  3023. ssh->version = 2;
  3024. logeventf(ssh, "Using bare ssh-connection protocol");
  3025. /* Send the version string, if we haven't already */
  3026. ssh_send_verstring(ssh, protoname, s->version);
  3027. /*
  3028. * Initialise bare connection protocol.
  3029. */
  3030. ssh->protocol = ssh2_bare_connection_protocol;
  3031. ssh2_bare_connection_protocol_setup(ssh);
  3032. ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
  3033. update_specials_menu(ssh->frontend);
  3034. ssh->state = SSH_STATE_BEFORE_SIZE;
  3035. ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
  3036. /*
  3037. * Get authconn (really just conn) under way.
  3038. */
  3039. do_ssh2_authconn(ssh, NULL, 0, NULL);
  3040. sfree(s->vstring);
  3041. crFinish(0);
  3042. }
  3043. static void ssh_process_incoming_data(Ssh ssh,
  3044. const unsigned char **data, int *datalen)
  3045. {
  3046. struct Packet *pktin;
  3047. pktin = ssh->s_rdpkt(ssh, data, datalen);
  3048. if (pktin) {
  3049. ssh->protocol(ssh, NULL, 0, pktin);
  3050. ssh_free_packet(pktin);
  3051. }
  3052. }
  3053. static void ssh_queue_incoming_data(Ssh ssh,
  3054. const unsigned char **data, int *datalen)
  3055. {
  3056. bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
  3057. *data += *datalen;
  3058. *datalen = 0;
  3059. }
  3060. static void ssh_process_queued_incoming_data(Ssh ssh)
  3061. {
  3062. void *vdata;
  3063. const unsigned char *data;
  3064. int len, origlen;
  3065. while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
  3066. bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
  3067. data = vdata;
  3068. origlen = len;
  3069. while (!ssh->frozen && len > 0)
  3070. ssh_process_incoming_data(ssh, &data, &len);
  3071. if (origlen > len)
  3072. bufchain_consume(&ssh->queued_incoming_data, origlen - len);
  3073. }
  3074. }
  3075. static void ssh_set_frozen(Ssh ssh, int frozen)
  3076. {
  3077. if (ssh->s)
  3078. sk_set_frozen(ssh->s, frozen);
  3079. ssh->frozen = frozen;
  3080. }
  3081. static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
  3082. {
  3083. /* Log raw data, if we're in that mode. */
  3084. if (ssh->logctx)
  3085. log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
  3086. 0, NULL, NULL, 0, NULL);
  3087. crBegin(ssh->ssh_gotdata_crstate);
  3088. /*
  3089. * To begin with, feed the characters one by one to the
  3090. * protocol initialisation / selection function do_ssh_init().
  3091. * When that returns 0, we're done with the initial greeting
  3092. * exchange and can move on to packet discipline.
  3093. */
  3094. while (1) {
  3095. int ret; /* need not be kept across crReturn */
  3096. if (datalen == 0)
  3097. crReturnV; /* more data please */
  3098. ret = ssh->do_ssh_init(ssh, *data);
  3099. data++;
  3100. datalen--;
  3101. if (ret == 0)
  3102. break;
  3103. }
  3104. /*
  3105. * We emerge from that loop when the initial negotiation is
  3106. * over and we have selected an s_rdpkt function. Now pass
  3107. * everything to s_rdpkt, and then pass the resulting packets
  3108. * to the proper protocol handler.
  3109. */
  3110. while (1) {
  3111. while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
  3112. if (ssh->frozen) {
  3113. ssh_queue_incoming_data(ssh, &data, &datalen);
  3114. /* This uses up all data and cannot cause anything interesting
  3115. * to happen; indeed, for anything to happen at all, we must
  3116. * return, so break out. */
  3117. break;
  3118. } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
  3119. /* This uses up some or all data, and may freeze the
  3120. * session. */
  3121. ssh_process_queued_incoming_data(ssh);
  3122. } else {
  3123. /* This uses up some or all data, and may freeze the
  3124. * session. */
  3125. ssh_process_incoming_data(ssh, &data, &datalen);
  3126. }
  3127. /* FIXME this is probably EBW. */
  3128. if (ssh->state == SSH_STATE_CLOSED)
  3129. return;
  3130. }
  3131. /* We're out of data. Go and get some more. */
  3132. crReturnV;
  3133. }
  3134. crFinishV;
  3135. }
  3136. static int ssh_do_close(Ssh ssh, int notify_exit)
  3137. {
  3138. int ret = 0;
  3139. struct ssh_channel *c;
  3140. ssh->state = SSH_STATE_CLOSED;
  3141. expire_timer_context(ssh);
  3142. if (ssh->s) {
  3143. sk_close(ssh->s);
  3144. ssh->s = NULL;
  3145. if (notify_exit)
  3146. notify_remote_exit(ssh->frontend);
  3147. else
  3148. ret = 1;
  3149. }
  3150. /*
  3151. * Now we must shut down any port- and X-forwarded channels going
  3152. * through this connection.
  3153. */
  3154. if (ssh->channels) {
  3155. while (NULL != (c = index234(ssh->channels, 0))) {
  3156. ssh_channel_close_local(c, NULL);
  3157. del234(ssh->channels, c); /* moving next one to index 0 */
  3158. if (ssh->version == 2)
  3159. bufchain_clear(&c->v.v2.outbuffer);
  3160. sfree(c);
  3161. }
  3162. }
  3163. /*
  3164. * Go through port-forwardings, and close any associated
  3165. * listening sockets.
  3166. */
  3167. if (ssh->portfwds) {
  3168. struct ssh_portfwd *pf;
  3169. while (NULL != (pf = index234(ssh->portfwds, 0))) {
  3170. /* Dispose of any listening socket. */
  3171. if (pf->local)
  3172. pfl_terminate(pf->local);
  3173. del234(ssh->portfwds, pf); /* moving next one to index 0 */
  3174. free_portfwd(pf);
  3175. }
  3176. freetree234(ssh->portfwds);
  3177. ssh->portfwds = NULL;
  3178. }
  3179. /*
  3180. * Also stop attempting to connection-share.
  3181. */
  3182. if (ssh->connshare) {
  3183. sharestate_free(ssh->connshare);
  3184. ssh->connshare = NULL;
  3185. }
  3186. return ret;
  3187. }
  3188. static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
  3189. const char *error_msg, int error_code)
  3190. {
  3191. Ssh ssh = (Ssh) plug;
  3192. /*
  3193. * While we're attempting connection sharing, don't loudly log
  3194. * everything that happens. Real TCP connections need to be logged
  3195. * when we _start_ trying to connect, because it might be ages
  3196. * before they respond if something goes wrong; but connection
  3197. * sharing is local and quick to respond, and it's sufficient to
  3198. * simply wait and see whether it worked afterwards.
  3199. */
  3200. if (!ssh->attempting_connshare)
  3201. backend_socket_log(ssh->frontend, type, addr, port,
  3202. error_msg, error_code, ssh->conf,
  3203. ssh->session_started);
  3204. }
  3205. void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
  3206. const char *ds_err, const char *us_err)
  3207. {
  3208. if (event == SHARE_NONE) {
  3209. /* In this case, 'logtext' is an error message indicating a
  3210. * reason why connection sharing couldn't be set up _at all_.
  3211. * Failing that, ds_err and us_err indicate why we couldn't be
  3212. * a downstream and an upstream respectively. */
  3213. if (logtext) {
  3214. logeventf(ssh, "Could not set up connection sharing: %s", logtext);
  3215. } else {
  3216. if (ds_err)
  3217. logeventf(ssh, "Could not set up connection sharing"
  3218. " as downstream: %s", ds_err);
  3219. if (us_err)
  3220. logeventf(ssh, "Could not set up connection sharing"
  3221. " as upstream: %s", us_err);
  3222. }
  3223. } else if (event == SHARE_DOWNSTREAM) {
  3224. /* In this case, 'logtext' is a local endpoint address */
  3225. logeventf(ssh, "Using existing shared connection at %s", logtext);
  3226. /* Also we should mention this in the console window to avoid
  3227. * confusing users as to why this window doesn't behave the
  3228. * usual way. */
  3229. if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
  3230. c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
  3231. }
  3232. } else if (event == SHARE_UPSTREAM) {
  3233. /* In this case, 'logtext' is a local endpoint address too */
  3234. logeventf(ssh, "Sharing this connection at %s", logtext);
  3235. }
  3236. }
  3237. static void ssh_closing(Plug plug, const char *error_msg, int error_code,
  3238. int calling_back)
  3239. {
  3240. Ssh ssh = (Ssh) plug;
  3241. int need_notify = ssh_do_close(ssh, FALSE);
  3242. if (!error_msg) {
  3243. if (!ssh->close_expected)
  3244. error_msg = "Server unexpectedly closed network connection";
  3245. else
  3246. error_msg = "Server closed network connection";
  3247. }
  3248. if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
  3249. ssh->exitcode = 0;
  3250. if (need_notify)
  3251. notify_remote_exit(ssh->frontend);
  3252. if (error_msg)
  3253. logevent(error_msg);
  3254. if (!ssh->close_expected || !ssh->clean_exit)
  3255. connection_fatal(ssh->frontend, "%s", error_msg);
  3256. }
  3257. static void ssh_receive(Plug plug, int urgent, char *data, int len)
  3258. {
  3259. Ssh ssh = (Ssh) plug;
  3260. ssh_gotdata(ssh, (unsigned char *)data, len);
  3261. if (ssh->state == SSH_STATE_CLOSED) {
  3262. ssh_do_close(ssh, TRUE);
  3263. }
  3264. }
  3265. static void ssh_sent(Plug plug, int bufsize)
  3266. {
  3267. Ssh ssh = (Ssh) plug;
  3268. /*
  3269. * If the send backlog on the SSH socket itself clears, we
  3270. * should unthrottle the whole world if it was throttled.
  3271. */
  3272. if (bufsize < SSH_MAX_BACKLOG)
  3273. {
  3274. ssh_throttle_all(ssh, 0, bufsize);
  3275. }
  3276. }
  3277. static void ssh_hostport_setup(const char *host, int port, Conf *conf,
  3278. char **savedhost, int *savedport,
  3279. char **loghost_ret)
  3280. {
  3281. char *loghost = conf_get_str(conf, CONF_loghost);
  3282. if (loghost_ret)
  3283. *loghost_ret = loghost;
  3284. if (*loghost) {
  3285. char *tmphost;
  3286. char *colon;
  3287. tmphost = dupstr(loghost);
  3288. *savedport = 22; /* default ssh port */
  3289. /*
  3290. * A colon suffix on the hostname string also lets us affect
  3291. * savedport. (Unless there are multiple colons, in which case
  3292. * we assume this is an unbracketed IPv6 literal.)
  3293. */
  3294. colon = host_strrchr(tmphost, ':');
  3295. if (colon && colon == host_strchr(tmphost, ':')) {
  3296. *colon++ = '\0';
  3297. if (*colon)
  3298. *savedport = atoi(colon);
  3299. }
  3300. *savedhost = host_strduptrim(tmphost);
  3301. sfree(tmphost);
  3302. } else {
  3303. *savedhost = host_strduptrim(host);
  3304. if (port < 0)
  3305. port = 22; /* default ssh port */
  3306. *savedport = port;
  3307. }
  3308. }
  3309. static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
  3310. {
  3311. char *savedhost;
  3312. int savedport;
  3313. int ret;
  3314. random_ref(); /* platform may need this to determine share socket name */
  3315. ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
  3316. ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
  3317. sfree(savedhost);
  3318. random_unref();
  3319. return ret;
  3320. }
  3321. /*
  3322. * Connect to specified host and port.
  3323. * Returns an error message, or NULL on success.
  3324. * Also places the canonical host name into `realhost'. It must be
  3325. * freed by the caller.
  3326. */
  3327. static const char *connect_to_host(Ssh ssh, const char *host, int port,
  3328. char **realhost, int nodelay, int keepalive)
  3329. {
  3330. static const struct plug_function_table fn_table = {
  3331. ssh_socket_log,
  3332. ssh_closing,
  3333. ssh_receive,
  3334. ssh_sent,
  3335. NULL
  3336. };
  3337. SockAddr addr;
  3338. const char *err;
  3339. char *loghost;
  3340. int addressfamily, sshprot;
  3341. ssh_hostport_setup(host, port, ssh->conf,
  3342. &ssh->savedhost, &ssh->savedport, &loghost);
  3343. #ifdef MPEXT
  3344. // make sure the field is initialized, in case lookup below fails
  3345. ssh->fullhostname = NULL;
  3346. #endif
  3347. ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
  3348. /*
  3349. * Try connection-sharing, in case that means we don't open a
  3350. * socket after all. ssh_connection_sharing_init will connect to a
  3351. * previously established upstream if it can, and failing that,
  3352. * establish a listening socket for _us_ to be the upstream. In
  3353. * the latter case it will return NULL just as if it had done
  3354. * nothing, because here we only need to care if we're a
  3355. * downstream and need to do our connection setup differently.
  3356. */
  3357. ssh->connshare = NULL;
  3358. ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
  3359. ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
  3360. ssh->conf, ssh, &ssh->connshare);
  3361. ssh->attempting_connshare = FALSE;
  3362. if (ssh->s != NULL) {
  3363. /*
  3364. * We are a downstream.
  3365. */
  3366. ssh->bare_connection = TRUE;
  3367. ssh->do_ssh_init = do_ssh_connection_init;
  3368. ssh->fullhostname = NULL;
  3369. *realhost = dupstr(host); /* best we can do */
  3370. } else {
  3371. /*
  3372. * We're not a downstream, so open a normal socket.
  3373. */
  3374. ssh->do_ssh_init = do_ssh_init;
  3375. /*
  3376. * Try to find host.
  3377. */
  3378. addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
  3379. addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
  3380. ssh->frontend, "SSH connection");
  3381. if ((err = sk_addr_error(addr)) != NULL) {
  3382. sk_addr_free(addr);
  3383. return err;
  3384. }
  3385. ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
  3386. ssh->s = new_connection(addr, *realhost, port,
  3387. 0, 1, nodelay, keepalive,
  3388. (Plug) ssh, ssh->conf);
  3389. if ((err = sk_socket_error(ssh->s)) != NULL) {
  3390. ssh->s = NULL;
  3391. notify_remote_exit(ssh->frontend);
  3392. return err;
  3393. }
  3394. }
  3395. /*
  3396. * The SSH version number is always fixed (since we no longer support
  3397. * fallback between versions), so set it now, and if it's SSH-2,
  3398. * send the version string now too.
  3399. */
  3400. sshprot = conf_get_int(ssh->conf, CONF_sshprot);
  3401. assert(sshprot == 0 || sshprot == 3);
  3402. if (sshprot == 0)
  3403. /* SSH-1 only */
  3404. ssh->version = 1;
  3405. if (sshprot == 3 && !ssh->bare_connection) {
  3406. /* SSH-2 only */
  3407. ssh->version = 2;
  3408. ssh_send_verstring(ssh, "SSH-", NULL);
  3409. }
  3410. /*
  3411. * loghost, if configured, overrides realhost.
  3412. */
  3413. if (*loghost) {
  3414. sfree(*realhost);
  3415. *realhost = dupstr(loghost);
  3416. }
  3417. return NULL;
  3418. }
  3419. /*
  3420. * Throttle or unthrottle the SSH connection.
  3421. */
  3422. static void ssh_throttle_conn(Ssh ssh, int adjust)
  3423. {
  3424. int old_count = ssh->conn_throttle_count;
  3425. ssh->conn_throttle_count += adjust;
  3426. assert(ssh->conn_throttle_count >= 0);
  3427. if (ssh->conn_throttle_count && !old_count) {
  3428. ssh_set_frozen(ssh, 1);
  3429. } else if (!ssh->conn_throttle_count && old_count) {
  3430. ssh_set_frozen(ssh, 0);
  3431. }
  3432. }
  3433. static void ssh_agentf_try_forward(struct ssh_channel *c);
  3434. /*
  3435. * Throttle or unthrottle _all_ local data streams (for when sends
  3436. * on the SSH connection itself back up).
  3437. */
  3438. static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
  3439. {
  3440. int i;
  3441. struct ssh_channel *c;
  3442. if (enable == ssh->throttled_all)
  3443. return;
  3444. ssh->throttled_all = enable;
  3445. ssh->overall_bufsize = bufsize;
  3446. if (!ssh->channels)
  3447. return;
  3448. for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
  3449. switch (c->type) {
  3450. case CHAN_MAINSESSION:
  3451. /*
  3452. * This is treated separately, outside the switch.
  3453. */
  3454. break;
  3455. case CHAN_X11:
  3456. x11_override_throttle(c->u.x11.xconn, enable);
  3457. break;
  3458. case CHAN_AGENT:
  3459. /* Agent forwarding channels are buffer-managed by
  3460. * checking ssh->throttled_all in ssh_agentf_try_forward.
  3461. * So at the moment we _un_throttle again, we must make an
  3462. * attempt to do something. */
  3463. if (!enable)
  3464. ssh_agentf_try_forward(c);
  3465. break;
  3466. case CHAN_SOCKDATA:
  3467. pfd_override_throttle(c->u.pfd.pf, enable);
  3468. break;
  3469. }
  3470. }
  3471. }
  3472. static void ssh_agent_callback(void *sshv, void *reply, int replylen)
  3473. {
  3474. Ssh ssh = (Ssh) sshv;
  3475. ssh->auth_agent_query = NULL;
  3476. ssh->agent_response = reply;
  3477. ssh->agent_response_len = replylen;
  3478. if (ssh->version == 1)
  3479. do_ssh1_login(ssh, NULL, -1, NULL);
  3480. else
  3481. do_ssh2_authconn(ssh, NULL, -1, NULL);
  3482. }
  3483. static void ssh_dialog_callback(void *sshv, int ret)
  3484. {
  3485. Ssh ssh = (Ssh) sshv;
  3486. ssh->user_response = ret;
  3487. if (ssh->version == 1)
  3488. do_ssh1_login(ssh, NULL, -1, NULL);
  3489. else
  3490. do_ssh2_transport(ssh, NULL, -1, NULL);
  3491. /*
  3492. * This may have unfrozen the SSH connection, so do a
  3493. * queued-data run.
  3494. */
  3495. ssh_process_queued_incoming_data(ssh);
  3496. }
  3497. static void ssh_agentf_got_response(struct ssh_channel *c,
  3498. void *reply, int replylen)
  3499. {
  3500. c->u.a.pending = NULL;
  3501. assert(!(c->closes & CLOSES_SENT_EOF));
  3502. if (!reply) {
  3503. /* The real agent didn't send any kind of reply at all for
  3504. * some reason, so fake an SSH_AGENT_FAILURE. */
  3505. reply = "\0\0\0\1\5";
  3506. replylen = 5;
  3507. }
  3508. ssh_send_channel_data(c, reply, replylen);
  3509. }
  3510. static void ssh_agentf_callback(void *cv, void *reply, int replylen);
  3511. static void ssh_agentf_try_forward(struct ssh_channel *c)
  3512. {
  3513. unsigned datalen, lengthfield, messagelen;
  3514. unsigned char *message;
  3515. unsigned char msglen[4];
  3516. void *reply;
  3517. int replylen;
  3518. /*
  3519. * Don't try to parallelise agent requests. Wait for each one to
  3520. * return before attempting the next.
  3521. */
  3522. if (c->u.a.pending)
  3523. return;
  3524. /*
  3525. * If the outgoing side of the channel connection is currently
  3526. * throttled (for any reason, either that channel's window size or
  3527. * the entire SSH connection being throttled), don't submit any
  3528. * new forwarded requests to the real agent. This causes the input
  3529. * side of the agent forwarding not to be emptied, exerting the
  3530. * required back-pressure on the remote client, and encouraging it
  3531. * to read our responses before sending too many more requests.
  3532. */
  3533. if (c->ssh->throttled_all ||
  3534. (c->ssh->version == 2 && c->v.v2.remwindow == 0))
  3535. return;
  3536. if (c->closes & CLOSES_SENT_EOF) {
  3537. /*
  3538. * If we've already sent outgoing EOF, there's nothing we can
  3539. * do with incoming data except consume it and throw it away.
  3540. */
  3541. bufchain_clear(&c->u.a.inbuffer);
  3542. return;
  3543. }
  3544. while (1) {
  3545. /*
  3546. * Try to extract a complete message from the input buffer.
  3547. */
  3548. datalen = bufchain_size(&c->u.a.inbuffer);
  3549. if (datalen < 4)
  3550. break; /* not even a length field available yet */
  3551. bufchain_fetch(&c->u.a.inbuffer, msglen, 4);
  3552. lengthfield = GET_32BIT(msglen);
  3553. if (lengthfield > AGENT_MAX_MSGLEN) {
  3554. /*
  3555. * If the remote has sent a message that's just _too_
  3556. * long, we should reject it in advance of seeing the rest
  3557. * of the incoming message, and also close the connection
  3558. * for good measure (which avoids us having to faff about
  3559. * with carefully ignoring just the right number of bytes
  3560. * from the overlong message).
  3561. */
  3562. ssh_agentf_got_response(c, NULL, 0);
  3563. sshfwd_write_eof(c);
  3564. return;
  3565. }
  3566. if (lengthfield > datalen - 4)
  3567. break; /* a whole message is not yet available */
  3568. messagelen = lengthfield + 4;
  3569. message = snewn(messagelen, unsigned char);
  3570. bufchain_fetch(&c->u.a.inbuffer, message, messagelen);
  3571. bufchain_consume(&c->u.a.inbuffer, messagelen);
  3572. c->u.a.pending = agent_query(
  3573. message, messagelen, &reply, &replylen, ssh_agentf_callback, c);
  3574. sfree(message);
  3575. if (c->u.a.pending)
  3576. return; /* agent_query promised to reply in due course */
  3577. /*
  3578. * If the agent gave us an answer immediately, pass it
  3579. * straight on and go round this loop again.
  3580. */
  3581. ssh_agentf_got_response(c, reply, replylen);
  3582. sfree(reply);
  3583. }
  3584. /*
  3585. * If we get here (i.e. we left the above while loop via 'break'
  3586. * rather than 'return'), that means we've determined that the
  3587. * input buffer for the agent forwarding connection doesn't
  3588. * contain a complete request.
  3589. *
  3590. * So if there's potentially more data to come, we can return now,
  3591. * and wait for the remote client to send it. But if the remote
  3592. * has sent EOF, it would be a mistake to do that, because we'd be
  3593. * waiting a long time. So this is the moment to check for EOF,
  3594. * and respond appropriately.
  3595. */
  3596. if (c->closes & CLOSES_RCVD_EOF)
  3597. sshfwd_write_eof(c);
  3598. }
  3599. static void ssh_agentf_callback(void *cv, void *reply, int replylen)
  3600. {
  3601. struct ssh_channel *c = (struct ssh_channel *)cv;
  3602. ssh_agentf_got_response(c, reply, replylen);
  3603. sfree(reply);
  3604. /*
  3605. * Now try to extract and send further messages from the channel's
  3606. * input-side buffer.
  3607. */
  3608. ssh_agentf_try_forward(c);
  3609. }
  3610. /*
  3611. * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
  3612. * non-NULL, otherwise just close the connection. `client_reason' == NULL
  3613. * => log `wire_reason'.
  3614. */
  3615. static void ssh_disconnect(Ssh ssh, const char *client_reason,
  3616. const char *wire_reason,
  3617. int code, int clean_exit)
  3618. {
  3619. char *error;
  3620. if (!client_reason)
  3621. client_reason = wire_reason;
  3622. if (client_reason)
  3623. error = dupprintf("Disconnected: %s", client_reason);
  3624. else
  3625. error = dupstr("Disconnected");
  3626. if (wire_reason) {
  3627. if (ssh->version == 1) {
  3628. send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
  3629. PKT_END);
  3630. } else if (ssh->version == 2) {
  3631. struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
  3632. ssh2_pkt_adduint32(pktout, code);
  3633. ssh2_pkt_addstring(pktout, wire_reason);
  3634. ssh2_pkt_addstring(pktout, "en"); /* language tag */
  3635. ssh2_pkt_send_noqueue(ssh, pktout);
  3636. }
  3637. }
  3638. ssh->close_expected = TRUE;
  3639. ssh->clean_exit = clean_exit;
  3640. ssh_closing((Plug)ssh, error, 0, 0);
  3641. sfree(error);
  3642. }
  3643. int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
  3644. const struct ssh_signkey *ssh2keytype,
  3645. void *ssh2keydata)
  3646. {
  3647. if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
  3648. return -1; /* no manual keys configured */
  3649. }
  3650. if (fingerprint) {
  3651. /*
  3652. * The fingerprint string we've been given will have things
  3653. * like 'ssh-rsa 2048' at the front of it. Strip those off and
  3654. * narrow down to just the colon-separated hex block at the
  3655. * end of the string.
  3656. */
  3657. const char *p = strrchr(fingerprint, ' ');
  3658. fingerprint = p ? p+1 : fingerprint;
  3659. /* Quick sanity checks, including making sure it's in lowercase */
  3660. assert(strlen(fingerprint) == 16*3 - 1);
  3661. assert(fingerprint[2] == ':');
  3662. assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
  3663. if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
  3664. fingerprint))
  3665. return 1; /* success */
  3666. }
  3667. if (ssh2keydata) {
  3668. /*
  3669. * Construct the base64-encoded public key blob and see if
  3670. * that's listed.
  3671. */
  3672. unsigned char *binblob;
  3673. char *base64blob;
  3674. int binlen, atoms, i;
  3675. binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
  3676. atoms = (binlen + 2) / 3;
  3677. base64blob = snewn(atoms * 4 + 1, char);
  3678. for (i = 0; i < atoms; i++)
  3679. base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
  3680. base64blob[atoms * 4] = '\0';
  3681. sfree(binblob);
  3682. if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
  3683. base64blob)) {
  3684. sfree(base64blob);
  3685. return 1; /* success */
  3686. }
  3687. sfree(base64blob);
  3688. }
  3689. return 0;
  3690. }
  3691. /*
  3692. * Handle the key exchange and user authentication phases.
  3693. */
  3694. static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
  3695. struct Packet *pktin)
  3696. {
  3697. int i, j, ret;
  3698. unsigned char cookie[8], *ptr;
  3699. struct MD5Context md5c;
  3700. struct do_ssh1_login_state {
  3701. int crLine;
  3702. int len;
  3703. unsigned char *rsabuf;
  3704. const unsigned char *keystr1, *keystr2;
  3705. unsigned long supported_ciphers_mask, supported_auths_mask;
  3706. int tried_publickey, tried_agent;
  3707. int tis_auth_refused, ccard_auth_refused;
  3708. unsigned char session_id[16];
  3709. int cipher_type;
  3710. void *publickey_blob;
  3711. int publickey_bloblen;
  3712. char *publickey_comment;
  3713. int privatekey_available, privatekey_encrypted;
  3714. prompts_t *cur_prompt;
  3715. char c;
  3716. int pwpkt_type;
  3717. unsigned char request[5], *response, *p;
  3718. int responselen;
  3719. int keyi, nkeys;
  3720. int authed;
  3721. struct RSAKey key;
  3722. Bignum challenge;
  3723. char *commentp;
  3724. int commentlen;
  3725. int dlgret;
  3726. Filename *keyfile;
  3727. struct RSAKey servkey, hostkey;
  3728. };
  3729. crState(do_ssh1_login_state);
  3730. crBeginState;
  3731. if (!pktin)
  3732. crWaitUntil(pktin);
  3733. if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
  3734. bombout(("Public key packet not received"));
  3735. crStop(0);
  3736. }
  3737. logevent("Received public keys");
  3738. ptr = ssh_pkt_getdata(pktin, 8);
  3739. if (!ptr) {
  3740. bombout(("SSH-1 public key packet stopped before random cookie"));
  3741. crStop(0);
  3742. }
  3743. memcpy(cookie, ptr, 8);
  3744. if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
  3745. !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
  3746. bombout(("Failed to read SSH-1 public keys from public key packet"));
  3747. crStop(0);
  3748. }
  3749. /*
  3750. * Log the host key fingerprint.
  3751. */
  3752. {
  3753. char logmsg[80];
  3754. logevent("Host key fingerprint is:");
  3755. strcpy(logmsg, " ");
  3756. s->hostkey.comment = NULL;
  3757. rsa_fingerprint(logmsg + strlen(logmsg),
  3758. sizeof(logmsg) - strlen(logmsg), &s->hostkey);
  3759. logevent(logmsg);
  3760. }
  3761. ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
  3762. s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
  3763. s->supported_auths_mask = ssh_pkt_getuint32(pktin);
  3764. if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
  3765. s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
  3766. ssh->v1_local_protoflags =
  3767. ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
  3768. ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
  3769. MD5Init(&md5c);
  3770. MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
  3771. MD5Update(&md5c, s->keystr1, s->servkey.bytes);
  3772. MD5Update(&md5c, cookie, 8);
  3773. MD5Final(s->session_id, &md5c);
  3774. for (i = 0; i < 32; i++)
  3775. ssh->session_key[i] = random_byte();
  3776. /*
  3777. * Verify that the `bits' and `bytes' parameters match.
  3778. */
  3779. if (s->hostkey.bits > s->hostkey.bytes * 8 ||
  3780. s->servkey.bits > s->servkey.bytes * 8) {
  3781. bombout(("SSH-1 public keys were badly formatted"));
  3782. crStop(0);
  3783. }
  3784. s->len = 32;
  3785. if (s->len < s->hostkey.bytes)
  3786. s->len = s->hostkey.bytes;
  3787. if (s->len < s->servkey.bytes)
  3788. s->len = s->servkey.bytes;
  3789. s->rsabuf = snewn(s->len, unsigned char);
  3790. /*
  3791. * Verify the host key.
  3792. */
  3793. {
  3794. /*
  3795. * First format the key into a string.
  3796. */
  3797. int len = rsastr_len(&s->hostkey);
  3798. char fingerprint[100];
  3799. char *keystr = snewn(len, char);
  3800. rsastr_fmt(keystr, &s->hostkey);
  3801. rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
  3802. /* First check against manually configured host keys. */
  3803. s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
  3804. if (s->dlgret == 0) { /* did not match */
  3805. bombout(("Host key did not appear in manually configured list"));
  3806. sfree(keystr);
  3807. crStop(0);
  3808. } else if (s->dlgret < 0) { /* none configured; use standard handling */
  3809. ssh_set_frozen(ssh, 1);
  3810. s->dlgret = verify_ssh_host_key(ssh->frontend,
  3811. ssh->savedhost, ssh->savedport,
  3812. "rsa", keystr, fingerprint,
  3813. ssh_dialog_callback, ssh);
  3814. sfree(keystr);
  3815. #ifdef FUZZING
  3816. s->dlgret = 1;
  3817. #endif
  3818. if (s->dlgret < 0) {
  3819. do {
  3820. crReturn(0);
  3821. if (pktin) {
  3822. bombout(("Unexpected data from server while waiting"
  3823. " for user host key response"));
  3824. crStop(0);
  3825. }
  3826. } while (pktin || inlen > 0);
  3827. s->dlgret = ssh->user_response;
  3828. }
  3829. ssh_set_frozen(ssh, 0);
  3830. if (s->dlgret == 0) {
  3831. ssh_disconnect(ssh, "User aborted at host key verification",
  3832. NULL, 0, TRUE);
  3833. crStop(0);
  3834. }
  3835. } else {
  3836. sfree(keystr);
  3837. }
  3838. }
  3839. for (i = 0; i < 32; i++) {
  3840. s->rsabuf[i] = ssh->session_key[i];
  3841. if (i < 16)
  3842. s->rsabuf[i] ^= s->session_id[i];
  3843. }
  3844. if (s->hostkey.bytes > s->servkey.bytes) {
  3845. ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
  3846. if (ret)
  3847. ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
  3848. } else {
  3849. ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
  3850. if (ret)
  3851. ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
  3852. }
  3853. if (!ret) {
  3854. bombout(("SSH-1 public key encryptions failed due to bad formatting"));
  3855. crStop(0);
  3856. }
  3857. logevent("Encrypted session key");
  3858. {
  3859. int cipher_chosen = 0, warn = 0;
  3860. const char *cipher_string = NULL;
  3861. int i;
  3862. for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
  3863. int next_cipher = conf_get_int_int(ssh->conf,
  3864. CONF_ssh_cipherlist, i);
  3865. if (next_cipher == CIPHER_WARN) {
  3866. /* If/when we choose a cipher, warn about it */
  3867. warn = 1;
  3868. } else if (next_cipher == CIPHER_AES) {
  3869. /* XXX Probably don't need to mention this. */
  3870. logevent("AES not supported in SSH-1, skipping");
  3871. } else {
  3872. switch (next_cipher) {
  3873. case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
  3874. cipher_string = "3DES"; break;
  3875. case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
  3876. cipher_string = "Blowfish"; break;
  3877. case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
  3878. cipher_string = "single-DES"; break;
  3879. }
  3880. if (s->supported_ciphers_mask & (1 << s->cipher_type))
  3881. cipher_chosen = 1;
  3882. }
  3883. }
  3884. if (!cipher_chosen) {
  3885. if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
  3886. bombout(("Server violates SSH-1 protocol by not "
  3887. "supporting 3DES encryption"));
  3888. else
  3889. /* shouldn't happen */
  3890. bombout(("No supported ciphers found"));
  3891. crStop(0);
  3892. }
  3893. /* Warn about chosen cipher if necessary. */
  3894. if (warn) {
  3895. ssh_set_frozen(ssh, 1);
  3896. s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
  3897. ssh_dialog_callback, ssh);
  3898. if (s->dlgret < 0) {
  3899. do {
  3900. crReturn(0);
  3901. if (pktin) {
  3902. bombout(("Unexpected data from server while waiting"
  3903. " for user response"));
  3904. crStop(0);
  3905. }
  3906. } while (pktin || inlen > 0);
  3907. s->dlgret = ssh->user_response;
  3908. }
  3909. ssh_set_frozen(ssh, 0);
  3910. if (s->dlgret == 0) {
  3911. ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
  3912. 0, TRUE);
  3913. crStop(0);
  3914. }
  3915. }
  3916. }
  3917. switch (s->cipher_type) {
  3918. case SSH_CIPHER_3DES:
  3919. logevent("Using 3DES encryption");
  3920. break;
  3921. case SSH_CIPHER_DES:
  3922. logevent("Using single-DES encryption");
  3923. break;
  3924. case SSH_CIPHER_BLOWFISH:
  3925. logevent("Using Blowfish encryption");
  3926. break;
  3927. }
  3928. send_packet(ssh, SSH1_CMSG_SESSION_KEY,
  3929. PKT_CHAR, s->cipher_type,
  3930. PKT_DATA, cookie, 8,
  3931. PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
  3932. PKT_DATA, s->rsabuf, s->len,
  3933. PKT_INT, ssh->v1_local_protoflags, PKT_END);
  3934. logevent("Trying to enable encryption...");
  3935. sfree(s->rsabuf);
  3936. ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
  3937. s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
  3938. &ssh_3des);
  3939. ssh->v1_cipher_ctx = ssh->cipher->make_context();
  3940. ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
  3941. logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
  3942. ssh->crcda_ctx = crcda_make_context();
  3943. logevent("Installing CRC compensation attack detector");
  3944. if (s->servkey.modulus) {
  3945. sfree(s->servkey.modulus);
  3946. s->servkey.modulus = NULL;
  3947. }
  3948. if (s->servkey.exponent) {
  3949. sfree(s->servkey.exponent);
  3950. s->servkey.exponent = NULL;
  3951. }
  3952. if (s->hostkey.modulus) {
  3953. sfree(s->hostkey.modulus);
  3954. s->hostkey.modulus = NULL;
  3955. }
  3956. if (s->hostkey.exponent) {
  3957. sfree(s->hostkey.exponent);
  3958. s->hostkey.exponent = NULL;
  3959. }
  3960. crWaitUntil(pktin);
  3961. if (pktin->type != SSH1_SMSG_SUCCESS) {
  3962. bombout(("Encryption not successfully enabled"));
  3963. crStop(0);
  3964. }
  3965. logevent("Successfully started encryption");
  3966. fflush(stdout); /* FIXME eh? */
  3967. {
  3968. if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
  3969. int ret; /* need not be kept over crReturn */
  3970. s->cur_prompt = new_prompts(ssh->frontend);
  3971. s->cur_prompt->to_server = TRUE;
  3972. s->cur_prompt->name = dupstr("SSH login name");
  3973. add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
  3974. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  3975. while (ret < 0) {
  3976. ssh->send_ok = 1;
  3977. crWaitUntil(!pktin);
  3978. ret = get_userpass_input(s->cur_prompt, in, inlen);
  3979. ssh->send_ok = 0;
  3980. }
  3981. if (!ret) {
  3982. /*
  3983. * Failed to get a username. Terminate.
  3984. */
  3985. free_prompts(s->cur_prompt);
  3986. ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
  3987. crStop(0);
  3988. }
  3989. ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
  3990. free_prompts(s->cur_prompt);
  3991. }
  3992. send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
  3993. {
  3994. char *userlog = dupprintf(MPEXT_BOM "Sent username \"%s\"", ssh->username);
  3995. logevent(userlog);
  3996. if (flags & FLAG_INTERACTIVE &&
  3997. (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
  3998. c_write_str(ssh, userlog);
  3999. c_write_str(ssh, "\r\n");
  4000. }
  4001. sfree(userlog);
  4002. }
  4003. }
  4004. crWaitUntil(pktin);
  4005. if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
  4006. /* We must not attempt PK auth. Pretend we've already tried it. */
  4007. s->tried_publickey = s->tried_agent = 1;
  4008. } else {
  4009. s->tried_publickey = s->tried_agent = 0;
  4010. }
  4011. s->tis_auth_refused = s->ccard_auth_refused = 0;
  4012. /*
  4013. * Load the public half of any configured keyfile for later use.
  4014. */
  4015. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  4016. if (!filename_is_null(s->keyfile)) {
  4017. int keytype;
  4018. logeventf(ssh, MPEXT_BOM "Reading key file \"%.150s\"",
  4019. filename_to_str(s->keyfile));
  4020. keytype = key_type(s->keyfile);
  4021. if (keytype == SSH_KEYTYPE_SSH1 ||
  4022. keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
  4023. const char *error;
  4024. if (rsakey_pubblob(s->keyfile,
  4025. &s->publickey_blob, &s->publickey_bloblen,
  4026. &s->publickey_comment, &error)) {
  4027. s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
  4028. if (!s->privatekey_available)
  4029. logeventf(ssh, "Key file contains public key only");
  4030. s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
  4031. NULL);
  4032. } else {
  4033. char *msgbuf;
  4034. logeventf(ssh, "Unable to load key (%s)", error);
  4035. msgbuf = dupprintf(MPEXT_BOM "Unable to load key file "
  4036. "\"%.150s\" (%s)\r\n",
  4037. filename_to_str(s->keyfile),
  4038. error);
  4039. c_write_str(ssh, msgbuf);
  4040. sfree(msgbuf);
  4041. s->publickey_blob = NULL;
  4042. }
  4043. } else {
  4044. char *msgbuf;
  4045. logeventf(ssh, "Unable to use this key file (%s)",
  4046. key_type_to_str(keytype));
  4047. msgbuf = dupprintf(MPEXT_BOM "Unable to use key file \"%.150s\""
  4048. " (%s)\r\n",
  4049. filename_to_str(s->keyfile),
  4050. key_type_to_str(keytype));
  4051. c_write_str(ssh, msgbuf);
  4052. sfree(msgbuf);
  4053. s->publickey_blob = NULL;
  4054. }
  4055. } else
  4056. s->publickey_blob = NULL;
  4057. while (pktin->type == SSH1_SMSG_FAILURE) {
  4058. s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
  4059. if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
  4060. /*
  4061. * Attempt RSA authentication using Pageant.
  4062. */
  4063. void *r;
  4064. s->authed = FALSE;
  4065. s->tried_agent = 1;
  4066. logevent("Pageant is running. Requesting keys.");
  4067. /* Request the keys held by the agent. */
  4068. PUT_32BIT(s->request, 1);
  4069. s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
  4070. ssh->auth_agent_query = agent_query(
  4071. s->request, 5, &r, &s->responselen, ssh_agent_callback, ssh);
  4072. if (ssh->auth_agent_query) {
  4073. do {
  4074. crReturn(0);
  4075. if (pktin) {
  4076. bombout(("Unexpected data from server while waiting"
  4077. " for agent response"));
  4078. crStop(0);
  4079. }
  4080. } while (pktin || inlen > 0);
  4081. r = ssh->agent_response;
  4082. s->responselen = ssh->agent_response_len;
  4083. }
  4084. s->response = (unsigned char *) r;
  4085. if (s->response && s->responselen >= 5 &&
  4086. s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
  4087. s->p = s->response + 5;
  4088. s->nkeys = toint(GET_32BIT(s->p));
  4089. if (s->nkeys < 0) {
  4090. logeventf(ssh, "Pageant reported negative key count %d",
  4091. s->nkeys);
  4092. s->nkeys = 0;
  4093. }
  4094. s->p += 4;
  4095. logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
  4096. for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
  4097. unsigned char *pkblob = s->p;
  4098. s->p += 4;
  4099. {
  4100. int n, ok = FALSE;
  4101. do { /* do while (0) to make breaking easy */
  4102. n = ssh1_read_bignum
  4103. (s->p, toint(s->responselen-(s->p-s->response)),
  4104. &s->key.exponent);
  4105. if (n < 0)
  4106. break;
  4107. s->p += n;
  4108. n = ssh1_read_bignum
  4109. (s->p, toint(s->responselen-(s->p-s->response)),
  4110. &s->key.modulus);
  4111. if (n < 0)
  4112. break;
  4113. s->p += n;
  4114. if (s->responselen - (s->p-s->response) < 4)
  4115. break;
  4116. s->commentlen = toint(GET_32BIT(s->p));
  4117. s->p += 4;
  4118. if (s->commentlen < 0 ||
  4119. toint(s->responselen - (s->p-s->response)) <
  4120. s->commentlen)
  4121. break;
  4122. s->commentp = (char *)s->p;
  4123. s->p += s->commentlen;
  4124. ok = TRUE;
  4125. } while (0);
  4126. if (!ok) {
  4127. logevent("Pageant key list packet was truncated");
  4128. break;
  4129. }
  4130. }
  4131. if (s->publickey_blob) {
  4132. if (!memcmp(pkblob, s->publickey_blob,
  4133. s->publickey_bloblen)) {
  4134. logeventf(ssh, "Pageant key #%d matches "
  4135. "configured key file", s->keyi);
  4136. s->tried_publickey = 1;
  4137. } else
  4138. /* Skip non-configured key */
  4139. continue;
  4140. }
  4141. logeventf(ssh, "Trying Pageant key #%d", s->keyi);
  4142. send_packet(ssh, SSH1_CMSG_AUTH_RSA,
  4143. PKT_BIGNUM, s->key.modulus, PKT_END);
  4144. crWaitUntil(pktin);
  4145. if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
  4146. logevent("Key refused");
  4147. continue;
  4148. }
  4149. logevent("Received RSA challenge");
  4150. if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
  4151. bombout(("Server's RSA challenge was badly formatted"));
  4152. crStop(0);
  4153. }
  4154. {
  4155. char *agentreq, *q, *ret;
  4156. void *vret;
  4157. int len, retlen;
  4158. len = 1 + 4; /* message type, bit count */
  4159. len += ssh1_bignum_length(s->key.exponent);
  4160. len += ssh1_bignum_length(s->key.modulus);
  4161. len += ssh1_bignum_length(s->challenge);
  4162. len += 16; /* session id */
  4163. len += 4; /* response format */
  4164. agentreq = snewn(4 + len, char);
  4165. PUT_32BIT(agentreq, len);
  4166. q = agentreq + 4;
  4167. *q++ = SSH1_AGENTC_RSA_CHALLENGE;
  4168. PUT_32BIT(q, bignum_bitcount(s->key.modulus));
  4169. q += 4;
  4170. q += ssh1_write_bignum(q, s->key.exponent);
  4171. q += ssh1_write_bignum(q, s->key.modulus);
  4172. q += ssh1_write_bignum(q, s->challenge);
  4173. memcpy(q, s->session_id, 16);
  4174. q += 16;
  4175. PUT_32BIT(q, 1); /* response format */
  4176. ssh->auth_agent_query = agent_query(
  4177. agentreq, len + 4, &vret, &retlen,
  4178. ssh_agent_callback, ssh);
  4179. if (ssh->auth_agent_query) {
  4180. sfree(agentreq);
  4181. do {
  4182. crReturn(0);
  4183. if (pktin) {
  4184. bombout(("Unexpected data from server"
  4185. " while waiting for agent"
  4186. " response"));
  4187. crStop(0);
  4188. }
  4189. } while (pktin || inlen > 0);
  4190. vret = ssh->agent_response;
  4191. retlen = ssh->agent_response_len;
  4192. } else
  4193. sfree(agentreq);
  4194. ret = vret;
  4195. if (ret) {
  4196. if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
  4197. logevent("Sending Pageant's response");
  4198. send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
  4199. PKT_DATA, ret + 5, 16,
  4200. PKT_END);
  4201. sfree(ret);
  4202. crWaitUntil(pktin);
  4203. if (pktin->type == SSH1_SMSG_SUCCESS) {
  4204. logevent
  4205. ("Pageant's response accepted");
  4206. if (flags & FLAG_VERBOSE) {
  4207. c_write_str(ssh, "Authenticated using"
  4208. " RSA key \"");
  4209. c_write(ssh, s->commentp,
  4210. s->commentlen);
  4211. c_write_str(ssh, "\" from agent\r\n");
  4212. }
  4213. s->authed = TRUE;
  4214. } else
  4215. logevent
  4216. ("Pageant's response not accepted");
  4217. } else {
  4218. logevent
  4219. ("Pageant failed to answer challenge");
  4220. sfree(ret);
  4221. }
  4222. } else {
  4223. logevent("No reply received from Pageant");
  4224. }
  4225. }
  4226. freebn(s->key.exponent);
  4227. freebn(s->key.modulus);
  4228. freebn(s->challenge);
  4229. if (s->authed)
  4230. break;
  4231. }
  4232. sfree(s->response);
  4233. if (s->publickey_blob && !s->tried_publickey)
  4234. logevent("Configured key file not in Pageant");
  4235. } else {
  4236. logevent("Failed to get reply from Pageant");
  4237. }
  4238. if (s->authed)
  4239. break;
  4240. }
  4241. if (s->publickey_blob && s->privatekey_available &&
  4242. !s->tried_publickey) {
  4243. /*
  4244. * Try public key authentication with the specified
  4245. * key file.
  4246. */
  4247. int got_passphrase; /* need not be kept over crReturn */
  4248. if (flags & FLAG_VERBOSE)
  4249. c_write_str(ssh, "Trying public key authentication.\r\n");
  4250. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  4251. logeventf(ssh, MPEXT_BOM "Trying public key \"%s\"",
  4252. filename_to_str(s->keyfile));
  4253. s->tried_publickey = 1;
  4254. got_passphrase = FALSE;
  4255. while (!got_passphrase) {
  4256. /*
  4257. * Get a passphrase, if necessary.
  4258. */
  4259. char *passphrase = NULL; /* only written after crReturn */
  4260. const char *error;
  4261. if (!s->privatekey_encrypted) {
  4262. if (flags & FLAG_VERBOSE)
  4263. c_write_str(ssh, "No passphrase required.\r\n");
  4264. passphrase = NULL;
  4265. } else {
  4266. int ret; /* need not be kept over crReturn */
  4267. s->cur_prompt = new_prompts(ssh->frontend);
  4268. s->cur_prompt->to_server = FALSE;
  4269. s->cur_prompt->name = dupstr("SSH key passphrase");
  4270. add_prompt(s->cur_prompt,
  4271. dupprintf("Passphrase for key \"%.100s\": ",
  4272. s->publickey_comment), FALSE);
  4273. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  4274. while (ret < 0) {
  4275. ssh->send_ok = 1;
  4276. crWaitUntil(!pktin);
  4277. ret = get_userpass_input(s->cur_prompt, in, inlen);
  4278. ssh->send_ok = 0;
  4279. }
  4280. if (!ret) {
  4281. /* Failed to get a passphrase. Terminate. */
  4282. free_prompts(s->cur_prompt);
  4283. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  4284. 0, TRUE);
  4285. crStop(0);
  4286. }
  4287. passphrase = dupstr(s->cur_prompt->prompts[0]->result);
  4288. free_prompts(s->cur_prompt);
  4289. }
  4290. /*
  4291. * Try decrypting key with passphrase.
  4292. */
  4293. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  4294. ret = loadrsakey(s->keyfile, &s->key, passphrase,
  4295. &error);
  4296. if (passphrase) {
  4297. smemclr(passphrase, strlen(passphrase));
  4298. sfree(passphrase);
  4299. }
  4300. if (ret == 1) {
  4301. /* Correct passphrase. */
  4302. got_passphrase = TRUE;
  4303. } else if (ret == 0) {
  4304. c_write_str(ssh, MPEXT_BOM "Couldn't load private key from ");
  4305. c_write_str(ssh, filename_to_str(s->keyfile));
  4306. c_write_str(ssh, " (");
  4307. c_write_str(ssh, error);
  4308. c_write_str(ssh, ").\r\n");
  4309. got_passphrase = FALSE;
  4310. break; /* go and try something else */
  4311. } else if (ret == -1) {
  4312. c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
  4313. got_passphrase = FALSE;
  4314. /* and try again */
  4315. } else {
  4316. assert(0 && "unexpected return from loadrsakey()");
  4317. got_passphrase = FALSE; /* placate optimisers */
  4318. }
  4319. }
  4320. if (got_passphrase) {
  4321. /*
  4322. * Send a public key attempt.
  4323. */
  4324. send_packet(ssh, SSH1_CMSG_AUTH_RSA,
  4325. PKT_BIGNUM, s->key.modulus, PKT_END);
  4326. crWaitUntil(pktin);
  4327. if (pktin->type == SSH1_SMSG_FAILURE) {
  4328. c_write_str(ssh, "Server refused our public key.\r\n");
  4329. continue; /* go and try something else */
  4330. }
  4331. if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
  4332. bombout(("Bizarre response to offer of public key"));
  4333. crStop(0);
  4334. }
  4335. {
  4336. int i;
  4337. unsigned char buffer[32];
  4338. Bignum challenge, response;
  4339. if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
  4340. bombout(("Server's RSA challenge was badly formatted"));
  4341. crStop(0);
  4342. }
  4343. response = rsadecrypt(challenge, &s->key);
  4344. freebn(s->key.private_exponent);/* burn the evidence */
  4345. for (i = 0; i < 32; i++) {
  4346. buffer[i] = bignum_byte(response, 31 - i);
  4347. }
  4348. MD5Init(&md5c);
  4349. MD5Update(&md5c, buffer, 32);
  4350. MD5Update(&md5c, s->session_id, 16);
  4351. MD5Final(buffer, &md5c);
  4352. send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
  4353. PKT_DATA, buffer, 16, PKT_END);
  4354. freebn(challenge);
  4355. freebn(response);
  4356. }
  4357. crWaitUntil(pktin);
  4358. if (pktin->type == SSH1_SMSG_FAILURE) {
  4359. if (flags & FLAG_VERBOSE)
  4360. c_write_str(ssh, "Failed to authenticate with"
  4361. " our public key.\r\n");
  4362. continue; /* go and try something else */
  4363. } else if (pktin->type != SSH1_SMSG_SUCCESS) {
  4364. bombout(("Bizarre response to RSA authentication response"));
  4365. crStop(0);
  4366. }
  4367. break; /* we're through! */
  4368. }
  4369. }
  4370. /*
  4371. * Otherwise, try various forms of password-like authentication.
  4372. */
  4373. s->cur_prompt = new_prompts(ssh->frontend);
  4374. if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
  4375. (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
  4376. !s->tis_auth_refused) {
  4377. s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
  4378. logevent("Requested TIS authentication");
  4379. send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
  4380. crWaitUntil(pktin);
  4381. if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
  4382. logevent("TIS authentication declined");
  4383. if (flags & FLAG_INTERACTIVE)
  4384. c_write_str(ssh, "TIS authentication refused.\r\n");
  4385. s->tis_auth_refused = 1;
  4386. continue;
  4387. } else {
  4388. char *challenge;
  4389. int challengelen;
  4390. char *instr_suf, *prompt;
  4391. ssh_pkt_getstring(pktin, &challenge, &challengelen);
  4392. if (!challenge) {
  4393. bombout(("TIS challenge packet was badly formed"));
  4394. crStop(0);
  4395. }
  4396. logevent("Received TIS challenge");
  4397. s->cur_prompt->to_server = TRUE;
  4398. s->cur_prompt->name = dupstr("SSH TIS authentication");
  4399. /* Prompt heuristic comes from OpenSSH */
  4400. if (memchr(challenge, '\n', challengelen)) {
  4401. instr_suf = dupstr("");
  4402. prompt = dupprintf("%.*s", challengelen, challenge);
  4403. } else {
  4404. instr_suf = dupprintf("%.*s", challengelen, challenge);
  4405. prompt = dupstr("Response: ");
  4406. }
  4407. s->cur_prompt->instruction =
  4408. dupprintf("Using TIS authentication.%s%s",
  4409. (*instr_suf) ? "\n" : "",
  4410. instr_suf);
  4411. s->cur_prompt->instr_reqd = TRUE;
  4412. add_prompt(s->cur_prompt, prompt, FALSE);
  4413. sfree(instr_suf);
  4414. }
  4415. }
  4416. if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
  4417. (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
  4418. !s->ccard_auth_refused) {
  4419. s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
  4420. logevent("Requested CryptoCard authentication");
  4421. send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
  4422. crWaitUntil(pktin);
  4423. if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
  4424. logevent("CryptoCard authentication declined");
  4425. c_write_str(ssh, "CryptoCard authentication refused.\r\n");
  4426. s->ccard_auth_refused = 1;
  4427. continue;
  4428. } else {
  4429. char *challenge;
  4430. int challengelen;
  4431. char *instr_suf, *prompt;
  4432. ssh_pkt_getstring(pktin, &challenge, &challengelen);
  4433. if (!challenge) {
  4434. bombout(("CryptoCard challenge packet was badly formed"));
  4435. crStop(0);
  4436. }
  4437. logevent("Received CryptoCard challenge");
  4438. s->cur_prompt->to_server = TRUE;
  4439. s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
  4440. s->cur_prompt->name_reqd = FALSE;
  4441. /* Prompt heuristic comes from OpenSSH */
  4442. if (memchr(challenge, '\n', challengelen)) {
  4443. instr_suf = dupstr("");
  4444. prompt = dupprintf("%.*s", challengelen, challenge);
  4445. } else {
  4446. instr_suf = dupprintf("%.*s", challengelen, challenge);
  4447. prompt = dupstr("Response: ");
  4448. }
  4449. s->cur_prompt->instruction =
  4450. dupprintf("Using CryptoCard authentication.%s%s",
  4451. (*instr_suf) ? "\n" : "",
  4452. instr_suf);
  4453. s->cur_prompt->instr_reqd = TRUE;
  4454. add_prompt(s->cur_prompt, prompt, FALSE);
  4455. sfree(instr_suf);
  4456. }
  4457. }
  4458. if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
  4459. if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
  4460. bombout(("No supported authentication methods available"));
  4461. crStop(0);
  4462. }
  4463. s->cur_prompt->to_server = TRUE;
  4464. s->cur_prompt->name = dupstr("SSH password");
  4465. add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
  4466. ssh->username, ssh->savedhost),
  4467. FALSE);
  4468. }
  4469. /*
  4470. * Show password prompt, having first obtained it via a TIS
  4471. * or CryptoCard exchange if we're doing TIS or CryptoCard
  4472. * authentication.
  4473. */
  4474. {
  4475. int ret; /* need not be kept over crReturn */
  4476. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  4477. while (ret < 0) {
  4478. ssh->send_ok = 1;
  4479. crWaitUntil(!pktin);
  4480. ret = get_userpass_input(s->cur_prompt, in, inlen);
  4481. ssh->send_ok = 0;
  4482. }
  4483. if (!ret) {
  4484. /*
  4485. * Failed to get a password (for example
  4486. * because one was supplied on the command line
  4487. * which has already failed to work). Terminate.
  4488. */
  4489. free_prompts(s->cur_prompt);
  4490. ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
  4491. crStop(0);
  4492. }
  4493. }
  4494. if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
  4495. /*
  4496. * Defence against traffic analysis: we send a
  4497. * whole bunch of packets containing strings of
  4498. * different lengths. One of these strings is the
  4499. * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
  4500. * The others are all random data in
  4501. * SSH1_MSG_IGNORE packets. This way a passive
  4502. * listener can't tell which is the password, and
  4503. * hence can't deduce the password length.
  4504. *
  4505. * Anybody with a password length greater than 16
  4506. * bytes is going to have enough entropy in their
  4507. * password that a listener won't find it _that_
  4508. * much help to know how long it is. So what we'll
  4509. * do is:
  4510. *
  4511. * - if password length < 16, we send 15 packets
  4512. * containing string lengths 1 through 15
  4513. *
  4514. * - otherwise, we let N be the nearest multiple
  4515. * of 8 below the password length, and send 8
  4516. * packets containing string lengths N through
  4517. * N+7. This won't obscure the order of
  4518. * magnitude of the password length, but it will
  4519. * introduce a bit of extra uncertainty.
  4520. *
  4521. * A few servers can't deal with SSH1_MSG_IGNORE, at
  4522. * least in this context. For these servers, we need
  4523. * an alternative defence. We make use of the fact
  4524. * that the password is interpreted as a C string:
  4525. * so we can append a NUL, then some random data.
  4526. *
  4527. * A few servers can deal with neither SSH1_MSG_IGNORE
  4528. * here _nor_ a padded password string.
  4529. * For these servers we are left with no defences
  4530. * against password length sniffing.
  4531. */
  4532. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
  4533. !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
  4534. /*
  4535. * The server can deal with SSH1_MSG_IGNORE, so
  4536. * we can use the primary defence.
  4537. */
  4538. int bottom, top, pwlen, i;
  4539. char *randomstr;
  4540. pwlen = strlen(s->cur_prompt->prompts[0]->result);
  4541. if (pwlen < 16) {
  4542. bottom = 0; /* zero length passwords are OK! :-) */
  4543. top = 15;
  4544. } else {
  4545. bottom = pwlen & ~7;
  4546. top = bottom + 7;
  4547. }
  4548. assert(pwlen >= bottom && pwlen <= top);
  4549. randomstr = snewn(top + 1, char);
  4550. for (i = bottom; i <= top; i++) {
  4551. if (i == pwlen) {
  4552. defer_packet(ssh, s->pwpkt_type,
  4553. PKT_STR,s->cur_prompt->prompts[0]->result,
  4554. PKT_END);
  4555. } else {
  4556. for (j = 0; j < i; j++) {
  4557. do {
  4558. randomstr[j] = random_byte();
  4559. } while (randomstr[j] == '\0');
  4560. }
  4561. randomstr[i] = '\0';
  4562. defer_packet(ssh, SSH1_MSG_IGNORE,
  4563. PKT_STR, randomstr, PKT_END);
  4564. }
  4565. }
  4566. logevent("Sending password with camouflage packets");
  4567. ssh_pkt_defersend(ssh);
  4568. sfree(randomstr);
  4569. }
  4570. else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
  4571. /*
  4572. * The server can't deal with SSH1_MSG_IGNORE
  4573. * but can deal with padded passwords, so we
  4574. * can use the secondary defence.
  4575. */
  4576. char string[64];
  4577. char *ss;
  4578. int len;
  4579. len = strlen(s->cur_prompt->prompts[0]->result);
  4580. if (len < sizeof(string)) {
  4581. ss = string;
  4582. strcpy(string, s->cur_prompt->prompts[0]->result);
  4583. len++; /* cover the zero byte */
  4584. while (len < sizeof(string)) {
  4585. string[len++] = (char) random_byte();
  4586. }
  4587. } else {
  4588. ss = s->cur_prompt->prompts[0]->result;
  4589. }
  4590. logevent("Sending length-padded password");
  4591. send_packet(ssh, s->pwpkt_type,
  4592. PKT_INT, len, PKT_DATA, ss, len,
  4593. PKT_END);
  4594. } else {
  4595. /*
  4596. * The server is believed unable to cope with
  4597. * any of our password camouflage methods.
  4598. */
  4599. int len;
  4600. len = strlen(s->cur_prompt->prompts[0]->result);
  4601. logevent("Sending unpadded password");
  4602. send_packet(ssh, s->pwpkt_type,
  4603. PKT_INT, len,
  4604. PKT_DATA, s->cur_prompt->prompts[0]->result, len,
  4605. PKT_END);
  4606. }
  4607. } else {
  4608. send_packet(ssh, s->pwpkt_type,
  4609. PKT_STR, s->cur_prompt->prompts[0]->result,
  4610. PKT_END);
  4611. }
  4612. logevent("Sent password");
  4613. free_prompts(s->cur_prompt);
  4614. crWaitUntil(pktin);
  4615. if (pktin->type == SSH1_SMSG_FAILURE) {
  4616. if (flags & FLAG_VERBOSE)
  4617. c_write_str(ssh, "Access denied\r\n");
  4618. logevent("Authentication refused");
  4619. } else if (pktin->type != SSH1_SMSG_SUCCESS) {
  4620. bombout(("Strange packet received, type %d", pktin->type));
  4621. crStop(0);
  4622. }
  4623. }
  4624. /* Clear up */
  4625. if (s->publickey_blob) {
  4626. sfree(s->publickey_blob);
  4627. sfree(s->publickey_comment);
  4628. }
  4629. logevent("Authentication successful");
  4630. crFinish(1);
  4631. }
  4632. static void ssh_channel_try_eof(struct ssh_channel *c)
  4633. {
  4634. Ssh ssh = c->ssh;
  4635. assert(c->pending_eof); /* precondition for calling us */
  4636. if (c->halfopen)
  4637. return; /* can't close: not even opened yet */
  4638. if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
  4639. return; /* can't send EOF: pending outgoing data */
  4640. c->pending_eof = FALSE; /* we're about to send it */
  4641. if (ssh->version == 1) {
  4642. send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
  4643. PKT_END);
  4644. c->closes |= CLOSES_SENT_EOF;
  4645. } else {
  4646. struct Packet *pktout;
  4647. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
  4648. ssh2_pkt_adduint32(pktout, c->remoteid);
  4649. ssh2_pkt_send(ssh, pktout);
  4650. c->closes |= CLOSES_SENT_EOF;
  4651. ssh2_channel_check_close(c);
  4652. }
  4653. }
  4654. Conf *sshfwd_get_conf(struct ssh_channel *c)
  4655. {
  4656. Ssh ssh = c->ssh;
  4657. return ssh->conf;
  4658. }
  4659. void sshfwd_write_eof(struct ssh_channel *c)
  4660. {
  4661. Ssh ssh = c->ssh;
  4662. if (ssh->state == SSH_STATE_CLOSED)
  4663. return;
  4664. if (c->closes & CLOSES_SENT_EOF)
  4665. return;
  4666. c->pending_eof = TRUE;
  4667. ssh_channel_try_eof(c);
  4668. }
  4669. void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
  4670. {
  4671. Ssh ssh = c->ssh;
  4672. char *reason;
  4673. if (ssh->state == SSH_STATE_CLOSED)
  4674. return;
  4675. reason = dupprintf("due to local error: %s", err);
  4676. ssh_channel_close_local(c, reason);
  4677. sfree(reason);
  4678. c->pending_eof = FALSE; /* this will confuse a zombie channel */
  4679. ssh2_channel_check_close(c);
  4680. }
  4681. int sshfwd_write(struct ssh_channel *c, char *buf, int len)
  4682. {
  4683. Ssh ssh = c->ssh;
  4684. if (ssh->state == SSH_STATE_CLOSED)
  4685. return 0;
  4686. return ssh_send_channel_data(c, buf, len);
  4687. }
  4688. void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
  4689. {
  4690. Ssh ssh = c->ssh;
  4691. if (ssh->state == SSH_STATE_CLOSED)
  4692. return;
  4693. ssh_channel_unthrottle(c, bufsize);
  4694. }
  4695. static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
  4696. {
  4697. struct queued_handler *qh = ssh->qhead;
  4698. assert(qh != NULL);
  4699. assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
  4700. if (qh->msg1 > 0) {
  4701. assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
  4702. ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
  4703. }
  4704. if (qh->msg2 > 0) {
  4705. assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
  4706. ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
  4707. }
  4708. if (qh->next) {
  4709. ssh->qhead = qh->next;
  4710. if (ssh->qhead->msg1 > 0) {
  4711. ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
  4712. ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
  4713. }
  4714. if (ssh->qhead->msg2 > 0) {
  4715. ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
  4716. ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
  4717. }
  4718. } else {
  4719. ssh->qhead = ssh->qtail = NULL;
  4720. }
  4721. qh->handler(ssh, pktin, qh->ctx);
  4722. sfree(qh);
  4723. }
  4724. static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
  4725. chandler_fn_t handler, void *ctx)
  4726. {
  4727. struct queued_handler *qh;
  4728. qh = snew(struct queued_handler);
  4729. qh->msg1 = msg1;
  4730. qh->msg2 = msg2;
  4731. qh->handler = handler;
  4732. qh->ctx = ctx;
  4733. qh->next = NULL;
  4734. if (ssh->qtail == NULL) {
  4735. ssh->qhead = qh;
  4736. if (qh->msg1 > 0) {
  4737. ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
  4738. ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
  4739. }
  4740. if (qh->msg2 > 0) {
  4741. ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
  4742. ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
  4743. }
  4744. } else {
  4745. ssh->qtail->next = qh;
  4746. }
  4747. ssh->qtail = qh;
  4748. }
  4749. static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
  4750. {
  4751. struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
  4752. if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
  4753. SSH2_MSG_REQUEST_SUCCESS)) {
  4754. logeventf(ssh, "Remote port forwarding from %s enabled",
  4755. pf->sportdesc);
  4756. } else {
  4757. logeventf(ssh, "Remote port forwarding from %s refused",
  4758. pf->sportdesc);
  4759. rpf = del234(ssh->rportfwds, pf);
  4760. assert(rpf == pf);
  4761. pf->pfrec->remote = NULL;
  4762. free_rportfwd(pf);
  4763. }
  4764. }
  4765. int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
  4766. void *share_ctx)
  4767. {
  4768. struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
  4769. pf->dhost = NULL;
  4770. pf->dport = 0;
  4771. pf->share_ctx = share_ctx;
  4772. pf->shost = dupstr(shost);
  4773. pf->sport = sport;
  4774. pf->sportdesc = NULL;
  4775. if (!ssh->rportfwds) {
  4776. assert(ssh->version == 2);
  4777. ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
  4778. }
  4779. if (add234(ssh->rportfwds, pf) != pf) {
  4780. sfree(pf->shost);
  4781. sfree(pf);
  4782. return FALSE;
  4783. }
  4784. return TRUE;
  4785. }
  4786. static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
  4787. void *ctx)
  4788. {
  4789. share_got_pkt_from_server(ctx, pktin->type,
  4790. pktin->body, pktin->length);
  4791. }
  4792. void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
  4793. {
  4794. ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
  4795. ssh_sharing_global_request_response, share_ctx);
  4796. }
  4797. static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
  4798. {
  4799. struct ssh_portfwd *epf;
  4800. int i;
  4801. char *key, *val;
  4802. if (!ssh->portfwds) {
  4803. ssh->portfwds = newtree234(ssh_portcmp);
  4804. } else {
  4805. /*
  4806. * Go through the existing port forwardings and tag them
  4807. * with status==DESTROY. Any that we want to keep will be
  4808. * re-enabled (status==KEEP) as we go through the
  4809. * configuration and find out which bits are the same as
  4810. * they were before.
  4811. */
  4812. struct ssh_portfwd *epf;
  4813. int i;
  4814. for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
  4815. epf->status = DESTROY;
  4816. }
  4817. for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
  4818. val != NULL;
  4819. val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
  4820. char *kp, *kp2, *vp, *vp2;
  4821. char address_family, type;
  4822. int sport,dport,sserv,dserv;
  4823. char *sports, *dports, *saddr, *host;
  4824. kp = key;
  4825. address_family = 'A';
  4826. type = 'L';
  4827. if (*kp == 'A' || *kp == '4' || *kp == '6')
  4828. address_family = *kp++;
  4829. if (*kp == 'L' || *kp == 'R')
  4830. type = *kp++;
  4831. if ((kp2 = host_strchr(kp, ':')) != NULL) {
  4832. /*
  4833. * There's a colon in the middle of the source port
  4834. * string, which means that the part before it is
  4835. * actually a source address.
  4836. */
  4837. char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
  4838. saddr = host_strduptrim(saddr_tmp);
  4839. sfree(saddr_tmp);
  4840. sports = kp2+1;
  4841. } else {
  4842. saddr = NULL;
  4843. sports = kp;
  4844. }
  4845. sport = atoi(sports);
  4846. sserv = 0;
  4847. if (sport == 0) {
  4848. sserv = 1;
  4849. sport = net_service_lookup(sports);
  4850. if (!sport) {
  4851. logeventf(ssh, "Service lookup failed for source"
  4852. " port \"%s\"", sports);
  4853. }
  4854. }
  4855. if (type == 'L' && !strcmp(val, "D")) {
  4856. /* dynamic forwarding */
  4857. host = NULL;
  4858. dports = NULL;
  4859. dport = -1;
  4860. dserv = 0;
  4861. type = 'D';
  4862. } else {
  4863. /* ordinary forwarding */
  4864. vp = val;
  4865. vp2 = vp + host_strcspn(vp, ":");
  4866. host = dupprintf("%.*s", (int)(vp2 - vp), vp);
  4867. if (*vp2)
  4868. vp2++;
  4869. dports = vp2;
  4870. dport = atoi(dports);
  4871. dserv = 0;
  4872. if (dport == 0) {
  4873. dserv = 1;
  4874. dport = net_service_lookup(dports);
  4875. if (!dport) {
  4876. logeventf(ssh, "Service lookup failed for destination"
  4877. " port \"%s\"", dports);
  4878. }
  4879. }
  4880. }
  4881. if (sport && dport) {
  4882. /* Set up a description of the source port. */
  4883. struct ssh_portfwd *pfrec, *epfrec;
  4884. pfrec = snew(struct ssh_portfwd);
  4885. pfrec->type = type;
  4886. pfrec->saddr = saddr;
  4887. pfrec->sserv = sserv ? dupstr(sports) : NULL;
  4888. pfrec->sport = sport;
  4889. pfrec->daddr = host;
  4890. pfrec->dserv = dserv ? dupstr(dports) : NULL;
  4891. pfrec->dport = dport;
  4892. pfrec->local = NULL;
  4893. pfrec->remote = NULL;
  4894. pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
  4895. address_family == '6' ? ADDRTYPE_IPV6 :
  4896. ADDRTYPE_UNSPEC);
  4897. epfrec = add234(ssh->portfwds, pfrec);
  4898. if (epfrec != pfrec) {
  4899. if (epfrec->status == DESTROY) {
  4900. /*
  4901. * We already have a port forwarding up and running
  4902. * with precisely these parameters. Hence, no need
  4903. * to do anything; simply re-tag the existing one
  4904. * as KEEP.
  4905. */
  4906. epfrec->status = KEEP;
  4907. }
  4908. /*
  4909. * Anything else indicates that there was a duplicate
  4910. * in our input, which we'll silently ignore.
  4911. */
  4912. free_portfwd(pfrec);
  4913. } else {
  4914. pfrec->status = CREATE;
  4915. }
  4916. } else {
  4917. sfree(saddr);
  4918. sfree(host);
  4919. }
  4920. }
  4921. /*
  4922. * Now go through and destroy any port forwardings which were
  4923. * not re-enabled.
  4924. */
  4925. for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
  4926. if (epf->status == DESTROY) {
  4927. char *message;
  4928. message = dupprintf("%s port forwarding from %s%s%d",
  4929. epf->type == 'L' ? "local" :
  4930. epf->type == 'R' ? "remote" : "dynamic",
  4931. epf->saddr ? epf->saddr : "",
  4932. epf->saddr ? ":" : "",
  4933. epf->sport);
  4934. if (epf->type != 'D') {
  4935. char *msg2 = dupprintf("%s to %s:%d", message,
  4936. epf->daddr, epf->dport);
  4937. sfree(message);
  4938. message = msg2;
  4939. }
  4940. logeventf(ssh, "Cancelling %s", message);
  4941. sfree(message);
  4942. /* epf->remote or epf->local may be NULL if setting up a
  4943. * forwarding failed. */
  4944. if (epf->remote) {
  4945. struct ssh_rportfwd *rpf = epf->remote;
  4946. struct Packet *pktout;
  4947. /*
  4948. * Cancel the port forwarding at the server
  4949. * end.
  4950. */
  4951. if (ssh->version == 1) {
  4952. /*
  4953. * We cannot cancel listening ports on the
  4954. * server side in SSH-1! There's no message
  4955. * to support it. Instead, we simply remove
  4956. * the rportfwd record from the local end
  4957. * so that any connections the server tries
  4958. * to make on it are rejected.
  4959. */
  4960. } else {
  4961. pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
  4962. ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
  4963. ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
  4964. if (epf->saddr) {
  4965. ssh2_pkt_addstring(pktout, epf->saddr);
  4966. } else if (conf_get_int(conf, CONF_rport_acceptall)) {
  4967. /* XXX: rport_acceptall may not represent
  4968. * what was used to open the original connection,
  4969. * since it's reconfigurable. */
  4970. ssh2_pkt_addstring(pktout, "");
  4971. } else {
  4972. ssh2_pkt_addstring(pktout, "localhost");
  4973. }
  4974. ssh2_pkt_adduint32(pktout, epf->sport);
  4975. ssh2_pkt_send(ssh, pktout);
  4976. }
  4977. del234(ssh->rportfwds, rpf);
  4978. free_rportfwd(rpf);
  4979. } else if (epf->local) {
  4980. pfl_terminate(epf->local);
  4981. }
  4982. delpos234(ssh->portfwds, i);
  4983. free_portfwd(epf);
  4984. i--; /* so we don't skip one in the list */
  4985. }
  4986. /*
  4987. * And finally, set up any new port forwardings (status==CREATE).
  4988. */
  4989. for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
  4990. if (epf->status == CREATE) {
  4991. char *sportdesc, *dportdesc;
  4992. sportdesc = dupprintf("%s%s%s%s%d%s",
  4993. epf->saddr ? epf->saddr : "",
  4994. epf->saddr ? ":" : "",
  4995. epf->sserv ? epf->sserv : "",
  4996. epf->sserv ? "(" : "",
  4997. epf->sport,
  4998. epf->sserv ? ")" : "");
  4999. if (epf->type == 'D') {
  5000. dportdesc = NULL;
  5001. } else {
  5002. dportdesc = dupprintf("%s:%s%s%d%s",
  5003. epf->daddr,
  5004. epf->dserv ? epf->dserv : "",
  5005. epf->dserv ? "(" : "",
  5006. epf->dport,
  5007. epf->dserv ? ")" : "");
  5008. }
  5009. if (epf->type == 'L') {
  5010. char *err = pfl_listen(epf->daddr, epf->dport,
  5011. epf->saddr, epf->sport,
  5012. ssh, conf, &epf->local,
  5013. epf->addressfamily);
  5014. logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
  5015. epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
  5016. epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
  5017. sportdesc, dportdesc,
  5018. err ? " failed: " : "", err ? err : "");
  5019. if (err)
  5020. sfree(err);
  5021. } else if (epf->type == 'D') {
  5022. char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
  5023. ssh, conf, &epf->local,
  5024. epf->addressfamily);
  5025. logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
  5026. epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
  5027. epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
  5028. sportdesc,
  5029. err ? " failed: " : "", err ? err : "");
  5030. if (err)
  5031. sfree(err);
  5032. } else {
  5033. struct ssh_rportfwd *pf;
  5034. /*
  5035. * Ensure the remote port forwardings tree exists.
  5036. */
  5037. if (!ssh->rportfwds) {
  5038. if (ssh->version == 1)
  5039. ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
  5040. else
  5041. ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
  5042. }
  5043. pf = snew(struct ssh_rportfwd);
  5044. pf->share_ctx = NULL;
  5045. pf->dhost = dupstr(epf->daddr);
  5046. pf->dport = epf->dport;
  5047. if (epf->saddr) {
  5048. pf->shost = dupstr(epf->saddr);
  5049. } else if (conf_get_int(conf, CONF_rport_acceptall)) {
  5050. pf->shost = dupstr("");
  5051. } else {
  5052. pf->shost = dupstr("localhost");
  5053. }
  5054. pf->sport = epf->sport;
  5055. if (add234(ssh->rportfwds, pf) != pf) {
  5056. logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
  5057. epf->daddr, epf->dport);
  5058. sfree(pf);
  5059. } else {
  5060. logeventf(ssh, "Requesting remote port %s"
  5061. " forward to %s", sportdesc, dportdesc);
  5062. pf->sportdesc = sportdesc;
  5063. sportdesc = NULL;
  5064. epf->remote = pf;
  5065. pf->pfrec = epf;
  5066. if (ssh->version == 1) {
  5067. send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
  5068. PKT_INT, epf->sport,
  5069. PKT_STR, epf->daddr,
  5070. PKT_INT, epf->dport,
  5071. PKT_END);
  5072. ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
  5073. SSH1_SMSG_FAILURE,
  5074. ssh_rportfwd_succfail, pf);
  5075. } else {
  5076. struct Packet *pktout;
  5077. pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
  5078. ssh2_pkt_addstring(pktout, "tcpip-forward");
  5079. ssh2_pkt_addbool(pktout, 1);/* want reply */
  5080. ssh2_pkt_addstring(pktout, pf->shost);
  5081. ssh2_pkt_adduint32(pktout, pf->sport);
  5082. ssh2_pkt_send(ssh, pktout);
  5083. ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
  5084. SSH2_MSG_REQUEST_FAILURE,
  5085. ssh_rportfwd_succfail, pf);
  5086. }
  5087. }
  5088. }
  5089. sfree(sportdesc);
  5090. sfree(dportdesc);
  5091. }
  5092. }
  5093. static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
  5094. {
  5095. char *string;
  5096. int stringlen, bufsize;
  5097. ssh_pkt_getstring(pktin, &string, &stringlen);
  5098. if (string == NULL) {
  5099. bombout(("Incoming terminal data packet was badly formed"));
  5100. return;
  5101. }
  5102. bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
  5103. string, stringlen);
  5104. if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
  5105. ssh->v1_stdout_throttling = 1;
  5106. ssh_throttle_conn(ssh, +1);
  5107. }
  5108. }
  5109. static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
  5110. {
  5111. /* Remote side is trying to open a channel to talk to our
  5112. * X-Server. Give them back a local channel number. */
  5113. struct ssh_channel *c;
  5114. int remoteid = ssh_pkt_getuint32(pktin);
  5115. logevent("Received X11 connect request");
  5116. /* Refuse if X11 forwarding is disabled. */
  5117. if (!ssh->X11_fwd_enabled) {
  5118. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  5119. PKT_INT, remoteid, PKT_END);
  5120. logevent("Rejected X11 connect request");
  5121. } else {
  5122. c = snew(struct ssh_channel);
  5123. c->ssh = ssh;
  5124. ssh_channel_init(c);
  5125. c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
  5126. c->remoteid = remoteid;
  5127. c->halfopen = FALSE;
  5128. c->type = CHAN_X11; /* identify channel type */
  5129. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
  5130. PKT_INT, c->remoteid, PKT_INT,
  5131. c->localid, PKT_END);
  5132. logevent("Opened X11 forward channel");
  5133. }
  5134. }
  5135. static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
  5136. {
  5137. /* Remote side is trying to open a channel to talk to our
  5138. * agent. Give them back a local channel number. */
  5139. struct ssh_channel *c;
  5140. int remoteid = ssh_pkt_getuint32(pktin);
  5141. /* Refuse if agent forwarding is disabled. */
  5142. if (!ssh->agentfwd_enabled) {
  5143. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  5144. PKT_INT, remoteid, PKT_END);
  5145. } else {
  5146. c = snew(struct ssh_channel);
  5147. c->ssh = ssh;
  5148. ssh_channel_init(c);
  5149. c->remoteid = remoteid;
  5150. c->halfopen = FALSE;
  5151. c->type = CHAN_AGENT; /* identify channel type */
  5152. c->u.a.pending = NULL;
  5153. bufchain_init(&c->u.a.inbuffer);
  5154. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
  5155. PKT_INT, c->remoteid, PKT_INT, c->localid,
  5156. PKT_END);
  5157. }
  5158. }
  5159. static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
  5160. {
  5161. /* Remote side is trying to open a channel to talk to a
  5162. * forwarded port. Give them back a local channel number. */
  5163. struct ssh_rportfwd pf, *pfp;
  5164. int remoteid;
  5165. int hostsize, port;
  5166. char *host;
  5167. char *err;
  5168. remoteid = ssh_pkt_getuint32(pktin);
  5169. ssh_pkt_getstring(pktin, &host, &hostsize);
  5170. port = ssh_pkt_getuint32(pktin);
  5171. pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
  5172. pf.dport = port;
  5173. pfp = find234(ssh->rportfwds, &pf, NULL);
  5174. if (pfp == NULL) {
  5175. logeventf(ssh, "Rejected remote port open request for %s:%d",
  5176. pf.dhost, port);
  5177. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  5178. PKT_INT, remoteid, PKT_END);
  5179. } else {
  5180. struct ssh_channel *c = snew(struct ssh_channel);
  5181. c->ssh = ssh;
  5182. logeventf(ssh, "Received remote port open request for %s:%d",
  5183. pf.dhost, port);
  5184. err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
  5185. c, ssh->conf, pfp->pfrec->addressfamily);
  5186. if (err != NULL) {
  5187. logeventf(ssh, "Port open failed: %s", err);
  5188. sfree(err);
  5189. sfree(c);
  5190. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  5191. PKT_INT, remoteid, PKT_END);
  5192. } else {
  5193. ssh_channel_init(c);
  5194. c->remoteid = remoteid;
  5195. c->halfopen = FALSE;
  5196. c->type = CHAN_SOCKDATA; /* identify channel type */
  5197. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
  5198. PKT_INT, c->remoteid, PKT_INT,
  5199. c->localid, PKT_END);
  5200. logevent("Forwarded port opened successfully");
  5201. }
  5202. }
  5203. sfree(pf.dhost);
  5204. }
  5205. static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
  5206. {
  5207. struct ssh_channel *c;
  5208. c = ssh_channel_msg(ssh, pktin);
  5209. if (c && c->type == CHAN_SOCKDATA) {
  5210. c->remoteid = ssh_pkt_getuint32(pktin);
  5211. c->halfopen = FALSE;
  5212. c->throttling_conn = 0;
  5213. pfd_confirm(c->u.pfd.pf);
  5214. }
  5215. if (c && c->pending_eof) {
  5216. /*
  5217. * We have a pending close on this channel,
  5218. * which we decided on before the server acked
  5219. * the channel open. So now we know the
  5220. * remoteid, we can close it again.
  5221. */
  5222. ssh_channel_try_eof(c);
  5223. }
  5224. }
  5225. static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
  5226. {
  5227. struct ssh_channel *c;
  5228. c = ssh_channel_msg(ssh, pktin);
  5229. if (c && c->type == CHAN_SOCKDATA) {
  5230. logevent("Forwarded connection refused by server");
  5231. pfd_close(c->u.pfd.pf);
  5232. del234(ssh->channels, c);
  5233. sfree(c);
  5234. }
  5235. }
  5236. static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
  5237. {
  5238. /* Remote side closes a channel. */
  5239. struct ssh_channel *c;
  5240. c = ssh_channel_msg(ssh, pktin);
  5241. if (c) {
  5242. if (pktin->type == SSH1_MSG_CHANNEL_CLOSE) {
  5243. /*
  5244. * Received CHANNEL_CLOSE, which we translate into
  5245. * outgoing EOF.
  5246. */
  5247. ssh_channel_got_eof(c);
  5248. }
  5249. if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
  5250. !(c->closes & CLOSES_RCVD_CLOSE)) {
  5251. if (!(c->closes & CLOSES_SENT_EOF)) {
  5252. bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %u"
  5253. " for which we never sent CHANNEL_CLOSE\n",
  5254. c->localid));
  5255. }
  5256. c->closes |= CLOSES_RCVD_CLOSE;
  5257. }
  5258. if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
  5259. !(c->closes & CLOSES_SENT_CLOSE)) {
  5260. send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
  5261. PKT_INT, c->remoteid, PKT_END);
  5262. c->closes |= CLOSES_SENT_CLOSE;
  5263. }
  5264. if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
  5265. ssh_channel_destroy(c);
  5266. }
  5267. }
  5268. /*
  5269. * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
  5270. */
  5271. static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
  5272. int length)
  5273. {
  5274. bufchain_add(&c->u.a.inbuffer, data, length);
  5275. ssh_agentf_try_forward(c);
  5276. /*
  5277. * We exert back-pressure on an agent forwarding client if and
  5278. * only if we're waiting for the response to an asynchronous agent
  5279. * request. This prevents the client running out of window while
  5280. * receiving the _first_ message, but means that if any message
  5281. * takes time to process, the client will be discouraged from
  5282. * sending an endless stream of further ones after it.
  5283. */
  5284. return (c->u.a.pending ? bufchain_size(&c->u.a.inbuffer) : 0);
  5285. }
  5286. static int ssh_channel_data(struct ssh_channel *c, int is_stderr,
  5287. char *data, int length)
  5288. {
  5289. switch (c->type) {
  5290. case CHAN_MAINSESSION:
  5291. return from_backend(c->ssh->frontend, is_stderr, data, length);
  5292. case CHAN_X11:
  5293. return x11_send(c->u.x11.xconn, data, length);
  5294. case CHAN_SOCKDATA:
  5295. return pfd_send(c->u.pfd.pf, data, length);
  5296. case CHAN_AGENT:
  5297. return ssh_agent_channel_data(c, data, length);
  5298. }
  5299. return 0;
  5300. }
  5301. static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
  5302. {
  5303. /* Data sent down one of our channels. */
  5304. char *p;
  5305. int len;
  5306. struct ssh_channel *c;
  5307. c = ssh_channel_msg(ssh, pktin);
  5308. ssh_pkt_getstring(pktin, &p, &len);
  5309. if (c) {
  5310. int bufsize = ssh_channel_data(c, FALSE, p, len);
  5311. if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
  5312. c->throttling_conn = 1;
  5313. ssh_throttle_conn(ssh, +1);
  5314. }
  5315. }
  5316. }
  5317. static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
  5318. {
  5319. ssh->exitcode = ssh_pkt_getuint32(pktin);
  5320. logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
  5321. send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
  5322. /*
  5323. * In case `helpful' firewalls or proxies tack
  5324. * extra human-readable text on the end of the
  5325. * session which we might mistake for another
  5326. * encrypted packet, we close the session once
  5327. * we've sent EXIT_CONFIRMATION.
  5328. */
  5329. ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
  5330. }
  5331. /* Helper function to deal with sending tty modes for REQUEST_PTY */
  5332. static void ssh1_send_ttymode(void *data,
  5333. const struct ssh_ttymode *mode, char *val)
  5334. {
  5335. struct Packet *pktout = (struct Packet *)data;
  5336. unsigned int arg = 0;
  5337. switch (mode->type) {
  5338. case TTY_OP_CHAR:
  5339. arg = ssh_tty_parse_specchar(val);
  5340. break;
  5341. case TTY_OP_BOOL:
  5342. arg = ssh_tty_parse_boolean(val);
  5343. break;
  5344. }
  5345. ssh2_pkt_addbyte(pktout, mode->opcode);
  5346. ssh2_pkt_addbyte(pktout, arg);
  5347. }
  5348. int ssh_agent_forwarding_permitted(Ssh ssh)
  5349. {
  5350. return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
  5351. }
  5352. static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
  5353. struct Packet *pktin)
  5354. {
  5355. crBegin(ssh->do_ssh1_connection_crstate);
  5356. ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
  5357. ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
  5358. ssh1_smsg_stdout_stderr_data;
  5359. ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
  5360. ssh1_msg_channel_open_confirmation;
  5361. ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
  5362. ssh1_msg_channel_open_failure;
  5363. ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
  5364. ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
  5365. ssh1_msg_channel_close;
  5366. ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
  5367. ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
  5368. if (ssh_agent_forwarding_permitted(ssh)) {
  5369. logevent("Requesting agent forwarding");
  5370. send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
  5371. do {
  5372. crReturnV;
  5373. } while (!pktin);
  5374. if (pktin->type != SSH1_SMSG_SUCCESS
  5375. && pktin->type != SSH1_SMSG_FAILURE) {
  5376. bombout(("Protocol confusion"));
  5377. crStopV;
  5378. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5379. logevent("Agent forwarding refused");
  5380. } else {
  5381. logevent("Agent forwarding enabled");
  5382. ssh->agentfwd_enabled = TRUE;
  5383. ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
  5384. }
  5385. }
  5386. if (conf_get_int(ssh->conf, CONF_x11_forward)) {
  5387. ssh->x11disp =
  5388. x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
  5389. ssh->conf);
  5390. if (!ssh->x11disp) {
  5391. /* FIXME: return an error message from x11_setup_display */
  5392. logevent("X11 forwarding not enabled: unable to"
  5393. " initialise X display");
  5394. } else {
  5395. ssh->x11auth = x11_invent_fake_auth
  5396. (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
  5397. ssh->x11auth->disp = ssh->x11disp;
  5398. logevent("Requesting X11 forwarding");
  5399. if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
  5400. send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
  5401. PKT_STR, ssh->x11auth->protoname,
  5402. PKT_STR, ssh->x11auth->datastring,
  5403. PKT_INT, ssh->x11disp->screennum,
  5404. PKT_END);
  5405. } else {
  5406. send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
  5407. PKT_STR, ssh->x11auth->protoname,
  5408. PKT_STR, ssh->x11auth->datastring,
  5409. PKT_END);
  5410. }
  5411. do {
  5412. crReturnV;
  5413. } while (!pktin);
  5414. if (pktin->type != SSH1_SMSG_SUCCESS
  5415. && pktin->type != SSH1_SMSG_FAILURE) {
  5416. bombout(("Protocol confusion"));
  5417. crStopV;
  5418. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5419. logevent("X11 forwarding refused");
  5420. } else {
  5421. logevent("X11 forwarding enabled");
  5422. ssh->X11_fwd_enabled = TRUE;
  5423. ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
  5424. }
  5425. }
  5426. }
  5427. ssh_setup_portfwd(ssh, ssh->conf);
  5428. ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
  5429. if (!conf_get_int(ssh->conf, CONF_nopty)) {
  5430. struct Packet *pkt;
  5431. /* Unpick the terminal-speed string. */
  5432. /* XXX perhaps we should allow no speeds to be sent. */
  5433. ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
  5434. sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
  5435. /* Send the pty request. */
  5436. pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
  5437. ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
  5438. ssh_pkt_adduint32(pkt, ssh->term_height);
  5439. ssh_pkt_adduint32(pkt, ssh->term_width);
  5440. ssh_pkt_adduint32(pkt, 0); /* width in pixels */
  5441. ssh_pkt_adduint32(pkt, 0); /* height in pixels */
  5442. parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
  5443. ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
  5444. ssh_pkt_adduint32(pkt, ssh->ispeed);
  5445. ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
  5446. ssh_pkt_adduint32(pkt, ssh->ospeed);
  5447. ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
  5448. s_wrpkt(ssh, pkt);
  5449. ssh->state = SSH_STATE_INTERMED;
  5450. do {
  5451. crReturnV;
  5452. } while (!pktin);
  5453. if (pktin->type != SSH1_SMSG_SUCCESS
  5454. && pktin->type != SSH1_SMSG_FAILURE) {
  5455. bombout(("Protocol confusion"));
  5456. crStopV;
  5457. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5458. c_write_str(ssh, "Server refused to allocate pty\r\n");
  5459. ssh->editing = ssh->echoing = 1;
  5460. } else {
  5461. logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
  5462. ssh->ospeed, ssh->ispeed);
  5463. ssh->got_pty = TRUE;
  5464. }
  5465. } else {
  5466. ssh->editing = ssh->echoing = 1;
  5467. }
  5468. if (conf_get_int(ssh->conf, CONF_compression)) {
  5469. send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
  5470. do {
  5471. crReturnV;
  5472. } while (!pktin);
  5473. if (pktin->type != SSH1_SMSG_SUCCESS
  5474. && pktin->type != SSH1_SMSG_FAILURE) {
  5475. bombout(("Protocol confusion"));
  5476. crStopV;
  5477. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5478. c_write_str(ssh, "Server refused to compress\r\n");
  5479. }
  5480. logevent("Started compression");
  5481. ssh->v1_compressing = TRUE;
  5482. ssh->cs_comp_ctx = zlib_compress_init();
  5483. logevent("Initialised zlib (RFC1950) compression");
  5484. ssh->sc_comp_ctx = zlib_decompress_init();
  5485. logevent("Initialised zlib (RFC1950) decompression");
  5486. }
  5487. /*
  5488. * Start the shell or command.
  5489. *
  5490. * Special case: if the first-choice command is an SSH-2
  5491. * subsystem (hence not usable here) and the second choice
  5492. * exists, we fall straight back to that.
  5493. */
  5494. {
  5495. char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
  5496. if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
  5497. conf_get_str(ssh->conf, CONF_remote_cmd2)) {
  5498. cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
  5499. ssh->fallback_cmd = TRUE;
  5500. }
  5501. if (*cmd)
  5502. send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
  5503. else
  5504. send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
  5505. logevent("Started session");
  5506. }
  5507. ssh->state = SSH_STATE_SESSION;
  5508. if (ssh->size_needed)
  5509. ssh_size(ssh, ssh->term_width, ssh->term_height);
  5510. if (ssh->eof_needed)
  5511. ssh_special(ssh, TS_EOF);
  5512. if (ssh->ldisc)
  5513. ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
  5514. ssh->send_ok = 1;
  5515. ssh->channels = newtree234(ssh_channelcmp);
  5516. while (1) {
  5517. /*
  5518. * By this point, most incoming packets are already being
  5519. * handled by the dispatch table, and we need only pay
  5520. * attention to the unusual ones.
  5521. */
  5522. crReturnV;
  5523. if (pktin) {
  5524. if (pktin->type == SSH1_SMSG_SUCCESS) {
  5525. /* may be from EXEC_SHELL on some servers */
  5526. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5527. /* may be from EXEC_SHELL on some servers
  5528. * if no pty is available or in other odd cases. Ignore */
  5529. } else {
  5530. bombout(("Strange packet received: type %d", pktin->type));
  5531. crStopV;
  5532. }
  5533. } else {
  5534. while (inlen > 0) {
  5535. int len = min(inlen, 512);
  5536. send_packet(ssh, SSH1_CMSG_STDIN_DATA,
  5537. PKT_INT, len, PKT_DATA, in, len,
  5538. PKT_END);
  5539. in += len;
  5540. inlen -= len;
  5541. }
  5542. }
  5543. }
  5544. crFinishV;
  5545. }
  5546. /*
  5547. * Handle the top-level SSH-2 protocol.
  5548. */
  5549. static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
  5550. {
  5551. char *msg;
  5552. int msglen;
  5553. ssh_pkt_getstring(pktin, &msg, &msglen);
  5554. logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
  5555. }
  5556. static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
  5557. {
  5558. /* log reason code in disconnect message */
  5559. char *msg;
  5560. int msglen;
  5561. ssh_pkt_getstring(pktin, &msg, &msglen);
  5562. bombout(("Server sent disconnect message:\n\"%.*s\"",
  5563. msglen, NULLTOEMPTY(msg)));
  5564. }
  5565. static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
  5566. {
  5567. /* Do nothing, because we're ignoring it! Duhh. */
  5568. }
  5569. static void ssh1_protocol_setup(Ssh ssh)
  5570. {
  5571. int i;
  5572. /*
  5573. * Most messages are handled by the coroutines.
  5574. */
  5575. for (i = 0; i < 256; i++)
  5576. ssh->packet_dispatch[i] = NULL;
  5577. /*
  5578. * These special message types we install handlers for.
  5579. */
  5580. ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
  5581. ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
  5582. ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
  5583. }
  5584. static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
  5585. struct Packet *pktin)
  5586. {
  5587. const unsigned char *in = (const unsigned char *)vin;
  5588. if (ssh->state == SSH_STATE_CLOSED)
  5589. return;
  5590. if (pktin && ssh->packet_dispatch[pktin->type]) {
  5591. ssh->packet_dispatch[pktin->type](ssh, pktin);
  5592. return;
  5593. }
  5594. if (!ssh->protocol_initial_phase_done) {
  5595. if (do_ssh1_login(ssh, in, inlen, pktin))
  5596. ssh->protocol_initial_phase_done = TRUE;
  5597. else
  5598. return;
  5599. }
  5600. do_ssh1_connection(ssh, in, inlen, pktin);
  5601. }
  5602. /*
  5603. * Utility routines for decoding comma-separated strings in KEXINIT.
  5604. */
  5605. static int first_in_commasep_string(char const *needle, char const *haystack,
  5606. int haylen)
  5607. {
  5608. int needlen;
  5609. if (!needle || !haystack) /* protect against null pointers */
  5610. return 0;
  5611. needlen = strlen(needle);
  5612. if (haylen >= needlen && /* haystack is long enough */
  5613. !memcmp(needle, haystack, needlen) && /* initial match */
  5614. (haylen == needlen || haystack[needlen] == ',')
  5615. /* either , or EOS follows */
  5616. )
  5617. return 1;
  5618. return 0;
  5619. }
  5620. static int in_commasep_string(char const *needle, char const *haystack,
  5621. int haylen)
  5622. {
  5623. char *p;
  5624. if (!needle || !haystack) /* protect against null pointers */
  5625. return 0;
  5626. /*
  5627. * Is it at the start of the string?
  5628. */
  5629. if (first_in_commasep_string(needle, haystack, haylen))
  5630. return 1;
  5631. /*
  5632. * If not, search for the next comma and resume after that.
  5633. * If no comma found, terminate.
  5634. */
  5635. p = memchr(haystack, ',', haylen);
  5636. if (!p) return 0;
  5637. /* + 1 to skip over comma */
  5638. return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
  5639. }
  5640. /*
  5641. * Add a value to the comma-separated string at the end of the packet.
  5642. */
  5643. static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
  5644. {
  5645. if (pkt->length - pkt->savedpos > 0)
  5646. ssh_pkt_addstring_str(pkt, ",");
  5647. ssh_pkt_addstring_str(pkt, data);
  5648. }
  5649. /*
  5650. * SSH-2 key derivation (RFC 4253 section 7.2).
  5651. */
  5652. static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
  5653. char chr, int keylen)
  5654. {
  5655. const struct ssh_hash *h = ssh->kex->hash;
  5656. int keylen_padded;
  5657. unsigned char *key;
  5658. void *s, *s2;
  5659. if (keylen == 0)
  5660. return NULL;
  5661. /* Round up to the next multiple of hash length. */
  5662. keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
  5663. key = snewn(keylen_padded, unsigned char);
  5664. /* First hlen bytes. */
  5665. s = h->init();
  5666. if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
  5667. hash_mpint(h, s, K);
  5668. h->bytes(s, H, h->hlen);
  5669. h->bytes(s, &chr, 1);
  5670. h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
  5671. h->final(s, key);
  5672. /* Subsequent blocks of hlen bytes. */
  5673. if (keylen_padded > h->hlen) {
  5674. int offset;
  5675. s = h->init();
  5676. if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
  5677. hash_mpint(h, s, K);
  5678. h->bytes(s, H, h->hlen);
  5679. for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
  5680. h->bytes(s, key + offset - h->hlen, h->hlen);
  5681. s2 = h->copy(s);
  5682. h->final(s2, key + offset);
  5683. }
  5684. h->free(s);
  5685. }
  5686. /* Now clear any extra bytes of key material beyond the length
  5687. * we're officially returning, because the caller won't know to
  5688. * smemclr those. */
  5689. if (keylen_padded > keylen)
  5690. smemclr(key + keylen, keylen_padded - keylen);
  5691. return key;
  5692. }
  5693. /*
  5694. * Structure for constructing KEXINIT algorithm lists.
  5695. */
  5696. #define MAXKEXLIST 16
  5697. struct kexinit_algorithm {
  5698. const char *name;
  5699. union {
  5700. struct {
  5701. const struct ssh_kex *kex;
  5702. int warn;
  5703. } kex;
  5704. struct {
  5705. const struct ssh_signkey *hostkey;
  5706. int warn;
  5707. } hk;
  5708. struct {
  5709. const struct ssh2_cipher *cipher;
  5710. int warn;
  5711. } cipher;
  5712. struct {
  5713. const struct ssh_mac *mac;
  5714. int etm;
  5715. } mac;
  5716. const struct ssh_compress *comp;
  5717. } u;
  5718. };
  5719. /*
  5720. * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
  5721. * If the algorithm is already in the list, return a pointer to its
  5722. * entry, otherwise return an entry from the end of the list.
  5723. * This assumes that every time a particular name is passed in, it
  5724. * comes from the same string constant. If this isn't true, this
  5725. * function may need to be rewritten to use strcmp() instead.
  5726. */
  5727. static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
  5728. *list, const char *name)
  5729. {
  5730. int i;
  5731. for (i = 0; i < MAXKEXLIST; i++)
  5732. if (list[i].name == NULL || list[i].name == name) {
  5733. list[i].name = name;
  5734. return &list[i];
  5735. }
  5736. assert(!"No space in KEXINIT list");
  5737. return NULL;
  5738. }
  5739. /*
  5740. * Handle the SSH-2 transport layer.
  5741. */
  5742. static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
  5743. struct Packet *pktin)
  5744. {
  5745. const unsigned char *in = (const unsigned char *)vin;
  5746. enum kexlist {
  5747. KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
  5748. KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
  5749. NKEXLIST
  5750. };
  5751. const char * kexlist_descr[NKEXLIST] = {
  5752. "key exchange algorithm", "host key algorithm",
  5753. "client-to-server cipher", "server-to-client cipher",
  5754. "client-to-server MAC", "server-to-client MAC",
  5755. "client-to-server compression method",
  5756. "server-to-client compression method" };
  5757. struct do_ssh2_transport_state {
  5758. int crLine;
  5759. int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
  5760. Bignum p, g, e, f, K;
  5761. void *our_kexinit;
  5762. int our_kexinitlen;
  5763. int kex_init_value, kex_reply_value;
  5764. const struct ssh_mac *const *maclist;
  5765. int nmacs;
  5766. const struct ssh2_cipher *cscipher_tobe;
  5767. const struct ssh2_cipher *sccipher_tobe;
  5768. const struct ssh_mac *csmac_tobe;
  5769. const struct ssh_mac *scmac_tobe;
  5770. int csmac_etm_tobe, scmac_etm_tobe;
  5771. const struct ssh_compress *cscomp_tobe;
  5772. const struct ssh_compress *sccomp_tobe;
  5773. char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
  5774. int hostkeylen, siglen, rsakeylen;
  5775. void *hkey; /* actual host key */
  5776. void *rsakey; /* for RSA kex */
  5777. void *eckey; /* for ECDH kex */
  5778. unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
  5779. int n_preferred_kex;
  5780. const struct ssh_kexes *preferred_kex[KEX_MAX];
  5781. int n_preferred_hk;
  5782. int preferred_hk[HK_MAX];
  5783. int n_preferred_ciphers;
  5784. const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
  5785. const struct ssh_compress *preferred_comp;
  5786. int userauth_succeeded; /* for delayed compression */
  5787. int pending_compression;
  5788. int got_session_id, activated_authconn;
  5789. struct Packet *pktout;
  5790. int dlgret;
  5791. int guessok;
  5792. int ignorepkt;
  5793. struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
  5794. };
  5795. crState(do_ssh2_transport_state);
  5796. assert(!ssh->bare_connection);
  5797. assert(ssh->version == 2);
  5798. crBeginState;
  5799. s->cscipher_tobe = s->sccipher_tobe = NULL;
  5800. s->csmac_tobe = s->scmac_tobe = NULL;
  5801. s->cscomp_tobe = s->sccomp_tobe = NULL;
  5802. s->got_session_id = s->activated_authconn = FALSE;
  5803. s->userauth_succeeded = FALSE;
  5804. s->pending_compression = FALSE;
  5805. /*
  5806. * Be prepared to work around the buggy MAC problem.
  5807. */
  5808. if (ssh->remote_bugs & BUG_SSH2_HMAC)
  5809. s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
  5810. else
  5811. s->maclist = macs, s->nmacs = lenof(macs);
  5812. begin_key_exchange:
  5813. ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
  5814. {
  5815. int i, j, k, warn;
  5816. struct kexinit_algorithm *alg;
  5817. /*
  5818. * Set up the preferred key exchange. (NULL => warn below here)
  5819. */
  5820. s->n_preferred_kex = 0;
  5821. for (i = 0; i < KEX_MAX; i++) {
  5822. switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
  5823. case KEX_DHGEX:
  5824. s->preferred_kex[s->n_preferred_kex++] =
  5825. &ssh_diffiehellman_gex;
  5826. break;
  5827. case KEX_DHGROUP14:
  5828. s->preferred_kex[s->n_preferred_kex++] =
  5829. &ssh_diffiehellman_group14;
  5830. break;
  5831. case KEX_DHGROUP1:
  5832. s->preferred_kex[s->n_preferred_kex++] =
  5833. &ssh_diffiehellman_group1;
  5834. break;
  5835. case KEX_RSA:
  5836. s->preferred_kex[s->n_preferred_kex++] =
  5837. &ssh_rsa_kex;
  5838. break;
  5839. case KEX_ECDH:
  5840. s->preferred_kex[s->n_preferred_kex++] =
  5841. &ssh_ecdh_kex;
  5842. break;
  5843. case KEX_WARN:
  5844. /* Flag for later. Don't bother if it's the last in
  5845. * the list. */
  5846. if (i < KEX_MAX - 1) {
  5847. s->preferred_kex[s->n_preferred_kex++] = NULL;
  5848. }
  5849. break;
  5850. }
  5851. }
  5852. /*
  5853. * Set up the preferred host key types. These are just the ids
  5854. * in the enum in putty.h, so 'warn below here' is indicated
  5855. * by HK_WARN.
  5856. */
  5857. s->n_preferred_hk = 0;
  5858. for (i = 0; i < HK_MAX; i++) {
  5859. int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
  5860. /* As above, don't bother with HK_WARN if it's last in the
  5861. * list */
  5862. if (id != HK_WARN || i < HK_MAX - 1)
  5863. s->preferred_hk[s->n_preferred_hk++] = id;
  5864. }
  5865. /*
  5866. * Set up the preferred ciphers. (NULL => warn below here)
  5867. */
  5868. s->n_preferred_ciphers = 0;
  5869. for (i = 0; i < CIPHER_MAX; i++) {
  5870. switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
  5871. case CIPHER_BLOWFISH:
  5872. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
  5873. break;
  5874. case CIPHER_DES:
  5875. if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
  5876. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
  5877. }
  5878. break;
  5879. case CIPHER_3DES:
  5880. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
  5881. break;
  5882. case CIPHER_AES:
  5883. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
  5884. break;
  5885. case CIPHER_ARCFOUR:
  5886. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
  5887. break;
  5888. case CIPHER_CHACHA20:
  5889. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
  5890. break;
  5891. case CIPHER_WARN:
  5892. /* Flag for later. Don't bother if it's the last in
  5893. * the list. */
  5894. if (i < CIPHER_MAX - 1) {
  5895. s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
  5896. }
  5897. break;
  5898. }
  5899. }
  5900. /*
  5901. * Set up preferred compression.
  5902. */
  5903. if (conf_get_int(ssh->conf, CONF_compression))
  5904. s->preferred_comp = &ssh_zlib;
  5905. else
  5906. s->preferred_comp = &ssh_comp_none;
  5907. /*
  5908. * Enable queueing of outgoing auth- or connection-layer
  5909. * packets while we are in the middle of a key exchange.
  5910. */
  5911. ssh->queueing = TRUE;
  5912. /*
  5913. * Flag that KEX is in progress.
  5914. */
  5915. ssh->kex_in_progress = TRUE;
  5916. for (i = 0; i < NKEXLIST; i++)
  5917. for (j = 0; j < MAXKEXLIST; j++)
  5918. s->kexlists[i][j].name = NULL;
  5919. /* List key exchange algorithms. */
  5920. warn = FALSE;
  5921. for (i = 0; i < s->n_preferred_kex; i++) {
  5922. const struct ssh_kexes *k = s->preferred_kex[i];
  5923. if (!k) warn = TRUE;
  5924. else for (j = 0; j < k->nkexes; j++) {
  5925. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
  5926. k->list[j]->name);
  5927. alg->u.kex.kex = k->list[j];
  5928. alg->u.kex.warn = warn;
  5929. }
  5930. }
  5931. /* List server host key algorithms. */
  5932. if (!s->got_session_id) {
  5933. /*
  5934. * In the first key exchange, we list all the algorithms
  5935. * we're prepared to cope with, but prefer those algorithms
  5936. * for which we have a host key for this host.
  5937. *
  5938. * If the host key algorithm is below the warning
  5939. * threshold, we warn even if we did already have a key
  5940. * for it, on the basis that if the user has just
  5941. * reconfigured that host key type to be warned about,
  5942. * they surely _do_ want to be alerted that a server
  5943. * they're actually connecting to is using it.
  5944. */
  5945. warn = FALSE;
  5946. for (i = 0; i < s->n_preferred_hk; i++) {
  5947. if (s->preferred_hk[i] == HK_WARN)
  5948. warn = TRUE;
  5949. for (j = 0; j < lenof(hostkey_algs); j++) {
  5950. if (hostkey_algs[j].id != s->preferred_hk[i])
  5951. continue;
  5952. if (have_ssh_host_key(
  5953. #ifdef MPEXT
  5954. ssh->frontend,
  5955. #endif
  5956. ssh->savedhost, ssh->savedport,
  5957. hostkey_algs[j].alg->keytype)) {
  5958. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  5959. hostkey_algs[j].alg->name);
  5960. alg->u.hk.hostkey = hostkey_algs[j].alg;
  5961. alg->u.hk.warn = warn;
  5962. }
  5963. }
  5964. }
  5965. warn = FALSE;
  5966. for (i = 0; i < s->n_preferred_hk; i++) {
  5967. if (s->preferred_hk[i] == HK_WARN)
  5968. warn = TRUE;
  5969. for (j = 0; j < lenof(hostkey_algs); j++) {
  5970. if (hostkey_algs[j].id != s->preferred_hk[i])
  5971. continue;
  5972. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  5973. hostkey_algs[j].alg->name);
  5974. alg->u.hk.hostkey = hostkey_algs[j].alg;
  5975. alg->u.hk.warn = warn;
  5976. }
  5977. }
  5978. } else {
  5979. /*
  5980. * In subsequent key exchanges, we list only the kex
  5981. * algorithm that was selected in the first key exchange,
  5982. * so that we keep getting the same host key and hence
  5983. * don't have to interrupt the user's session to ask for
  5984. * reverification.
  5985. */
  5986. assert(ssh->kex);
  5987. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  5988. ssh->hostkey->name);
  5989. alg->u.hk.hostkey = ssh->hostkey;
  5990. alg->u.hk.warn = FALSE;
  5991. }
  5992. /* List encryption algorithms (client->server then server->client). */
  5993. for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
  5994. warn = FALSE;
  5995. #ifdef FUZZING
  5996. alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
  5997. alg->u.cipher.cipher = NULL;
  5998. alg->u.cipher.warn = warn;
  5999. #endif /* FUZZING */
  6000. for (i = 0; i < s->n_preferred_ciphers; i++) {
  6001. const struct ssh2_ciphers *c = s->preferred_ciphers[i];
  6002. if (!c) warn = TRUE;
  6003. else for (j = 0; j < c->nciphers; j++) {
  6004. alg = ssh2_kexinit_addalg(s->kexlists[k],
  6005. c->list[j]->name);
  6006. alg->u.cipher.cipher = c->list[j];
  6007. alg->u.cipher.warn = warn;
  6008. }
  6009. }
  6010. }
  6011. /* List MAC algorithms (client->server then server->client). */
  6012. for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
  6013. #ifdef FUZZING
  6014. alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
  6015. alg->u.mac.mac = NULL;
  6016. alg->u.mac.etm = FALSE;
  6017. #endif /* FUZZING */
  6018. for (i = 0; i < s->nmacs; i++) {
  6019. alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
  6020. alg->u.mac.mac = s->maclist[i];
  6021. alg->u.mac.etm = FALSE;
  6022. }
  6023. for (i = 0; i < s->nmacs; i++)
  6024. /* For each MAC, there may also be an ETM version,
  6025. * which we list second. */
  6026. if (s->maclist[i]->etm_name) {
  6027. alg = ssh2_kexinit_addalg(s->kexlists[j],
  6028. s->maclist[i]->etm_name);
  6029. alg->u.mac.mac = s->maclist[i];
  6030. alg->u.mac.etm = TRUE;
  6031. }
  6032. }
  6033. /* List client->server compression algorithms,
  6034. * then server->client compression algorithms. (We use the
  6035. * same set twice.) */
  6036. for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
  6037. assert(lenof(compressions) > 1);
  6038. /* Prefer non-delayed versions */
  6039. alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
  6040. alg->u.comp = s->preferred_comp;
  6041. /* We don't even list delayed versions of algorithms until
  6042. * they're allowed to be used, to avoid a race. See the end of
  6043. * this function. */
  6044. if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
  6045. alg = ssh2_kexinit_addalg(s->kexlists[j],
  6046. s->preferred_comp->delayed_name);
  6047. alg->u.comp = s->preferred_comp;
  6048. }
  6049. for (i = 0; i < lenof(compressions); i++) {
  6050. const struct ssh_compress *c = compressions[i];
  6051. alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
  6052. alg->u.comp = c;
  6053. if (s->userauth_succeeded && c->delayed_name) {
  6054. alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
  6055. alg->u.comp = c;
  6056. }
  6057. }
  6058. }
  6059. /*
  6060. * Construct and send our key exchange packet.
  6061. */
  6062. s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
  6063. for (i = 0; i < 16; i++)
  6064. ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
  6065. for (i = 0; i < NKEXLIST; i++) {
  6066. ssh2_pkt_addstring_start(s->pktout);
  6067. for (j = 0; j < MAXKEXLIST; j++) {
  6068. if (s->kexlists[i][j].name == NULL) break;
  6069. ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
  6070. }
  6071. }
  6072. /* List client->server languages. Empty list. */
  6073. ssh2_pkt_addstring_start(s->pktout);
  6074. /* List server->client languages. Empty list. */
  6075. ssh2_pkt_addstring_start(s->pktout);
  6076. /* First KEX packet does _not_ follow, because we're not that brave. */
  6077. ssh2_pkt_addbool(s->pktout, FALSE);
  6078. /* Reserved. */
  6079. ssh2_pkt_adduint32(s->pktout, 0);
  6080. }
  6081. s->our_kexinitlen = s->pktout->length - 5;
  6082. s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
  6083. memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
  6084. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6085. if (!pktin)
  6086. crWaitUntilV(pktin);
  6087. /*
  6088. * Now examine the other side's KEXINIT to see what we're up
  6089. * to.
  6090. */
  6091. {
  6092. char *str;
  6093. int i, j, len;
  6094. if (pktin->type != SSH2_MSG_KEXINIT) {
  6095. bombout(("expected key exchange packet from server"));
  6096. crStopV;
  6097. }
  6098. ssh->kex = NULL;
  6099. ssh->hostkey = NULL;
  6100. s->cscipher_tobe = NULL;
  6101. s->sccipher_tobe = NULL;
  6102. s->csmac_tobe = NULL;
  6103. s->scmac_tobe = NULL;
  6104. s->cscomp_tobe = NULL;
  6105. s->sccomp_tobe = NULL;
  6106. s->warn_kex = s->warn_hk = FALSE;
  6107. s->warn_cscipher = s->warn_sccipher = FALSE;
  6108. pktin->savedpos += 16; /* skip garbage cookie */
  6109. s->guessok = FALSE;
  6110. for (i = 0; i < NKEXLIST; i++) {
  6111. ssh_pkt_getstring(pktin, &str, &len);
  6112. if (!str) {
  6113. bombout(("KEXINIT packet was incomplete"));
  6114. crStopV;
  6115. }
  6116. /* If we've already selected a cipher which requires a
  6117. * particular MAC, then just select that, and don't even
  6118. * bother looking through the server's KEXINIT string for
  6119. * MACs. */
  6120. if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
  6121. s->cscipher_tobe->required_mac) {
  6122. s->csmac_tobe = s->cscipher_tobe->required_mac;
  6123. s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
  6124. goto matched;
  6125. }
  6126. if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
  6127. s->sccipher_tobe->required_mac) {
  6128. s->scmac_tobe = s->sccipher_tobe->required_mac;
  6129. s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
  6130. goto matched;
  6131. }
  6132. for (j = 0; j < MAXKEXLIST; j++) {
  6133. struct kexinit_algorithm *alg = &s->kexlists[i][j];
  6134. if (alg->name == NULL) break;
  6135. if (in_commasep_string(alg->name, str, len)) {
  6136. /* We've found a matching algorithm. */
  6137. if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
  6138. /* Check if we might need to ignore first kex pkt */
  6139. if (j != 0 ||
  6140. !first_in_commasep_string(alg->name, str, len))
  6141. s->guessok = FALSE;
  6142. }
  6143. if (i == KEXLIST_KEX) {
  6144. ssh->kex = alg->u.kex.kex;
  6145. s->warn_kex = alg->u.kex.warn;
  6146. } else if (i == KEXLIST_HOSTKEY) {
  6147. ssh->hostkey = alg->u.hk.hostkey;
  6148. s->warn_hk = alg->u.hk.warn;
  6149. } else if (i == KEXLIST_CSCIPHER) {
  6150. s->cscipher_tobe = alg->u.cipher.cipher;
  6151. s->warn_cscipher = alg->u.cipher.warn;
  6152. } else if (i == KEXLIST_SCCIPHER) {
  6153. s->sccipher_tobe = alg->u.cipher.cipher;
  6154. s->warn_sccipher = alg->u.cipher.warn;
  6155. } else if (i == KEXLIST_CSMAC) {
  6156. s->csmac_tobe = alg->u.mac.mac;
  6157. s->csmac_etm_tobe = alg->u.mac.etm;
  6158. } else if (i == KEXLIST_SCMAC) {
  6159. s->scmac_tobe = alg->u.mac.mac;
  6160. s->scmac_etm_tobe = alg->u.mac.etm;
  6161. } else if (i == KEXLIST_CSCOMP) {
  6162. s->cscomp_tobe = alg->u.comp;
  6163. } else if (i == KEXLIST_SCCOMP) {
  6164. s->sccomp_tobe = alg->u.comp;
  6165. }
  6166. goto matched;
  6167. }
  6168. if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
  6169. in_commasep_string(alg->u.comp->delayed_name, str, len))
  6170. s->pending_compression = TRUE; /* try this later */
  6171. }
  6172. bombout(("Couldn't agree a %s (available: %.*s)",
  6173. kexlist_descr[i], len, str));
  6174. crStopV;
  6175. matched:;
  6176. if (i == KEXLIST_HOSTKEY) {
  6177. int j;
  6178. /*
  6179. * In addition to deciding which host key we're
  6180. * actually going to use, we should make a list of the
  6181. * host keys offered by the server which we _don't_
  6182. * have cached. These will be offered as cross-
  6183. * certification options by ssh_get_specials.
  6184. *
  6185. * We also count the key we're currently using for KEX
  6186. * as one we've already got, because by the time this
  6187. * menu becomes visible, it will be.
  6188. */
  6189. ssh->n_uncert_hostkeys = 0;
  6190. for (j = 0; j < lenof(hostkey_algs); j++) {
  6191. if (hostkey_algs[j].alg != ssh->hostkey &&
  6192. in_commasep_string(hostkey_algs[j].alg->name,
  6193. str, len) &&
  6194. !have_ssh_host_key(
  6195. #ifdef MPEXT
  6196. ssh->frontend,
  6197. #endif
  6198. ssh->savedhost, ssh->savedport,
  6199. hostkey_algs[j].alg->keytype)) {
  6200. ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
  6201. }
  6202. }
  6203. }
  6204. }
  6205. if (s->pending_compression) {
  6206. logevent("Server supports delayed compression; "
  6207. "will try this later");
  6208. }
  6209. ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
  6210. ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
  6211. s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
  6212. ssh->exhash = ssh->kex->hash->init();
  6213. hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
  6214. hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
  6215. hash_string(ssh->kex->hash, ssh->exhash,
  6216. s->our_kexinit, s->our_kexinitlen);
  6217. sfree(s->our_kexinit);
  6218. /* Include the type byte in the hash of server's KEXINIT */
  6219. hash_string(ssh->kex->hash, ssh->exhash,
  6220. pktin->body - 1, pktin->length + 1);
  6221. if (s->warn_kex) {
  6222. ssh_set_frozen(ssh, 1);
  6223. s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
  6224. ssh->kex->name,
  6225. ssh_dialog_callback, ssh);
  6226. if (s->dlgret < 0) {
  6227. do {
  6228. crReturnV;
  6229. if (pktin) {
  6230. bombout(("Unexpected data from server while"
  6231. " waiting for user response"));
  6232. crStopV;
  6233. }
  6234. } while (pktin || inlen > 0);
  6235. s->dlgret = ssh->user_response;
  6236. }
  6237. ssh_set_frozen(ssh, 0);
  6238. if (s->dlgret == 0) {
  6239. ssh_disconnect(ssh, "User aborted at kex warning", NULL,
  6240. 0, TRUE);
  6241. crStopV;
  6242. }
  6243. }
  6244. if (s->warn_hk) {
  6245. int j, k;
  6246. char *betteralgs;
  6247. ssh_set_frozen(ssh, 1);
  6248. /*
  6249. * Change warning box wording depending on why we chose a
  6250. * warning-level host key algorithm. If it's because
  6251. * that's all we have *cached*, use the askhk mechanism,
  6252. * and list the host keys we could usefully cross-certify.
  6253. * Otherwise, use askalg for the standard wording.
  6254. */
  6255. betteralgs = NULL;
  6256. for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
  6257. const struct ssh_signkey_with_user_pref_id *hktype =
  6258. &hostkey_algs[ssh->uncert_hostkeys[j]];
  6259. int better = FALSE;
  6260. for (k = 0; k < HK_MAX; k++) {
  6261. int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
  6262. if (id == HK_WARN) {
  6263. break;
  6264. } else if (id == hktype->id) {
  6265. better = TRUE;
  6266. break;
  6267. }
  6268. }
  6269. if (better) {
  6270. if (betteralgs) {
  6271. char *old_ba = betteralgs;
  6272. betteralgs = dupcat(betteralgs, ",",
  6273. hktype->alg->name,
  6274. (const char *)NULL);
  6275. sfree(old_ba);
  6276. } else {
  6277. betteralgs = dupstr(hktype->alg->name);
  6278. }
  6279. }
  6280. }
  6281. if (betteralgs) {
  6282. s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
  6283. betteralgs, ssh_dialog_callback, ssh);
  6284. sfree(betteralgs);
  6285. } else {
  6286. s->dlgret = askalg(ssh->frontend, "host key type",
  6287. ssh->hostkey->name,
  6288. ssh_dialog_callback, ssh);
  6289. }
  6290. if (s->dlgret < 0) {
  6291. do {
  6292. crReturnV;
  6293. if (pktin) {
  6294. bombout(("Unexpected data from server while"
  6295. " waiting for user response"));
  6296. crStopV;
  6297. }
  6298. } while (pktin || inlen > 0);
  6299. s->dlgret = ssh->user_response;
  6300. }
  6301. ssh_set_frozen(ssh, 0);
  6302. if (s->dlgret == 0) {
  6303. ssh_disconnect(ssh, "User aborted at host key warning", NULL,
  6304. 0, TRUE);
  6305. crStopV;
  6306. }
  6307. }
  6308. if (s->warn_cscipher) {
  6309. ssh_set_frozen(ssh, 1);
  6310. s->dlgret = askalg(ssh->frontend,
  6311. "client-to-server cipher",
  6312. s->cscipher_tobe->name,
  6313. ssh_dialog_callback, ssh);
  6314. if (s->dlgret < 0) {
  6315. do {
  6316. crReturnV;
  6317. if (pktin) {
  6318. bombout(("Unexpected data from server while"
  6319. " waiting for user response"));
  6320. crStopV;
  6321. }
  6322. } while (pktin || inlen > 0);
  6323. s->dlgret = ssh->user_response;
  6324. }
  6325. ssh_set_frozen(ssh, 0);
  6326. if (s->dlgret == 0) {
  6327. ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
  6328. 0, TRUE);
  6329. crStopV;
  6330. }
  6331. }
  6332. if (s->warn_sccipher) {
  6333. ssh_set_frozen(ssh, 1);
  6334. s->dlgret = askalg(ssh->frontend,
  6335. "server-to-client cipher",
  6336. s->sccipher_tobe->name,
  6337. ssh_dialog_callback, ssh);
  6338. if (s->dlgret < 0) {
  6339. do {
  6340. crReturnV;
  6341. if (pktin) {
  6342. bombout(("Unexpected data from server while"
  6343. " waiting for user response"));
  6344. crStopV;
  6345. }
  6346. } while (pktin || inlen > 0);
  6347. s->dlgret = ssh->user_response;
  6348. }
  6349. ssh_set_frozen(ssh, 0);
  6350. if (s->dlgret == 0) {
  6351. ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
  6352. 0, TRUE);
  6353. crStopV;
  6354. }
  6355. }
  6356. if (s->ignorepkt) /* first_kex_packet_follows */
  6357. crWaitUntilV(pktin); /* Ignore packet */
  6358. }
  6359. if (ssh->kex->main_type == KEXTYPE_DH) {
  6360. /*
  6361. * Work out the number of bits of key we will need from the
  6362. * key exchange. We start with the maximum key length of
  6363. * either cipher...
  6364. */
  6365. {
  6366. int csbits, scbits;
  6367. csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
  6368. scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
  6369. s->nbits = (csbits > scbits ? csbits : scbits);
  6370. }
  6371. /* The keys only have hlen-bit entropy, since they're based on
  6372. * a hash. So cap the key size at hlen bits. */
  6373. if (s->nbits > ssh->kex->hash->hlen * 8)
  6374. s->nbits = ssh->kex->hash->hlen * 8;
  6375. /*
  6376. * If we're doing Diffie-Hellman group exchange, start by
  6377. * requesting a group.
  6378. */
  6379. if (dh_is_gex(ssh->kex)) {
  6380. logevent("Doing Diffie-Hellman group exchange");
  6381. ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
  6382. /*
  6383. * Work out how big a DH group we will need to allow that
  6384. * much data.
  6385. */
  6386. s->pbits = 512 << ((s->nbits - 1) / 64);
  6387. if (s->pbits < DH_MIN_SIZE)
  6388. s->pbits = DH_MIN_SIZE;
  6389. if (s->pbits > DH_MAX_SIZE)
  6390. s->pbits = DH_MAX_SIZE;
  6391. if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
  6392. s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
  6393. ssh2_pkt_adduint32(s->pktout, s->pbits);
  6394. } else {
  6395. s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
  6396. ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
  6397. ssh2_pkt_adduint32(s->pktout, s->pbits);
  6398. ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
  6399. }
  6400. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6401. crWaitUntilV(pktin);
  6402. if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
  6403. bombout(("expected key exchange group packet from server"));
  6404. crStopV;
  6405. }
  6406. s->p = ssh2_pkt_getmp(pktin);
  6407. s->g = ssh2_pkt_getmp(pktin);
  6408. if (!s->p || !s->g) {
  6409. bombout(("unable to read mp-ints from incoming group packet"));
  6410. crStopV;
  6411. }
  6412. ssh->kex_ctx = dh_setup_gex(s->p, s->g);
  6413. s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
  6414. s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
  6415. } else {
  6416. ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
  6417. ssh->kex_ctx = dh_setup_group(ssh->kex);
  6418. s->kex_init_value = SSH2_MSG_KEXDH_INIT;
  6419. s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
  6420. logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
  6421. ssh->kex->groupname);
  6422. }
  6423. logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
  6424. ssh->kex->hash->text_name);
  6425. /*
  6426. * Now generate and send e for Diffie-Hellman.
  6427. */
  6428. set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
  6429. s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
  6430. s->pktout = ssh2_pkt_init(s->kex_init_value);
  6431. ssh2_pkt_addmp(s->pktout, s->e);
  6432. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6433. set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
  6434. crWaitUntilV(pktin);
  6435. if (pktin->type != s->kex_reply_value) {
  6436. bombout(("expected key exchange reply packet from server"));
  6437. crStopV;
  6438. }
  6439. set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
  6440. ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
  6441. if (!s->hostkeydata) {
  6442. bombout(("unable to parse key exchange reply packet"));
  6443. crStopV;
  6444. }
  6445. s->hkey = ssh->hostkey->newkey(ssh->hostkey,
  6446. s->hostkeydata, s->hostkeylen);
  6447. s->f = ssh2_pkt_getmp(pktin);
  6448. if (!s->f) {
  6449. bombout(("unable to parse key exchange reply packet"));
  6450. crStopV;
  6451. }
  6452. ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
  6453. if (!s->sigdata) {
  6454. bombout(("unable to parse key exchange reply packet"));
  6455. crStopV;
  6456. }
  6457. {
  6458. const char *err = dh_validate_f(ssh->kex_ctx, s->f);
  6459. if (err) {
  6460. bombout(("key exchange reply failed validation: %s", err));
  6461. crStopV;
  6462. }
  6463. }
  6464. s->K = dh_find_K(ssh->kex_ctx, s->f);
  6465. /* We assume everything from now on will be quick, and it might
  6466. * involve user interaction. */
  6467. set_busy_status(ssh->frontend, BUSY_NOT);
  6468. hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
  6469. if (dh_is_gex(ssh->kex)) {
  6470. if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
  6471. hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
  6472. hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
  6473. if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
  6474. hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
  6475. hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
  6476. hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
  6477. }
  6478. hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
  6479. hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
  6480. dh_cleanup(ssh->kex_ctx);
  6481. freebn(s->f);
  6482. if (dh_is_gex(ssh->kex)) {
  6483. freebn(s->g);
  6484. freebn(s->p);
  6485. }
  6486. } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
  6487. logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
  6488. ssh_ecdhkex_curve_textname(ssh->kex),
  6489. ssh->kex->hash->text_name);
  6490. ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
  6491. s->eckey = ssh_ecdhkex_newkey(ssh->kex);
  6492. if (!s->eckey) {
  6493. bombout(("Unable to generate key for ECDH"));
  6494. crStopV;
  6495. }
  6496. {
  6497. char *publicPoint;
  6498. int publicPointLength;
  6499. publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
  6500. if (!publicPoint) {
  6501. ssh_ecdhkex_freekey(s->eckey);
  6502. bombout(("Unable to encode public key for ECDH"));
  6503. crStopV;
  6504. }
  6505. s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
  6506. ssh2_pkt_addstring_start(s->pktout);
  6507. ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
  6508. sfree(publicPoint);
  6509. }
  6510. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6511. crWaitUntilV(pktin);
  6512. if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
  6513. ssh_ecdhkex_freekey(s->eckey);
  6514. bombout(("expected ECDH reply packet from server"));
  6515. crStopV;
  6516. }
  6517. ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
  6518. if (!s->hostkeydata) {
  6519. bombout(("unable to parse ECDH reply packet"));
  6520. crStopV;
  6521. }
  6522. hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
  6523. s->hkey = ssh->hostkey->newkey(ssh->hostkey,
  6524. s->hostkeydata, s->hostkeylen);
  6525. {
  6526. char *publicPoint;
  6527. int publicPointLength;
  6528. publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
  6529. if (!publicPoint) {
  6530. ssh_ecdhkex_freekey(s->eckey);
  6531. bombout(("Unable to encode public key for ECDH hash"));
  6532. crStopV;
  6533. }
  6534. hash_string(ssh->kex->hash, ssh->exhash,
  6535. publicPoint, publicPointLength);
  6536. sfree(publicPoint);
  6537. }
  6538. {
  6539. char *keydata;
  6540. int keylen;
  6541. ssh_pkt_getstring(pktin, &keydata, &keylen);
  6542. if (!keydata) {
  6543. bombout(("unable to parse ECDH reply packet"));
  6544. crStopV;
  6545. }
  6546. hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
  6547. s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
  6548. if (!s->K) {
  6549. ssh_ecdhkex_freekey(s->eckey);
  6550. bombout(("point received in ECDH was not valid"));
  6551. crStopV;
  6552. }
  6553. }
  6554. ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
  6555. if (!s->sigdata) {
  6556. bombout(("unable to parse key exchange reply packet"));
  6557. crStopV;
  6558. }
  6559. ssh_ecdhkex_freekey(s->eckey);
  6560. } else {
  6561. logeventf(ssh, "Doing RSA key exchange with hash %s",
  6562. ssh->kex->hash->text_name);
  6563. ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
  6564. /*
  6565. * RSA key exchange. First expect a KEXRSA_PUBKEY packet
  6566. * from the server.
  6567. */
  6568. crWaitUntilV(pktin);
  6569. if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
  6570. bombout(("expected RSA public key packet from server"));
  6571. crStopV;
  6572. }
  6573. ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
  6574. if (!s->hostkeydata) {
  6575. bombout(("unable to parse RSA public key packet"));
  6576. crStopV;
  6577. }
  6578. hash_string(ssh->kex->hash, ssh->exhash,
  6579. s->hostkeydata, s->hostkeylen);
  6580. s->hkey = ssh->hostkey->newkey(ssh->hostkey,
  6581. s->hostkeydata, s->hostkeylen);
  6582. {
  6583. char *keydata;
  6584. ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
  6585. if (!keydata) {
  6586. bombout(("unable to parse RSA public key packet"));
  6587. crStopV;
  6588. }
  6589. s->rsakeydata = snewn(s->rsakeylen, char);
  6590. memcpy(s->rsakeydata, keydata, s->rsakeylen);
  6591. }
  6592. s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
  6593. if (!s->rsakey) {
  6594. sfree(s->rsakeydata);
  6595. bombout(("unable to parse RSA public key from server"));
  6596. crStopV;
  6597. }
  6598. hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
  6599. /*
  6600. * Next, set up a shared secret K, of precisely KLEN -
  6601. * 2*HLEN - 49 bits, where KLEN is the bit length of the
  6602. * RSA key modulus and HLEN is the bit length of the hash
  6603. * we're using.
  6604. */
  6605. {
  6606. int klen = ssh_rsakex_klen(s->rsakey);
  6607. int nbits;
  6608. int i, byte = 0;
  6609. unsigned char *kstr1, *kstr2, *outstr;
  6610. int kstr1len, kstr2len, outstrlen;
  6611. const struct ssh_rsa_kex_extra *extra =
  6612. (const struct ssh_rsa_kex_extra *)ssh->kex->extra;
  6613. if (klen < extra->minklen) {
  6614. bombout(("Server sent RSA key with less bits than the minimum size for key exchange"));
  6615. crStopV;
  6616. }
  6617. nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
  6618. s->K = bn_power_2(nbits - 1);
  6619. for (i = 0; i < nbits; i++) {
  6620. if ((i & 7) == 0) {
  6621. byte = random_byte();
  6622. }
  6623. bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
  6624. }
  6625. /*
  6626. * Encode this as an mpint.
  6627. */
  6628. kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
  6629. kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
  6630. PUT_32BIT(kstr2, kstr1len);
  6631. memcpy(kstr2 + 4, kstr1, kstr1len);
  6632. /*
  6633. * Encrypt it with the given RSA key.
  6634. */
  6635. outstrlen = (klen + 7) / 8;
  6636. outstr = snewn(outstrlen, unsigned char);
  6637. ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
  6638. outstr, outstrlen, s->rsakey);
  6639. /*
  6640. * And send it off in a return packet.
  6641. */
  6642. s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
  6643. ssh2_pkt_addstring_start(s->pktout);
  6644. ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
  6645. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6646. hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
  6647. sfree(kstr2);
  6648. sfree(kstr1);
  6649. sfree(outstr);
  6650. }
  6651. ssh_rsakex_freekey(s->rsakey);
  6652. crWaitUntilV(pktin);
  6653. if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
  6654. sfree(s->rsakeydata);
  6655. bombout(("expected signature packet from server"));
  6656. crStopV;
  6657. }
  6658. ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
  6659. if (!s->sigdata) {
  6660. bombout(("unable to parse signature packet"));
  6661. crStopV;
  6662. }
  6663. sfree(s->rsakeydata);
  6664. }
  6665. hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
  6666. assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
  6667. ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
  6668. ssh->kex_ctx = NULL;
  6669. #if 0
  6670. debug(("Exchange hash is:\n"));
  6671. dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
  6672. #endif
  6673. if (!s->hkey) {
  6674. bombout(("Server's host key is invalid"));
  6675. crStopV;
  6676. }
  6677. if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
  6678. (char *)s->exchange_hash,
  6679. ssh->kex->hash->hlen)) {
  6680. #ifndef FUZZING
  6681. bombout(("Server's host key did not match the signature supplied"));
  6682. crStopV;
  6683. #endif
  6684. }
  6685. s->keystr = ssh->hostkey->fmtkey(s->hkey);
  6686. if (!s->got_session_id) {
  6687. /*
  6688. * Make a note of any other host key formats that are available.
  6689. */
  6690. {
  6691. int i, j, nkeys = 0;
  6692. char *list = NULL;
  6693. for (i = 0; i < lenof(hostkey_algs); i++) {
  6694. if (hostkey_algs[i].alg == ssh->hostkey)
  6695. continue;
  6696. for (j = 0; j < ssh->n_uncert_hostkeys; j++)
  6697. if (ssh->uncert_hostkeys[j] == i)
  6698. break;
  6699. if (j < ssh->n_uncert_hostkeys) {
  6700. char *newlist;
  6701. if (list)
  6702. newlist = dupprintf("%s/%s", list,
  6703. hostkey_algs[i].alg->name);
  6704. else
  6705. newlist = dupprintf("%s", hostkey_algs[i].alg->name);
  6706. sfree(list);
  6707. list = newlist;
  6708. nkeys++;
  6709. }
  6710. }
  6711. if (list) {
  6712. logeventf(ssh,
  6713. "Server also has %s host key%s, but we "
  6714. "don't know %s", list,
  6715. nkeys > 1 ? "s" : "",
  6716. nkeys > 1 ? "any of them" : "it");
  6717. sfree(list);
  6718. }
  6719. }
  6720. /*
  6721. * Authenticate remote host: verify host key. (We've already
  6722. * checked the signature of the exchange hash.)
  6723. */
  6724. s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
  6725. logevent("Host key fingerprint is:");
  6726. logevent(s->fingerprint);
  6727. /* First check against manually configured host keys. */
  6728. s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
  6729. ssh->hostkey, s->hkey);
  6730. if (s->dlgret == 0) { /* did not match */
  6731. bombout(("Host key did not appear in manually configured list"));
  6732. crStopV;
  6733. } else if (s->dlgret < 0) { /* none configured; use standard handling */
  6734. ssh_set_frozen(ssh, 1);
  6735. s->dlgret = verify_ssh_host_key(ssh->frontend,
  6736. ssh->savedhost, ssh->savedport,
  6737. ssh->hostkey->keytype, s->keystr,
  6738. s->fingerprint,
  6739. ssh_dialog_callback, ssh);
  6740. #ifdef FUZZING
  6741. s->dlgret = 1;
  6742. #endif
  6743. if (s->dlgret < 0) {
  6744. do {
  6745. crReturnV;
  6746. if (pktin) {
  6747. bombout(("Unexpected data from server while waiting"
  6748. " for user host key response"));
  6749. crStopV;
  6750. }
  6751. } while (pktin || inlen > 0);
  6752. s->dlgret = ssh->user_response;
  6753. }
  6754. ssh_set_frozen(ssh, 0);
  6755. if (s->dlgret == 0) {
  6756. ssh_disconnect(ssh, "Aborted at host key verification", NULL,
  6757. 0, TRUE);
  6758. crStopV;
  6759. }
  6760. }
  6761. sfree(s->fingerprint);
  6762. /*
  6763. * Save this host key, to check against the one presented in
  6764. * subsequent rekeys.
  6765. */
  6766. ssh->hostkey_str = s->keystr;
  6767. } else if (ssh->cross_certifying) {
  6768. s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
  6769. logevent("Storing additional host key for this host:");
  6770. logevent(s->fingerprint);
  6771. sfree(s->fingerprint);
  6772. store_host_key(ssh->savedhost, ssh->savedport,
  6773. ssh->hostkey->keytype, s->keystr);
  6774. ssh->cross_certifying = FALSE;
  6775. /*
  6776. * Don't forget to store the new key as the one we'll be
  6777. * re-checking in future normal rekeys.
  6778. */
  6779. ssh->hostkey_str = s->keystr;
  6780. } else {
  6781. /*
  6782. * In a rekey, we never present an interactive host key
  6783. * verification request to the user. Instead, we simply
  6784. * enforce that the key we're seeing this time is identical to
  6785. * the one we saw before.
  6786. */
  6787. if (strcmp(ssh->hostkey_str, s->keystr)) {
  6788. #ifndef FUZZING
  6789. bombout(("Host key was different in repeat key exchange"));
  6790. crStopV;
  6791. #endif
  6792. }
  6793. sfree(s->keystr);
  6794. }
  6795. ssh->hostkey->freekey(s->hkey);
  6796. /*
  6797. * The exchange hash from the very first key exchange is also
  6798. * the session id, used in session key construction and
  6799. * authentication.
  6800. */
  6801. if (!s->got_session_id) {
  6802. assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
  6803. memcpy(ssh->v2_session_id, s->exchange_hash,
  6804. sizeof(s->exchange_hash));
  6805. ssh->v2_session_id_len = ssh->kex->hash->hlen;
  6806. assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
  6807. s->got_session_id = TRUE;
  6808. }
  6809. /*
  6810. * Send SSH2_MSG_NEWKEYS.
  6811. */
  6812. s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
  6813. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6814. ssh->outgoing_data_size = 0; /* start counting from here */
  6815. /*
  6816. * We've sent client NEWKEYS, so create and initialise
  6817. * client-to-server session keys.
  6818. */
  6819. if (ssh->cs_cipher_ctx)
  6820. ssh->cscipher->free_context(ssh->cs_cipher_ctx);
  6821. ssh->cscipher = s->cscipher_tobe;
  6822. if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
  6823. if (ssh->cs_mac_ctx)
  6824. ssh->csmac->free_context(ssh->cs_mac_ctx);
  6825. ssh->csmac = s->csmac_tobe;
  6826. ssh->csmac_etm = s->csmac_etm_tobe;
  6827. if (ssh->csmac)
  6828. ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
  6829. if (ssh->cs_comp_ctx)
  6830. ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
  6831. ssh->cscomp = s->cscomp_tobe;
  6832. ssh->cs_comp_ctx = ssh->cscomp->compress_init();
  6833. /*
  6834. * Set IVs on client-to-server keys. Here we use the exchange
  6835. * hash from the _first_ key exchange.
  6836. */
  6837. if (ssh->cscipher) {
  6838. unsigned char *key;
  6839. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
  6840. ssh->cscipher->padded_keybytes);
  6841. ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
  6842. smemclr(key, ssh->cscipher->padded_keybytes);
  6843. sfree(key);
  6844. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
  6845. ssh->cscipher->blksize);
  6846. ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
  6847. smemclr(key, ssh->cscipher->blksize);
  6848. sfree(key);
  6849. }
  6850. if (ssh->csmac) {
  6851. unsigned char *key;
  6852. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
  6853. ssh->csmac->keylen);
  6854. ssh->csmac->setkey(ssh->cs_mac_ctx, key);
  6855. smemclr(key, ssh->csmac->keylen);
  6856. sfree(key);
  6857. }
  6858. if (ssh->cscipher)
  6859. logeventf(ssh, "Initialised %.200s client->server encryption",
  6860. ssh->cscipher->text_name);
  6861. if (ssh->csmac)
  6862. logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
  6863. ssh->csmac->text_name,
  6864. ssh->csmac_etm ? " (in ETM mode)" : "",
  6865. ssh->cscipher->required_mac ? " (required by cipher)" : "");
  6866. if (ssh->cscomp->text_name)
  6867. logeventf(ssh, "Initialised %s compression",
  6868. ssh->cscomp->text_name);
  6869. /*
  6870. * Now our end of the key exchange is complete, we can send all
  6871. * our queued higher-layer packets.
  6872. */
  6873. ssh->queueing = FALSE;
  6874. ssh2_pkt_queuesend(ssh);
  6875. /*
  6876. * Expect SSH2_MSG_NEWKEYS from server.
  6877. */
  6878. crWaitUntilV(pktin);
  6879. if (pktin->type != SSH2_MSG_NEWKEYS) {
  6880. bombout(("expected new-keys packet from server"));
  6881. crStopV;
  6882. }
  6883. ssh->incoming_data_size = 0; /* start counting from here */
  6884. /*
  6885. * We've seen server NEWKEYS, so create and initialise
  6886. * server-to-client session keys.
  6887. */
  6888. if (ssh->sc_cipher_ctx)
  6889. ssh->sccipher->free_context(ssh->sc_cipher_ctx);
  6890. if (s->sccipher_tobe) {
  6891. ssh->sccipher = s->sccipher_tobe;
  6892. ssh->sc_cipher_ctx = ssh->sccipher->make_context();
  6893. }
  6894. if (ssh->sc_mac_ctx)
  6895. ssh->scmac->free_context(ssh->sc_mac_ctx);
  6896. if (s->scmac_tobe) {
  6897. ssh->scmac = s->scmac_tobe;
  6898. ssh->scmac_etm = s->scmac_etm_tobe;
  6899. ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
  6900. }
  6901. if (ssh->sc_comp_ctx)
  6902. ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
  6903. ssh->sccomp = s->sccomp_tobe;
  6904. ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
  6905. /*
  6906. * Set IVs on server-to-client keys. Here we use the exchange
  6907. * hash from the _first_ key exchange.
  6908. */
  6909. if (ssh->sccipher) {
  6910. unsigned char *key;
  6911. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
  6912. ssh->sccipher->padded_keybytes);
  6913. ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
  6914. smemclr(key, ssh->sccipher->padded_keybytes);
  6915. sfree(key);
  6916. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
  6917. ssh->sccipher->blksize);
  6918. ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
  6919. smemclr(key, ssh->sccipher->blksize);
  6920. sfree(key);
  6921. }
  6922. if (ssh->scmac) {
  6923. unsigned char *key;
  6924. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
  6925. ssh->scmac->keylen);
  6926. ssh->scmac->setkey(ssh->sc_mac_ctx, key);
  6927. smemclr(key, ssh->scmac->keylen);
  6928. sfree(key);
  6929. }
  6930. if (ssh->sccipher)
  6931. logeventf(ssh, "Initialised %.200s server->client encryption",
  6932. ssh->sccipher->text_name);
  6933. if (ssh->scmac)
  6934. logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
  6935. ssh->scmac->text_name,
  6936. ssh->scmac_etm ? " (in ETM mode)" : "",
  6937. ssh->sccipher->required_mac ? " (required by cipher)" : "");
  6938. if (ssh->sccomp->text_name)
  6939. logeventf(ssh, "Initialised %s decompression",
  6940. ssh->sccomp->text_name);
  6941. /*
  6942. * Free shared secret.
  6943. */
  6944. freebn(s->K);
  6945. /*
  6946. * Update the specials menu to list the remaining uncertified host
  6947. * keys.
  6948. */
  6949. update_specials_menu(ssh->frontend);
  6950. /*
  6951. * Key exchange is over. Loop straight back round if we have a
  6952. * deferred rekey reason.
  6953. */
  6954. if (ssh->deferred_rekey_reason) {
  6955. logevent(ssh->deferred_rekey_reason);
  6956. pktin = NULL;
  6957. ssh->deferred_rekey_reason = NULL;
  6958. goto begin_key_exchange;
  6959. }
  6960. /*
  6961. * Otherwise, schedule a timer for our next rekey.
  6962. */
  6963. ssh->kex_in_progress = FALSE;
  6964. ssh->last_rekey = GETTICKCOUNT();
  6965. if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
  6966. ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
  6967. ssh2_timer, ssh);
  6968. /*
  6969. * Now we're encrypting. Begin returning 1 to the protocol main
  6970. * function so that other things can run on top of the
  6971. * transport. If we ever see a KEXINIT, we must go back to the
  6972. * start.
  6973. *
  6974. * We _also_ go back to the start if we see pktin==NULL and
  6975. * inlen negative, because this is a special signal meaning
  6976. * `initiate client-driven rekey', and `in' contains a message
  6977. * giving the reason for the rekey.
  6978. *
  6979. * inlen==-1 means always initiate a rekey;
  6980. * inlen==-2 means that userauth has completed successfully and
  6981. * we should consider rekeying (for delayed compression).
  6982. */
  6983. while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
  6984. (!pktin && inlen < 0))) {
  6985. wait_for_rekey:
  6986. if (!ssh->protocol_initial_phase_done) {
  6987. ssh->protocol_initial_phase_done = TRUE;
  6988. /*
  6989. * Allow authconn to initialise itself.
  6990. */
  6991. do_ssh2_authconn(ssh, NULL, 0, NULL);
  6992. }
  6993. crReturnV;
  6994. }
  6995. if (pktin) {
  6996. logevent("Server initiated key re-exchange");
  6997. } else {
  6998. if (inlen == -2) {
  6999. /*
  7000. * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
  7001. * delayed compression, if it's available.
  7002. *
  7003. * draft-miller-secsh-compression-delayed-00 says that you
  7004. * negotiate delayed compression in the first key exchange, and
  7005. * both sides start compressing when the server has sent
  7006. * USERAUTH_SUCCESS. This has a race condition -- the server
  7007. * can't know when the client has seen it, and thus which incoming
  7008. * packets it should treat as compressed.
  7009. *
  7010. * Instead, we do the initial key exchange without offering the
  7011. * delayed methods, but note if the server offers them; when we
  7012. * get here, if a delayed method was available that was higher
  7013. * on our list than what we got, we initiate a rekey in which we
  7014. * _do_ list the delayed methods (and hopefully get it as a
  7015. * result). Subsequent rekeys will do the same.
  7016. */
  7017. assert(!s->userauth_succeeded); /* should only happen once */
  7018. s->userauth_succeeded = TRUE;
  7019. if (!s->pending_compression)
  7020. /* Can't see any point rekeying. */
  7021. goto wait_for_rekey; /* this is utterly horrid */
  7022. /* else fall through to rekey... */
  7023. s->pending_compression = FALSE;
  7024. }
  7025. /*
  7026. * Now we've decided to rekey.
  7027. *
  7028. * Special case: if the server bug is set that doesn't
  7029. * allow rekeying, we give a different log message and
  7030. * continue waiting. (If such a server _initiates_ a rekey,
  7031. * we process it anyway!)
  7032. */
  7033. if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
  7034. logeventf(ssh, "Server bug prevents key re-exchange (%s)",
  7035. (char *)in);
  7036. /* Reset the counters, so that at least this message doesn't
  7037. * hit the event log _too_ often. */
  7038. ssh->outgoing_data_size = 0;
  7039. ssh->incoming_data_size = 0;
  7040. if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
  7041. ssh->next_rekey =
  7042. schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
  7043. ssh2_timer, ssh);
  7044. }
  7045. goto wait_for_rekey; /* this is still utterly horrid */
  7046. } else {
  7047. logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
  7048. }
  7049. }
  7050. goto begin_key_exchange;
  7051. crFinishV;
  7052. }
  7053. /*
  7054. * Send data on an SSH channel. In SSH-2, this involves buffering it
  7055. * first.
  7056. */
  7057. static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
  7058. int len)
  7059. {
  7060. if (c->ssh->version == 2) {
  7061. bufchain_add(&c->v.v2.outbuffer, buf, len);
  7062. return ssh2_try_send(c);
  7063. } else {
  7064. send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
  7065. PKT_INT, c->remoteid,
  7066. PKT_INT, len,
  7067. PKT_DATA, buf, len,
  7068. PKT_END);
  7069. /*
  7070. * In SSH-1 we can return 0 here - implying that channels are
  7071. * never individually throttled - because the only
  7072. * circumstance that can cause throttling will be the whole
  7073. * SSH connection backing up, in which case _everything_ will
  7074. * be throttled as a whole.
  7075. */
  7076. return 0;
  7077. }
  7078. }
  7079. /*
  7080. * Attempt to send data on an SSH-2 channel.
  7081. */
  7082. static int ssh2_try_send(struct ssh_channel *c)
  7083. {
  7084. Ssh ssh = c->ssh;
  7085. struct Packet *pktout;
  7086. int ret;
  7087. while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
  7088. int len;
  7089. void *data;
  7090. bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
  7091. if ((unsigned)len > c->v.v2.remwindow)
  7092. len = c->v.v2.remwindow;
  7093. if ((unsigned)len > c->v.v2.remmaxpkt)
  7094. len = c->v.v2.remmaxpkt;
  7095. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
  7096. ssh2_pkt_adduint32(pktout, c->remoteid);
  7097. ssh2_pkt_addstring_start(pktout);
  7098. ssh2_pkt_addstring_data(pktout, data, len);
  7099. ssh2_pkt_send(ssh, pktout);
  7100. bufchain_consume(&c->v.v2.outbuffer, len);
  7101. c->v.v2.remwindow -= len;
  7102. }
  7103. /*
  7104. * After having sent as much data as we can, return the amount
  7105. * still buffered.
  7106. */
  7107. ret = bufchain_size(&c->v.v2.outbuffer);
  7108. /*
  7109. * And if there's no data pending but we need to send an EOF, send
  7110. * it.
  7111. */
  7112. if (!ret && c->pending_eof)
  7113. ssh_channel_try_eof(c);
  7114. return ret;
  7115. }
  7116. static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
  7117. {
  7118. int bufsize;
  7119. if (c->closes & CLOSES_SENT_EOF)
  7120. return; /* don't send on channels we've EOFed */
  7121. bufsize = ssh2_try_send(c);
  7122. if (bufsize == 0) {
  7123. switch (c->type) {
  7124. case CHAN_MAINSESSION:
  7125. /* stdin need not receive an unthrottle
  7126. * notification since it will be polled */
  7127. break;
  7128. case CHAN_X11:
  7129. x11_unthrottle(c->u.x11.xconn);
  7130. break;
  7131. case CHAN_AGENT:
  7132. /* Now that we've successfully sent all the outgoing
  7133. * replies we had, try to process more incoming data. */
  7134. ssh_agentf_try_forward(c);
  7135. break;
  7136. case CHAN_SOCKDATA:
  7137. pfd_unthrottle(c->u.pfd.pf);
  7138. break;
  7139. }
  7140. }
  7141. }
  7142. static int ssh_is_simple(Ssh ssh)
  7143. {
  7144. /*
  7145. * We use the 'simple' variant of the SSH protocol if we're asked
  7146. * to, except not if we're also doing connection-sharing (either
  7147. * tunnelling our packets over an upstream or expecting to be
  7148. * tunnelled over ourselves), since then the assumption that we
  7149. * have only one channel to worry about is not true after all.
  7150. */
  7151. return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
  7152. !ssh->bare_connection && !ssh->connshare);
  7153. }
  7154. /*
  7155. * Set up most of a new ssh_channel.
  7156. */
  7157. static void ssh_channel_init(struct ssh_channel *c)
  7158. {
  7159. Ssh ssh = c->ssh;
  7160. c->localid = alloc_channel_id(ssh);
  7161. c->closes = 0;
  7162. c->pending_eof = FALSE;
  7163. c->throttling_conn = FALSE;
  7164. if (ssh->version == 2) {
  7165. c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
  7166. ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
  7167. c->v.v2.chanreq_head = NULL;
  7168. c->v.v2.throttle_state = UNTHROTTLED;
  7169. bufchain_init(&c->v.v2.outbuffer);
  7170. }
  7171. add234(ssh->channels, c);
  7172. }
  7173. /*
  7174. * Construct the common parts of a CHANNEL_OPEN.
  7175. */
  7176. static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
  7177. const char *type)
  7178. {
  7179. struct Packet *pktout;
  7180. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
  7181. ssh2_pkt_addstring(pktout, type);
  7182. ssh2_pkt_adduint32(pktout, c->localid);
  7183. ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
  7184. ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
  7185. return pktout;
  7186. }
  7187. /*
  7188. * CHANNEL_FAILURE doesn't come with any indication of what message
  7189. * caused it, so we have to keep track of the outstanding
  7190. * CHANNEL_REQUESTs ourselves.
  7191. */
  7192. static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
  7193. cchandler_fn_t handler, void *ctx)
  7194. {
  7195. struct outstanding_channel_request *ocr =
  7196. snew(struct outstanding_channel_request);
  7197. assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
  7198. ocr->handler = handler;
  7199. ocr->ctx = ctx;
  7200. ocr->next = NULL;
  7201. if (!c->v.v2.chanreq_head)
  7202. c->v.v2.chanreq_head = ocr;
  7203. else
  7204. c->v.v2.chanreq_tail->next = ocr;
  7205. c->v.v2.chanreq_tail = ocr;
  7206. }
  7207. /*
  7208. * Construct the common parts of a CHANNEL_REQUEST. If handler is not
  7209. * NULL then a reply will be requested and the handler will be called
  7210. * when it arrives. The returned packet is ready to have any
  7211. * request-specific data added and be sent. Note that if a handler is
  7212. * provided, it's essential that the request actually be sent.
  7213. *
  7214. * The handler will usually be passed the response packet in pktin. If
  7215. * pktin is NULL, this means that no reply will ever be forthcoming
  7216. * (e.g. because the entire connection is being destroyed, or because
  7217. * the server initiated channel closure before we saw the response)
  7218. * and the handler should free any storage it's holding.
  7219. */
  7220. static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
  7221. const char *type,
  7222. cchandler_fn_t handler, void *ctx)
  7223. {
  7224. struct Packet *pktout;
  7225. assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
  7226. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
  7227. ssh2_pkt_adduint32(pktout, c->remoteid);
  7228. ssh2_pkt_addstring(pktout, type);
  7229. ssh2_pkt_addbool(pktout, handler != NULL);
  7230. if (handler != NULL)
  7231. ssh2_queue_chanreq_handler(c, handler, ctx);
  7232. return pktout;
  7233. }
  7234. static void ssh_channel_unthrottle(struct ssh_channel *c, int bufsize)
  7235. {
  7236. Ssh ssh = c->ssh;
  7237. int buflimit;
  7238. if (ssh->version == 1) {
  7239. buflimit = SSH1_BUFFER_LIMIT;
  7240. } else {
  7241. if (ssh_is_simple(ssh))
  7242. buflimit = 0;
  7243. else
  7244. buflimit = c->v.v2.locmaxwin;
  7245. if (bufsize < buflimit)
  7246. ssh2_set_window(c, buflimit - bufsize);
  7247. }
  7248. if (c->throttling_conn && bufsize <= buflimit) {
  7249. c->throttling_conn = 0;
  7250. ssh_throttle_conn(ssh, -1);
  7251. }
  7252. }
  7253. /*
  7254. * Potentially enlarge the window on an SSH-2 channel.
  7255. */
  7256. static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
  7257. void *);
  7258. static void ssh2_set_window(struct ssh_channel *c, int newwin)
  7259. {
  7260. Ssh ssh = c->ssh;
  7261. /*
  7262. * Never send WINDOW_ADJUST for a channel that the remote side has
  7263. * already sent EOF on; there's no point, since it won't be
  7264. * sending any more data anyway. Ditto if _we've_ already sent
  7265. * CLOSE.
  7266. */
  7267. if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
  7268. return;
  7269. /*
  7270. * Also, never widen the window for an X11 channel when we're
  7271. * still waiting to see its initial auth and may yet hand it off
  7272. * to a downstream.
  7273. */
  7274. if (c->type == CHAN_X11 && c->u.x11.initial)
  7275. return;
  7276. /*
  7277. * If the remote end has a habit of ignoring maxpkt, limit the
  7278. * window so that it has no choice (assuming it doesn't ignore the
  7279. * window as well).
  7280. */
  7281. if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
  7282. newwin = OUR_V2_MAXPKT;
  7283. /*
  7284. * Only send a WINDOW_ADJUST if there's significantly more window
  7285. * available than the other end thinks there is. This saves us
  7286. * sending a WINDOW_ADJUST for every character in a shell session.
  7287. *
  7288. * "Significant" is arbitrarily defined as half the window size.
  7289. */
  7290. if (newwin / 2 >= c->v.v2.locwindow) {
  7291. struct Packet *pktout;
  7292. unsigned *up;
  7293. /*
  7294. * In order to keep track of how much window the client
  7295. * actually has available, we'd like it to acknowledge each
  7296. * WINDOW_ADJUST. We can't do that directly, so we accompany
  7297. * it with a CHANNEL_REQUEST that has to be acknowledged.
  7298. *
  7299. * This is only necessary if we're opening the window wide.
  7300. * If we're not, then throughput is being constrained by
  7301. * something other than the maximum window size anyway.
  7302. */
  7303. if (newwin == c->v.v2.locmaxwin &&
  7304. !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
  7305. up = snew(unsigned);
  7306. *up = newwin - c->v.v2.locwindow;
  7307. pktout = ssh2_chanreq_init(c, "[email protected]",
  7308. ssh2_handle_winadj_response, up);
  7309. ssh2_pkt_send(ssh, pktout);
  7310. if (c->v.v2.throttle_state != UNTHROTTLED)
  7311. c->v.v2.throttle_state = UNTHROTTLING;
  7312. } else {
  7313. /* Pretend the WINDOW_ADJUST was acked immediately. */
  7314. c->v.v2.remlocwin = newwin;
  7315. c->v.v2.throttle_state = THROTTLED;
  7316. }
  7317. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  7318. ssh2_pkt_adduint32(pktout, c->remoteid);
  7319. ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
  7320. ssh2_pkt_send(ssh, pktout);
  7321. c->v.v2.locwindow = newwin;
  7322. }
  7323. }
  7324. /*
  7325. * Find the channel associated with a message. If there's no channel,
  7326. * or it's not properly open, make a noise about it and return NULL.
  7327. * If the channel is shared, pass the message on to downstream and
  7328. * also return NULL (meaning the caller should ignore this message).
  7329. */
  7330. static struct ssh_channel *ssh_channel_msg(Ssh ssh, struct Packet *pktin)
  7331. {
  7332. unsigned localid = ssh_pkt_getuint32(pktin);
  7333. struct ssh_channel *c;
  7334. int halfopen_ok;
  7335. /* Is this message OK on a half-open connection? */
  7336. if (ssh->version == 1)
  7337. halfopen_ok = (pktin->type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION ||
  7338. pktin->type == SSH1_MSG_CHANNEL_OPEN_FAILURE);
  7339. else
  7340. halfopen_ok = (pktin->type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION ||
  7341. pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE);
  7342. c = find234(ssh->channels, &localid, ssh_channelfind);
  7343. if (!c || (c->type != CHAN_SHARING && (c->halfopen != halfopen_ok))) {
  7344. char *buf = dupprintf("Received %s for %s channel %u",
  7345. ssh_pkt_type(ssh, pktin->type),
  7346. !c ? "nonexistent" :
  7347. c->halfopen ? "half-open" : "open",
  7348. localid);
  7349. ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
  7350. sfree(buf);
  7351. return NULL;
  7352. }
  7353. if (c->type == CHAN_SHARING) {
  7354. share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
  7355. pktin->body, pktin->length);
  7356. return NULL;
  7357. }
  7358. return c;
  7359. }
  7360. static void ssh2_handle_winadj_response(struct ssh_channel *c,
  7361. struct Packet *pktin, void *ctx)
  7362. {
  7363. unsigned *sizep = ctx;
  7364. /*
  7365. * Winadj responses should always be failures. However, at least
  7366. * one server ("boks_sshd") is known to return SUCCESS for channel
  7367. * requests it's never heard of, such as "winadj@putty". Raised
  7368. * with foxt.com as bug 090916-090424, but for the sake of a quiet
  7369. * life, we don't worry about what kind of response we got.
  7370. */
  7371. c->v.v2.remlocwin += *sizep;
  7372. sfree(sizep);
  7373. /*
  7374. * winadj messages are only sent when the window is fully open, so
  7375. * if we get an ack of one, we know any pending unthrottle is
  7376. * complete.
  7377. */
  7378. if (c->v.v2.throttle_state == UNTHROTTLING)
  7379. c->v.v2.throttle_state = UNTHROTTLED;
  7380. }
  7381. static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
  7382. {
  7383. struct ssh_channel *c = ssh_channel_msg(ssh, pktin);
  7384. struct outstanding_channel_request *ocr;
  7385. if (!c) return;
  7386. ocr = c->v.v2.chanreq_head;
  7387. if (!ocr) {
  7388. ssh2_msg_unexpected(ssh, pktin);
  7389. return;
  7390. }
  7391. ocr->handler(c, pktin, ocr->ctx);
  7392. c->v.v2.chanreq_head = ocr->next;
  7393. sfree(ocr);
  7394. /*
  7395. * We may now initiate channel-closing procedures, if that
  7396. * CHANNEL_REQUEST was the last thing outstanding before we send
  7397. * CHANNEL_CLOSE.
  7398. */
  7399. ssh2_channel_check_close(c);
  7400. }
  7401. static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
  7402. {
  7403. struct ssh_channel *c;
  7404. c = ssh_channel_msg(ssh, pktin);
  7405. if (!c)
  7406. return;
  7407. if (!(c->closes & CLOSES_SENT_EOF)) {
  7408. c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
  7409. ssh2_try_send_and_unthrottle(ssh, c);
  7410. }
  7411. }
  7412. static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
  7413. {
  7414. char *data;
  7415. int length;
  7416. unsigned ext_type = 0; /* 0 means not extended */
  7417. struct ssh_channel *c;
  7418. c = ssh_channel_msg(ssh, pktin);
  7419. if (!c)
  7420. return;
  7421. if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
  7422. ext_type = ssh_pkt_getuint32(pktin);
  7423. ssh_pkt_getstring(pktin, &data, &length);
  7424. if (data) {
  7425. int bufsize;
  7426. c->v.v2.locwindow -= length;
  7427. c->v.v2.remlocwin -= length;
  7428. if (ext_type != 0 && ext_type != SSH2_EXTENDED_DATA_STDERR)
  7429. length = 0; /* Don't do anything with unknown extended data. */
  7430. bufsize = ssh_channel_data(c, ext_type == SSH2_EXTENDED_DATA_STDERR,
  7431. data, length);
  7432. /*
  7433. * If it looks like the remote end hit the end of its window,
  7434. * and we didn't want it to do that, think about using a
  7435. * larger window.
  7436. */
  7437. if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
  7438. c->v.v2.locmaxwin < 0x40000000)
  7439. c->v.v2.locmaxwin += OUR_V2_WINSIZE;
  7440. /*
  7441. * If we are not buffering too much data,
  7442. * enlarge the window again at the remote side.
  7443. * If we are buffering too much, we may still
  7444. * need to adjust the window if the server's
  7445. * sent excess data.
  7446. */
  7447. if (bufsize < c->v.v2.locmaxwin)
  7448. ssh2_set_window(c, c->v.v2.locmaxwin - bufsize);
  7449. /*
  7450. * If we're either buffering way too much data, or if we're
  7451. * buffering anything at all and we're in "simple" mode,
  7452. * throttle the whole channel.
  7453. */
  7454. if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
  7455. && !c->throttling_conn) {
  7456. c->throttling_conn = 1;
  7457. ssh_throttle_conn(ssh, +1);
  7458. }
  7459. }
  7460. }
  7461. static void ssh_check_termination(Ssh ssh)
  7462. {
  7463. if (ssh->version == 2 &&
  7464. !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
  7465. (ssh->channels && count234(ssh->channels) == 0) &&
  7466. !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
  7467. /*
  7468. * We used to send SSH_MSG_DISCONNECT here, because I'd
  7469. * believed that _every_ conforming SSH-2 connection had to
  7470. * end with a disconnect being sent by at least one side;
  7471. * apparently I was wrong and it's perfectly OK to
  7472. * unceremoniously slam the connection shut when you're done,
  7473. * and indeed OpenSSH feels this is more polite than sending a
  7474. * DISCONNECT. So now we don't.
  7475. */
  7476. ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
  7477. }
  7478. }
  7479. void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
  7480. const char *peerinfo)
  7481. {
  7482. if (peerinfo)
  7483. logeventf(ssh, "Connection sharing downstream #%u connected from %s",
  7484. id, peerinfo);
  7485. else
  7486. logeventf(ssh, "Connection sharing downstream #%u connected", id);
  7487. }
  7488. void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
  7489. {
  7490. logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
  7491. ssh_check_termination(ssh);
  7492. }
  7493. void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
  7494. {
  7495. va_list ap;
  7496. char *buf;
  7497. va_start(ap, logfmt);
  7498. buf = dupvprintf(logfmt, ap);
  7499. va_end(ap);
  7500. if (id)
  7501. logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
  7502. else
  7503. logeventf(ssh, "Connection sharing: %s", buf);
  7504. sfree(buf);
  7505. }
  7506. /*
  7507. * Close any local socket and free any local resources associated with
  7508. * a channel. This converts the channel into a CHAN_ZOMBIE.
  7509. */
  7510. static void ssh_channel_close_local(struct ssh_channel *c, char const *reason)
  7511. {
  7512. Ssh ssh = c->ssh;
  7513. char const *msg = NULL;
  7514. switch (c->type) {
  7515. case CHAN_MAINSESSION:
  7516. ssh->mainchan = NULL;
  7517. update_specials_menu(ssh->frontend);
  7518. break;
  7519. case CHAN_X11:
  7520. assert(c->u.x11.xconn != NULL);
  7521. x11_close(c->u.x11.xconn);
  7522. msg = "Forwarded X11 connection terminated";
  7523. break;
  7524. case CHAN_AGENT:
  7525. if (c->u.a.pending)
  7526. agent_cancel_query(c->u.a.pending);
  7527. bufchain_clear(&c->u.a.inbuffer);
  7528. msg = "Agent-forwarding connection closed";
  7529. break;
  7530. case CHAN_SOCKDATA:
  7531. assert(c->u.pfd.pf != NULL);
  7532. pfd_close(c->u.pfd.pf);
  7533. msg = "Forwarded port closed";
  7534. break;
  7535. }
  7536. c->type = CHAN_ZOMBIE;
  7537. if (msg != NULL) {
  7538. if (reason != NULL)
  7539. logeventf(ssh, "%s %s", msg, reason);
  7540. else
  7541. logevent(msg);
  7542. }
  7543. }
  7544. static void ssh_channel_destroy(struct ssh_channel *c)
  7545. {
  7546. Ssh ssh = c->ssh;
  7547. ssh_channel_close_local(c, NULL);
  7548. del234(ssh->channels, c);
  7549. if (ssh->version == 2) {
  7550. bufchain_clear(&c->v.v2.outbuffer);
  7551. assert(c->v.v2.chanreq_head == NULL);
  7552. }
  7553. sfree(c);
  7554. /*
  7555. * If that was the last channel left open, we might need to
  7556. * terminate.
  7557. */
  7558. ssh_check_termination(ssh);
  7559. }
  7560. static void ssh2_channel_check_close(struct ssh_channel *c)
  7561. {
  7562. Ssh ssh = c->ssh;
  7563. struct Packet *pktout;
  7564. assert(ssh->version == 2);
  7565. if (c->halfopen) {
  7566. /*
  7567. * If we've sent out our own CHANNEL_OPEN but not yet seen
  7568. * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
  7569. * it's too early to be sending close messages of any kind.
  7570. */
  7571. return;
  7572. }
  7573. if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
  7574. c->type == CHAN_ZOMBIE) &&
  7575. !c->v.v2.chanreq_head &&
  7576. !(c->closes & CLOSES_SENT_CLOSE)) {
  7577. /*
  7578. * We have both sent and received EOF (or the channel is a
  7579. * zombie), and we have no outstanding channel requests, which
  7580. * means the channel is in final wind-up. But we haven't sent
  7581. * CLOSE, so let's do so now.
  7582. */
  7583. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
  7584. ssh2_pkt_adduint32(pktout, c->remoteid);
  7585. ssh2_pkt_send(ssh, pktout);
  7586. c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
  7587. }
  7588. if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
  7589. assert(c->v.v2.chanreq_head == NULL);
  7590. /*
  7591. * We have both sent and received CLOSE, which means we're
  7592. * completely done with the channel.
  7593. */
  7594. ssh_channel_destroy(c);
  7595. }
  7596. }
  7597. static void ssh_channel_got_eof(struct ssh_channel *c)
  7598. {
  7599. if (c->closes & CLOSES_RCVD_EOF)
  7600. return; /* already seen EOF */
  7601. c->closes |= CLOSES_RCVD_EOF;
  7602. if (c->type == CHAN_X11) {
  7603. assert(c->u.x11.xconn != NULL);
  7604. x11_send_eof(c->u.x11.xconn);
  7605. } else if (c->type == CHAN_AGENT) {
  7606. /* Just call try_forward, which will respond to the EOF now if
  7607. * appropriate, or wait until the queue of outstanding
  7608. * requests is dealt with if not */
  7609. ssh_agentf_try_forward(c);
  7610. } else if (c->type == CHAN_SOCKDATA) {
  7611. assert(c->u.pfd.pf != NULL);
  7612. pfd_send_eof(c->u.pfd.pf);
  7613. } else if (c->type == CHAN_MAINSESSION) {
  7614. Ssh ssh = c->ssh;
  7615. if (!ssh->sent_console_eof &&
  7616. (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
  7617. /*
  7618. * Either from_backend_eof told us that the front end
  7619. * wants us to close the outgoing side of the connection
  7620. * as soon as we see EOF from the far end, or else we've
  7621. * unilaterally decided to do that because we've allocated
  7622. * a remote pty and hence EOF isn't a particularly
  7623. * meaningful concept.
  7624. */
  7625. sshfwd_write_eof(c);
  7626. }
  7627. ssh->sent_console_eof = TRUE;
  7628. }
  7629. }
  7630. static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
  7631. {
  7632. struct ssh_channel *c;
  7633. c = ssh_channel_msg(ssh, pktin);
  7634. if (!c)
  7635. return;
  7636. ssh_channel_got_eof(c);
  7637. ssh2_channel_check_close(c);
  7638. }
  7639. static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
  7640. {
  7641. struct ssh_channel *c;
  7642. c = ssh_channel_msg(ssh, pktin);
  7643. if (!c)
  7644. return;
  7645. /*
  7646. * When we receive CLOSE on a channel, we assume it comes with an
  7647. * implied EOF if we haven't seen EOF yet.
  7648. */
  7649. ssh_channel_got_eof(c);
  7650. if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
  7651. /*
  7652. * It also means we stop expecting to see replies to any
  7653. * outstanding channel requests, so clean those up too.
  7654. * (ssh_chanreq_init will enforce by assertion that we don't
  7655. * subsequently put anything back on this list.)
  7656. */
  7657. while (c->v.v2.chanreq_head) {
  7658. struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
  7659. ocr->handler(c, NULL, ocr->ctx);
  7660. c->v.v2.chanreq_head = ocr->next;
  7661. sfree(ocr);
  7662. }
  7663. }
  7664. /*
  7665. * And we also send an outgoing EOF, if we haven't already, on the
  7666. * assumption that CLOSE is a pretty forceful announcement that
  7667. * the remote side is doing away with the entire channel. (If it
  7668. * had wanted to send us EOF and continue receiving data from us,
  7669. * it would have just sent CHANNEL_EOF.)
  7670. */
  7671. if (!(c->closes & CLOSES_SENT_EOF)) {
  7672. /*
  7673. * Make sure we don't read any more from whatever our local
  7674. * data source is for this channel.
  7675. */
  7676. switch (c->type) {
  7677. case CHAN_MAINSESSION:
  7678. ssh->send_ok = 0; /* stop trying to read from stdin */
  7679. break;
  7680. case CHAN_X11:
  7681. x11_override_throttle(c->u.x11.xconn, 1);
  7682. break;
  7683. case CHAN_SOCKDATA:
  7684. pfd_override_throttle(c->u.pfd.pf, 1);
  7685. break;
  7686. }
  7687. /*
  7688. * Abandon any buffered data we still wanted to send to this
  7689. * channel. Receiving a CHANNEL_CLOSE is an indication that
  7690. * the server really wants to get on and _destroy_ this
  7691. * channel, and it isn't going to send us any further
  7692. * WINDOW_ADJUSTs to permit us to send pending stuff.
  7693. */
  7694. bufchain_clear(&c->v.v2.outbuffer);
  7695. /*
  7696. * Send outgoing EOF.
  7697. */
  7698. sshfwd_write_eof(c);
  7699. }
  7700. /*
  7701. * Now process the actual close.
  7702. */
  7703. if (!(c->closes & CLOSES_RCVD_CLOSE)) {
  7704. c->closes |= CLOSES_RCVD_CLOSE;
  7705. ssh2_channel_check_close(c);
  7706. }
  7707. }
  7708. static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
  7709. {
  7710. struct ssh_channel *c;
  7711. c = ssh_channel_msg(ssh, pktin);
  7712. if (!c)
  7713. return;
  7714. assert(c->halfopen); /* ssh_channel_msg will have enforced this */
  7715. c->remoteid = ssh_pkt_getuint32(pktin);
  7716. c->halfopen = FALSE;
  7717. c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
  7718. c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
  7719. if (c->type == CHAN_SOCKDATA) {
  7720. assert(c->u.pfd.pf != NULL);
  7721. pfd_confirm(c->u.pfd.pf);
  7722. } else if (c->type == CHAN_ZOMBIE) {
  7723. /*
  7724. * This case can occur if a local socket error occurred
  7725. * between us sending out CHANNEL_OPEN and receiving
  7726. * OPEN_CONFIRMATION. In this case, all we can do is
  7727. * immediately initiate close proceedings now that we know the
  7728. * server's id to put in the close message.
  7729. */
  7730. ssh2_channel_check_close(c);
  7731. } else {
  7732. /*
  7733. * We never expect to receive OPEN_CONFIRMATION for any
  7734. * *other* channel type (since only local-to-remote port
  7735. * forwardings cause us to send CHANNEL_OPEN after the main
  7736. * channel is live - all other auxiliary channel types are
  7737. * initiated from the server end). It's safe to enforce this
  7738. * by assertion rather than by ssh_disconnect, because the
  7739. * real point is that we never constructed a half-open channel
  7740. * structure in the first place with any type other than the
  7741. * above.
  7742. */
  7743. assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
  7744. }
  7745. if (c->pending_eof)
  7746. ssh_channel_try_eof(c); /* in case we had a pending EOF */
  7747. }
  7748. static char *ssh2_channel_open_failure_error_text(struct Packet *pktin)
  7749. {
  7750. static const char *const reasons[] = {
  7751. NULL,
  7752. "Administratively prohibited",
  7753. "Connect failed",
  7754. "Unknown channel type",
  7755. "Resource shortage",
  7756. };
  7757. unsigned reason_code;
  7758. const char *reason_code_string;
  7759. char reason_code_buf[256];
  7760. char *reason_string;
  7761. int reason_length;
  7762. reason_code = ssh_pkt_getuint32(pktin);
  7763. if (reason_code < lenof(reasons) && reasons[reason_code]) {
  7764. reason_code_string = reasons[reason_code];
  7765. } else {
  7766. reason_code_string = reason_code_buf;
  7767. sprintf(reason_code_buf, "unknown reason code %#x", reason_code);
  7768. }
  7769. ssh_pkt_getstring(pktin, &reason_string, &reason_length);
  7770. return dupprintf("%s [%.*s]", reason_code_string,
  7771. reason_length, NULLTOEMPTY(reason_string));
  7772. }
  7773. static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
  7774. {
  7775. struct ssh_channel *c;
  7776. c = ssh_channel_msg(ssh, pktin);
  7777. if (!c)
  7778. return;
  7779. assert(c->halfopen); /* ssh_channel_msg will have enforced this */
  7780. if (c->type == CHAN_SOCKDATA) {
  7781. char *errtext = ssh2_channel_open_failure_error_text(pktin);
  7782. logeventf(ssh, "Forwarded connection refused by server: %s", errtext);
  7783. sfree(errtext);
  7784. pfd_close(c->u.pfd.pf);
  7785. } else if (c->type == CHAN_ZOMBIE) {
  7786. /*
  7787. * This case can occur if a local socket error occurred
  7788. * between us sending out CHANNEL_OPEN and receiving
  7789. * OPEN_FAILURE. In this case, we need do nothing except allow
  7790. * the code below to throw the half-open channel away.
  7791. */
  7792. } else {
  7793. /*
  7794. * We never expect to receive OPEN_FAILURE for any *other*
  7795. * channel type (since only local-to-remote port forwardings
  7796. * cause us to send CHANNEL_OPEN after the main channel is
  7797. * live - all other auxiliary channel types are initiated from
  7798. * the server end). It's safe to enforce this by assertion
  7799. * rather than by ssh_disconnect, because the real point is
  7800. * that we never constructed a half-open channel structure in
  7801. * the first place with any type other than the above.
  7802. */
  7803. assert(!"Funny channel type in ssh2_msg_channel_open_failure");
  7804. }
  7805. del234(ssh->channels, c);
  7806. sfree(c);
  7807. }
  7808. static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
  7809. {
  7810. char *type;
  7811. int typelen, want_reply;
  7812. int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
  7813. struct ssh_channel *c;
  7814. struct Packet *pktout;
  7815. c = ssh_channel_msg(ssh, pktin);
  7816. if (!c)
  7817. return;
  7818. ssh_pkt_getstring(pktin, &type, &typelen);
  7819. want_reply = ssh2_pkt_getbool(pktin);
  7820. if (c->closes & CLOSES_SENT_CLOSE) {
  7821. /*
  7822. * We don't reply to channel requests after we've sent
  7823. * CHANNEL_CLOSE for the channel, because our reply might
  7824. * cross in the network with the other side's CHANNEL_CLOSE
  7825. * and arrive after they have wound the channel up completely.
  7826. */
  7827. want_reply = FALSE;
  7828. }
  7829. /*
  7830. * Having got the channel number, we now look at
  7831. * the request type string to see if it's something
  7832. * we recognise.
  7833. */
  7834. if (c == ssh->mainchan) {
  7835. /*
  7836. * We recognise "exit-status" and "exit-signal" on
  7837. * the primary channel.
  7838. */
  7839. if (typelen == 11 &&
  7840. !memcmp(type, "exit-status", 11)) {
  7841. ssh->exitcode = ssh_pkt_getuint32(pktin);
  7842. logeventf(ssh, "Server sent command exit status %d",
  7843. ssh->exitcode);
  7844. reply = SSH2_MSG_CHANNEL_SUCCESS;
  7845. } else if (typelen == 11 &&
  7846. !memcmp(type, "exit-signal", 11)) {
  7847. int is_plausible = TRUE, is_int = FALSE;
  7848. char *fmt_sig = NULL, *fmt_msg = NULL;
  7849. char *msg;
  7850. int msglen = 0, core = FALSE;
  7851. /* ICK: older versions of OpenSSH (e.g. 3.4p1)
  7852. * provide an `int' for the signal, despite its
  7853. * having been a `string' in the drafts of RFC 4254 since at
  7854. * least 2001. (Fixed in session.c 1.147.) Try to
  7855. * infer which we can safely parse it as. */
  7856. {
  7857. unsigned char *p = pktin->body +
  7858. pktin->savedpos;
  7859. long len = pktin->length - pktin->savedpos;
  7860. unsigned long num = GET_32BIT(p); /* what is it? */
  7861. /* If it's 0, it hardly matters; assume string */
  7862. if (num == 0) {
  7863. is_int = FALSE;
  7864. } else {
  7865. int maybe_int = FALSE, maybe_str = FALSE;
  7866. #define CHECK_HYPOTHESIS(offset, result) \
  7867. do \
  7868. { \
  7869. int q = toint(offset); \
  7870. if (q >= 0 && q+4 <= len) { \
  7871. q = toint(q + 4 + GET_32BIT(p+q)); \
  7872. if (q >= 0 && q+4 <= len && \
  7873. ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
  7874. q == len) \
  7875. result = TRUE; \
  7876. } \
  7877. } while(0)
  7878. CHECK_HYPOTHESIS(4+1, maybe_int);
  7879. CHECK_HYPOTHESIS(4+num+1, maybe_str);
  7880. #undef CHECK_HYPOTHESIS
  7881. if (maybe_int && !maybe_str)
  7882. is_int = TRUE;
  7883. else if (!maybe_int && maybe_str)
  7884. is_int = FALSE;
  7885. else
  7886. /* Crikey. Either or neither. Panic. */
  7887. is_plausible = FALSE;
  7888. }
  7889. }
  7890. ssh->exitcode = 128; /* means `unknown signal' */
  7891. if (is_plausible) {
  7892. if (is_int) {
  7893. /* Old non-standard OpenSSH. */
  7894. int signum = ssh_pkt_getuint32(pktin);
  7895. fmt_sig = dupprintf(" %d", signum);
  7896. ssh->exitcode = 128 + signum;
  7897. } else {
  7898. /* As per RFC 4254. */
  7899. char *sig;
  7900. int siglen;
  7901. ssh_pkt_getstring(pktin, &sig, &siglen);
  7902. /* Signal name isn't supposed to be blank, but
  7903. * let's cope gracefully if it is. */
  7904. if (siglen) {
  7905. fmt_sig = dupprintf(" \"%.*s\"",
  7906. siglen, sig);
  7907. }
  7908. /*
  7909. * Really hideous method of translating the
  7910. * signal description back into a locally
  7911. * meaningful number.
  7912. */
  7913. if (0)
  7914. ;
  7915. #define TRANSLATE_SIGNAL(s) \
  7916. else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
  7917. ssh->exitcode = 128 + SIG ## s
  7918. #ifdef SIGABRT
  7919. TRANSLATE_SIGNAL(ABRT);
  7920. #endif
  7921. #ifdef SIGALRM
  7922. TRANSLATE_SIGNAL(ALRM);
  7923. #endif
  7924. #ifdef SIGFPE
  7925. TRANSLATE_SIGNAL(FPE);
  7926. #endif
  7927. #ifdef SIGHUP
  7928. TRANSLATE_SIGNAL(HUP);
  7929. #endif
  7930. #ifdef SIGILL
  7931. TRANSLATE_SIGNAL(ILL);
  7932. #endif
  7933. #ifdef SIGINT
  7934. TRANSLATE_SIGNAL(INT);
  7935. #endif
  7936. #ifdef SIGKILL
  7937. TRANSLATE_SIGNAL(KILL);
  7938. #endif
  7939. #ifdef SIGPIPE
  7940. TRANSLATE_SIGNAL(PIPE);
  7941. #endif
  7942. #ifdef SIGQUIT
  7943. TRANSLATE_SIGNAL(QUIT);
  7944. #endif
  7945. #ifdef SIGSEGV
  7946. TRANSLATE_SIGNAL(SEGV);
  7947. #endif
  7948. #ifdef SIGTERM
  7949. TRANSLATE_SIGNAL(TERM);
  7950. #endif
  7951. #ifdef SIGUSR1
  7952. TRANSLATE_SIGNAL(USR1);
  7953. #endif
  7954. #ifdef SIGUSR2
  7955. TRANSLATE_SIGNAL(USR2);
  7956. #endif
  7957. #undef TRANSLATE_SIGNAL
  7958. else
  7959. ssh->exitcode = 128;
  7960. }
  7961. core = ssh2_pkt_getbool(pktin);
  7962. ssh_pkt_getstring(pktin, &msg, &msglen);
  7963. if (msglen) {
  7964. fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
  7965. }
  7966. /* ignore lang tag */
  7967. } /* else don't attempt to parse */
  7968. logeventf(ssh, "Server exited on signal%s%s%s",
  7969. fmt_sig ? fmt_sig : "",
  7970. core ? " (core dumped)" : "",
  7971. fmt_msg ? fmt_msg : "");
  7972. sfree(fmt_sig);
  7973. sfree(fmt_msg);
  7974. reply = SSH2_MSG_CHANNEL_SUCCESS;
  7975. }
  7976. } else {
  7977. /*
  7978. * This is a channel request we don't know
  7979. * about, so we now either ignore the request
  7980. * or respond with CHANNEL_FAILURE, depending
  7981. * on want_reply.
  7982. */
  7983. reply = SSH2_MSG_CHANNEL_FAILURE;
  7984. }
  7985. if (want_reply) {
  7986. pktout = ssh2_pkt_init(reply);
  7987. ssh2_pkt_adduint32(pktout, c->remoteid);
  7988. ssh2_pkt_send(ssh, pktout);
  7989. }
  7990. }
  7991. static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
  7992. {
  7993. char *type;
  7994. int typelen, want_reply;
  7995. struct Packet *pktout;
  7996. ssh_pkt_getstring(pktin, &type, &typelen);
  7997. want_reply = ssh2_pkt_getbool(pktin);
  7998. /*
  7999. * We currently don't support any global requests
  8000. * at all, so we either ignore the request or
  8001. * respond with REQUEST_FAILURE, depending on
  8002. * want_reply.
  8003. */
  8004. if (want_reply) {
  8005. pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
  8006. ssh2_pkt_send(ssh, pktout);
  8007. }
  8008. }
  8009. struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
  8010. void *share_cs,
  8011. void *share_chan)
  8012. {
  8013. struct X11FakeAuth *auth;
  8014. /*
  8015. * Make up a new set of fake X11 auth data, and add it to the tree
  8016. * of currently valid ones with an indication of the sharing
  8017. * context that it's relevant to.
  8018. */
  8019. auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
  8020. auth->share_cs = share_cs;
  8021. auth->share_chan = share_chan;
  8022. return auth;
  8023. }
  8024. void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
  8025. {
  8026. del234(ssh->x11authtree, auth);
  8027. x11_free_fake_auth(auth);
  8028. }
  8029. static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
  8030. {
  8031. char *type;
  8032. int typelen;
  8033. char *peeraddr;
  8034. int peeraddrlen;
  8035. int peerport;
  8036. const char *error = NULL;
  8037. struct ssh_channel *c;
  8038. unsigned remid, winsize, pktsize;
  8039. unsigned our_winsize_override = 0;
  8040. struct Packet *pktout;
  8041. ssh_pkt_getstring(pktin, &type, &typelen);
  8042. c = snew(struct ssh_channel);
  8043. c->ssh = ssh;
  8044. remid = ssh_pkt_getuint32(pktin);
  8045. winsize = ssh_pkt_getuint32(pktin);
  8046. pktsize = ssh_pkt_getuint32(pktin);
  8047. if (typelen == 3 && !memcmp(type, "x11", 3)) {
  8048. char *addrstr;
  8049. ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
  8050. addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
  8051. peerport = ssh_pkt_getuint32(pktin);
  8052. logeventf(ssh, "Received X11 connect request from %s:%d",
  8053. addrstr, peerport);
  8054. if (!ssh->X11_fwd_enabled && !ssh->connshare)
  8055. error = "X11 forwarding is not enabled";
  8056. else {
  8057. c->u.x11.xconn = x11_init(ssh->x11authtree, c,
  8058. addrstr, peerport);
  8059. c->type = CHAN_X11;
  8060. c->u.x11.initial = TRUE;
  8061. /*
  8062. * If we are a connection-sharing upstream, then we should
  8063. * initially present a very small window, adequate to take
  8064. * the X11 initial authorisation packet but not much more.
  8065. * Downstream will then present us a larger window (by
  8066. * fiat of the connection-sharing protocol) and we can
  8067. * guarantee to send a positive-valued WINDOW_ADJUST.
  8068. */
  8069. if (ssh->connshare)
  8070. our_winsize_override = 128;
  8071. logevent("Opened X11 forward channel");
  8072. }
  8073. sfree(addrstr);
  8074. } else if (typelen == 15 &&
  8075. !memcmp(type, "forwarded-tcpip", 15)) {
  8076. struct ssh_rportfwd pf, *realpf;
  8077. char *shost;
  8078. int shostlen;
  8079. ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
  8080. pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
  8081. pf.sport = ssh_pkt_getuint32(pktin);
  8082. ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
  8083. peerport = ssh_pkt_getuint32(pktin);
  8084. realpf = find234(ssh->rportfwds, &pf, NULL);
  8085. logeventf(ssh, "Received remote port %s:%d open request "
  8086. "from %.*s:%d", pf.shost, pf.sport,
  8087. peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
  8088. sfree(pf.shost);
  8089. if (realpf == NULL) {
  8090. error = "Remote port is not recognised";
  8091. } else {
  8092. char *err;
  8093. if (realpf->share_ctx) {
  8094. /*
  8095. * This port forwarding is on behalf of a
  8096. * connection-sharing downstream, so abandon our own
  8097. * channel-open procedure and just pass the message on
  8098. * to sshshare.c.
  8099. */
  8100. share_got_pkt_from_server(realpf->share_ctx, pktin->type,
  8101. pktin->body, pktin->length);
  8102. sfree(c);
  8103. return;
  8104. }
  8105. err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
  8106. c, ssh->conf, realpf->pfrec->addressfamily);
  8107. logeventf(ssh, "Attempting to forward remote port to "
  8108. "%s:%d", realpf->dhost, realpf->dport);
  8109. if (err != NULL) {
  8110. logeventf(ssh, "Port open failed: %s", err);
  8111. sfree(err);
  8112. error = "Port open failed";
  8113. } else {
  8114. logevent("Forwarded port opened successfully");
  8115. c->type = CHAN_SOCKDATA;
  8116. }
  8117. }
  8118. } else if (typelen == 22 &&
  8119. !memcmp(type, "[email protected]", 22)) {
  8120. if (!ssh->agentfwd_enabled)
  8121. error = "Agent forwarding is not enabled";
  8122. else {
  8123. c->type = CHAN_AGENT; /* identify channel type */
  8124. bufchain_init(&c->u.a.inbuffer);
  8125. c->u.a.pending = NULL;
  8126. }
  8127. } else {
  8128. error = "Unsupported channel type requested";
  8129. }
  8130. c->remoteid = remid;
  8131. c->halfopen = FALSE;
  8132. if (error) {
  8133. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
  8134. ssh2_pkt_adduint32(pktout, c->remoteid);
  8135. ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
  8136. ssh2_pkt_addstring(pktout, error);
  8137. ssh2_pkt_addstring(pktout, "en"); /* language tag */
  8138. ssh2_pkt_send(ssh, pktout);
  8139. logeventf(ssh, "Rejected channel open: %s", error);
  8140. sfree(c);
  8141. } else {
  8142. ssh_channel_init(c);
  8143. c->v.v2.remwindow = winsize;
  8144. c->v.v2.remmaxpkt = pktsize;
  8145. if (our_winsize_override) {
  8146. c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
  8147. our_winsize_override;
  8148. }
  8149. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
  8150. ssh2_pkt_adduint32(pktout, c->remoteid);
  8151. ssh2_pkt_adduint32(pktout, c->localid);
  8152. ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
  8153. ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
  8154. ssh2_pkt_send(ssh, pktout);
  8155. }
  8156. }
  8157. void sshfwd_x11_sharing_handover(struct ssh_channel *c,
  8158. void *share_cs, void *share_chan,
  8159. const char *peer_addr, int peer_port,
  8160. int endian, int protomajor, int protominor,
  8161. const void *initial_data, int initial_len)
  8162. {
  8163. /*
  8164. * This function is called when we've just discovered that an X
  8165. * forwarding channel on which we'd been handling the initial auth
  8166. * ourselves turns out to be destined for a connection-sharing
  8167. * downstream. So we turn the channel into a CHAN_SHARING, meaning
  8168. * that we completely stop tracking windows and buffering data and
  8169. * just pass more or less unmodified SSH messages back and forth.
  8170. */
  8171. c->type = CHAN_SHARING;
  8172. c->u.sharing.ctx = share_cs;
  8173. share_setup_x11_channel(share_cs, share_chan,
  8174. c->localid, c->remoteid, c->v.v2.remwindow,
  8175. c->v.v2.remmaxpkt, c->v.v2.locwindow,
  8176. peer_addr, peer_port, endian,
  8177. protomajor, protominor,
  8178. initial_data, initial_len);
  8179. }
  8180. void sshfwd_x11_is_local(struct ssh_channel *c)
  8181. {
  8182. /*
  8183. * This function is called when we've just discovered that an X
  8184. * forwarding channel is _not_ destined for a connection-sharing
  8185. * downstream but we're going to handle it ourselves. We stop
  8186. * presenting a cautiously small window and go into ordinary data
  8187. * exchange mode.
  8188. */
  8189. c->u.x11.initial = FALSE;
  8190. ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
  8191. }
  8192. /*
  8193. * Buffer banner messages for later display at some convenient point,
  8194. * if we're going to display them.
  8195. */
  8196. static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
  8197. {
  8198. /* Arbitrary limit to prevent unbounded inflation of buffer */
  8199. if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
  8200. bufchain_size(&ssh->banner) <= 131072) {
  8201. char *banner = NULL;
  8202. int size = 0;
  8203. ssh_pkt_getstring(pktin, &banner, &size);
  8204. if (banner)
  8205. bufchain_add(&ssh->banner, banner, size);
  8206. }
  8207. }
  8208. /* Helper function to deal with sending tty modes for "pty-req" */
  8209. static void ssh2_send_ttymode(void *data,
  8210. const struct ssh_ttymode *mode, char *val)
  8211. {
  8212. struct Packet *pktout = (struct Packet *)data;
  8213. unsigned int arg = 0;
  8214. switch (mode->type) {
  8215. case TTY_OP_CHAR:
  8216. arg = ssh_tty_parse_specchar(val);
  8217. break;
  8218. case TTY_OP_BOOL:
  8219. arg = ssh_tty_parse_boolean(val);
  8220. break;
  8221. }
  8222. ssh2_pkt_addbyte(pktout, mode->opcode);
  8223. ssh2_pkt_adduint32(pktout, arg);
  8224. }
  8225. static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
  8226. void *ctx)
  8227. {
  8228. struct ssh2_setup_x11_state {
  8229. int crLine;
  8230. };
  8231. Ssh ssh = c->ssh;
  8232. struct Packet *pktout;
  8233. crStateP(ssh2_setup_x11_state, ctx);
  8234. crBeginState;
  8235. logevent("Requesting X11 forwarding");
  8236. pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
  8237. ssh2_setup_x11, s);
  8238. ssh2_pkt_addbool(pktout, 0); /* many connections */
  8239. ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
  8240. ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
  8241. ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
  8242. ssh2_pkt_send(ssh, pktout);
  8243. /* Wait to be called back with either a response packet, or NULL
  8244. * meaning clean up and free our data */
  8245. crReturnV;
  8246. if (pktin) {
  8247. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
  8248. logevent("X11 forwarding enabled");
  8249. ssh->X11_fwd_enabled = TRUE;
  8250. } else
  8251. logevent("X11 forwarding refused");
  8252. }
  8253. crFinishFreeV;
  8254. }
  8255. static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
  8256. void *ctx)
  8257. {
  8258. struct ssh2_setup_agent_state {
  8259. int crLine;
  8260. };
  8261. Ssh ssh = c->ssh;
  8262. struct Packet *pktout;
  8263. crStateP(ssh2_setup_agent_state, ctx);
  8264. crBeginState;
  8265. logevent("Requesting OpenSSH-style agent forwarding");
  8266. pktout = ssh2_chanreq_init(ssh->mainchan, "[email protected]",
  8267. ssh2_setup_agent, s);
  8268. ssh2_pkt_send(ssh, pktout);
  8269. /* Wait to be called back with either a response packet, or NULL
  8270. * meaning clean up and free our data */
  8271. crReturnV;
  8272. if (pktin) {
  8273. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
  8274. logevent("Agent forwarding enabled");
  8275. ssh->agentfwd_enabled = TRUE;
  8276. } else
  8277. logevent("Agent forwarding refused");
  8278. }
  8279. crFinishFreeV;
  8280. }
  8281. static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
  8282. void *ctx)
  8283. {
  8284. struct ssh2_setup_pty_state {
  8285. int crLine;
  8286. };
  8287. Ssh ssh = c->ssh;
  8288. struct Packet *pktout;
  8289. crStateP(ssh2_setup_pty_state, ctx);
  8290. crBeginState;
  8291. /* Unpick the terminal-speed string. */
  8292. /* XXX perhaps we should allow no speeds to be sent. */
  8293. ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
  8294. sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
  8295. /* Build the pty request. */
  8296. pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
  8297. ssh2_setup_pty, s);
  8298. ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
  8299. ssh2_pkt_adduint32(pktout, ssh->term_width);
  8300. ssh2_pkt_adduint32(pktout, ssh->term_height);
  8301. ssh2_pkt_adduint32(pktout, 0); /* pixel width */
  8302. ssh2_pkt_adduint32(pktout, 0); /* pixel height */
  8303. ssh2_pkt_addstring_start(pktout);
  8304. parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
  8305. ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
  8306. ssh2_pkt_adduint32(pktout, ssh->ispeed);
  8307. ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
  8308. ssh2_pkt_adduint32(pktout, ssh->ospeed);
  8309. ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
  8310. ssh2_pkt_send(ssh, pktout);
  8311. ssh->state = SSH_STATE_INTERMED;
  8312. /* Wait to be called back with either a response packet, or NULL
  8313. * meaning clean up and free our data */
  8314. crReturnV;
  8315. if (pktin) {
  8316. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
  8317. logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
  8318. ssh->ospeed, ssh->ispeed);
  8319. ssh->got_pty = TRUE;
  8320. } else {
  8321. c_write_str(ssh, "Server refused to allocate pty\r\n");
  8322. ssh->editing = ssh->echoing = 1;
  8323. }
  8324. }
  8325. crFinishFreeV;
  8326. }
  8327. static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
  8328. void *ctx)
  8329. {
  8330. struct ssh2_setup_env_state {
  8331. int crLine;
  8332. int num_env, env_left, env_ok;
  8333. };
  8334. Ssh ssh = c->ssh;
  8335. struct Packet *pktout;
  8336. crStateP(ssh2_setup_env_state, ctx);
  8337. crBeginState;
  8338. /*
  8339. * Send environment variables.
  8340. *
  8341. * Simplest thing here is to send all the requests at once, and
  8342. * then wait for a whole bunch of successes or failures.
  8343. */
  8344. s->num_env = 0;
  8345. {
  8346. char *key, *val;
  8347. for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
  8348. val != NULL;
  8349. val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
  8350. pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
  8351. ssh2_pkt_addstring(pktout, key);
  8352. ssh2_pkt_addstring(pktout, val);
  8353. ssh2_pkt_send(ssh, pktout);
  8354. s->num_env++;
  8355. }
  8356. if (s->num_env)
  8357. logeventf(ssh, "Sent %d environment variables", s->num_env);
  8358. }
  8359. if (s->num_env) {
  8360. s->env_ok = 0;
  8361. s->env_left = s->num_env;
  8362. while (s->env_left > 0) {
  8363. /* Wait to be called back with either a response packet,
  8364. * or NULL meaning clean up and free our data */
  8365. crReturnV;
  8366. if (!pktin) goto out;
  8367. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
  8368. s->env_ok++;
  8369. s->env_left--;
  8370. }
  8371. if (s->env_ok == s->num_env) {
  8372. logevent("All environment variables successfully set");
  8373. } else if (s->env_ok == 0) {
  8374. logevent("All environment variables refused");
  8375. c_write_str(ssh, "Server refused to set environment variables\r\n");
  8376. } else {
  8377. logeventf(ssh, "%d environment variables refused",
  8378. s->num_env - s->env_ok);
  8379. c_write_str(ssh, "Server refused to set all environment variables\r\n");
  8380. }
  8381. }
  8382. out:;
  8383. crFinishFreeV;
  8384. }
  8385. /*
  8386. * Handle the SSH-2 userauth and connection layers.
  8387. */
  8388. static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
  8389. {
  8390. do_ssh2_authconn(ssh, NULL, 0, pktin);
  8391. }
  8392. static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
  8393. void *ctx)
  8394. {
  8395. if (pktin)
  8396. do_ssh2_authconn(c->ssh, NULL, 0, pktin);
  8397. }
  8398. static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
  8399. struct Packet *pktin)
  8400. {
  8401. struct do_ssh2_authconn_state {
  8402. int crLine;
  8403. enum {
  8404. AUTH_TYPE_NONE,
  8405. AUTH_TYPE_PUBLICKEY,
  8406. AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
  8407. AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
  8408. AUTH_TYPE_PASSWORD,
  8409. AUTH_TYPE_GSSAPI, /* always QUIET */
  8410. AUTH_TYPE_KEYBOARD_INTERACTIVE,
  8411. AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
  8412. } type;
  8413. int done_service_req;
  8414. int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
  8415. int tried_pubkey_config, done_agent;
  8416. #ifndef NO_GSSAPI
  8417. int can_gssapi;
  8418. int tried_gssapi;
  8419. #endif
  8420. int kbd_inter_refused;
  8421. int we_are_in, userauth_success;
  8422. prompts_t *cur_prompt;
  8423. #ifdef MPEXT
  8424. int change_password;
  8425. #endif
  8426. int num_prompts;
  8427. char *username;
  8428. char *password;
  8429. int got_username;
  8430. void *publickey_blob;
  8431. int publickey_bloblen;
  8432. int privatekey_available, privatekey_encrypted;
  8433. char *publickey_algorithm;
  8434. char *publickey_comment;
  8435. unsigned char agent_request[5], *agent_response, *agentp;
  8436. int agent_responselen;
  8437. unsigned char *pkblob_in_agent;
  8438. int keyi, nkeys;
  8439. char *pkblob, *alg, *commentp;
  8440. int pklen, alglen, commentlen;
  8441. int siglen, retlen, len;
  8442. char *q, *agentreq, *ret;
  8443. struct Packet *pktout;
  8444. Filename *keyfile;
  8445. #ifndef NO_GSSAPI
  8446. struct ssh_gss_library *gsslib;
  8447. Ssh_gss_ctx gss_ctx;
  8448. Ssh_gss_buf gss_buf;
  8449. Ssh_gss_buf gss_rcvtok, gss_sndtok;
  8450. Ssh_gss_name gss_srv_name;
  8451. Ssh_gss_stat gss_stat;
  8452. #endif
  8453. };
  8454. crState(do_ssh2_authconn_state);
  8455. crBeginState;
  8456. /* Register as a handler for all the messages this coroutine handles. */
  8457. ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
  8458. ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
  8459. ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
  8460. ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
  8461. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
  8462. ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
  8463. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
  8464. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
  8465. ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
  8466. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
  8467. ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
  8468. ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
  8469. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
  8470. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
  8471. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
  8472. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
  8473. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
  8474. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
  8475. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
  8476. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
  8477. s->done_service_req = FALSE;
  8478. s->we_are_in = s->userauth_success = FALSE;
  8479. s->agent_response = NULL;
  8480. #ifndef NO_GSSAPI
  8481. s->tried_gssapi = FALSE;
  8482. #endif
  8483. if (!ssh->bare_connection) {
  8484. if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
  8485. /*
  8486. * Request userauth protocol, and await a response to it.
  8487. */
  8488. s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
  8489. ssh2_pkt_addstring(s->pktout, "ssh-userauth");
  8490. ssh2_pkt_send(ssh, s->pktout);
  8491. crWaitUntilV(pktin);
  8492. if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
  8493. s->done_service_req = TRUE;
  8494. }
  8495. if (!s->done_service_req) {
  8496. /*
  8497. * Request connection protocol directly, without authentication.
  8498. */
  8499. s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
  8500. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  8501. ssh2_pkt_send(ssh, s->pktout);
  8502. crWaitUntilV(pktin);
  8503. if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
  8504. s->we_are_in = TRUE; /* no auth required */
  8505. } else {
  8506. bombout(("Server refused service request"));
  8507. crStopV;
  8508. }
  8509. }
  8510. } else {
  8511. s->we_are_in = TRUE;
  8512. }
  8513. /* Arrange to be able to deal with any BANNERs that come in.
  8514. * (We do this now as packets may come in during the next bit.) */
  8515. bufchain_init(&ssh->banner);
  8516. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
  8517. ssh2_msg_userauth_banner;
  8518. /*
  8519. * Misc one-time setup for authentication.
  8520. */
  8521. s->publickey_blob = NULL;
  8522. if (!s->we_are_in) {
  8523. /*
  8524. * Load the public half of any configured public key file
  8525. * for later use.
  8526. */
  8527. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  8528. if (!filename_is_null(s->keyfile)) {
  8529. int keytype;
  8530. #ifdef _DEBUG
  8531. // To suppress CodeGuard warning
  8532. logeventf(ssh, MPEXT_BOM "Reading key file \"%s\"",
  8533. filename_to_str(s->keyfile));
  8534. #else
  8535. logeventf(ssh, MPEXT_BOM "Reading key file \"%.150s\"",
  8536. filename_to_str(s->keyfile));
  8537. #endif
  8538. keytype = key_type(s->keyfile);
  8539. if (keytype == SSH_KEYTYPE_SSH2 ||
  8540. keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
  8541. keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  8542. const char *error;
  8543. s->publickey_blob =
  8544. ssh2_userkey_loadpub(s->keyfile,
  8545. &s->publickey_algorithm,
  8546. &s->publickey_bloblen,
  8547. &s->publickey_comment, &error);
  8548. if (s->publickey_blob) {
  8549. s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
  8550. if (!s->privatekey_available)
  8551. logeventf(ssh, "Key file contains public key only");
  8552. s->privatekey_encrypted =
  8553. ssh2_userkey_encrypted(s->keyfile, NULL);
  8554. } else {
  8555. char *msgbuf;
  8556. logeventf(ssh, "Unable to load key (%s)",
  8557. error);
  8558. msgbuf = dupprintf(MPEXT_BOM "Unable to load key file "
  8559. "\"%.150s\" (%s)\r\n",
  8560. filename_to_str(s->keyfile),
  8561. error);
  8562. c_write_str(ssh, msgbuf);
  8563. sfree(msgbuf);
  8564. }
  8565. } else {
  8566. char *msgbuf;
  8567. logeventf(ssh, "Unable to use this key file (%s)",
  8568. key_type_to_str(keytype));
  8569. msgbuf = dupprintf(MPEXT_BOM "Unable to use key file \"%.150s\""
  8570. " (%s)\r\n",
  8571. filename_to_str(s->keyfile),
  8572. key_type_to_str(keytype));
  8573. c_write_str(ssh, msgbuf);
  8574. sfree(msgbuf);
  8575. s->publickey_blob = NULL;
  8576. }
  8577. }
  8578. /*
  8579. * Find out about any keys Pageant has (but if there's a
  8580. * public key configured, filter out all others).
  8581. */
  8582. s->nkeys = 0;
  8583. s->agent_response = NULL;
  8584. s->pkblob_in_agent = NULL;
  8585. if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
  8586. void *r;
  8587. logevent("Pageant is running. Requesting keys.");
  8588. /* Request the keys held by the agent. */
  8589. PUT_32BIT(s->agent_request, 1);
  8590. s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
  8591. ssh->auth_agent_query = agent_query(
  8592. s->agent_request, 5, &r, &s->agent_responselen,
  8593. ssh_agent_callback, ssh);
  8594. if (ssh->auth_agent_query) {
  8595. do {
  8596. crReturnV;
  8597. if (pktin) {
  8598. bombout(("Unexpected data from server while"
  8599. " waiting for agent response"));
  8600. crStopV;
  8601. }
  8602. } while (pktin || inlen > 0);
  8603. r = ssh->agent_response;
  8604. s->agent_responselen = ssh->agent_response_len;
  8605. }
  8606. s->agent_response = (unsigned char *) r;
  8607. if (s->agent_response && s->agent_responselen >= 5 &&
  8608. s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
  8609. int keyi;
  8610. unsigned char *p;
  8611. p = s->agent_response + 5;
  8612. s->nkeys = toint(GET_32BIT(p));
  8613. /*
  8614. * Vet the Pageant response to ensure that the key
  8615. * count and blob lengths make sense.
  8616. */
  8617. if (s->nkeys < 0) {
  8618. logeventf(ssh, "Pageant response contained a negative"
  8619. " key count %d", s->nkeys);
  8620. s->nkeys = 0;
  8621. goto done_agent_query;
  8622. } else {
  8623. unsigned char *q = p + 4;
  8624. int lenleft = s->agent_responselen - 5 - 4;
  8625. for (keyi = 0; keyi < s->nkeys; keyi++) {
  8626. int bloblen, commentlen;
  8627. if (lenleft < 4) {
  8628. logeventf(ssh, "Pageant response was truncated");
  8629. s->nkeys = 0;
  8630. goto done_agent_query;
  8631. }
  8632. bloblen = toint(GET_32BIT(q));
  8633. lenleft -= 4;
  8634. q += 4;
  8635. if (bloblen < 0 || bloblen > lenleft) {
  8636. logeventf(ssh, "Pageant response was truncated");
  8637. s->nkeys = 0;
  8638. goto done_agent_query;
  8639. }
  8640. lenleft -= bloblen;
  8641. q += bloblen;
  8642. commentlen = toint(GET_32BIT(q));
  8643. lenleft -= 4;
  8644. q += 4;
  8645. if (commentlen < 0 || commentlen > lenleft) {
  8646. logeventf(ssh, "Pageant response was truncated");
  8647. s->nkeys = 0;
  8648. goto done_agent_query;
  8649. }
  8650. lenleft -= commentlen;
  8651. q += commentlen;
  8652. }
  8653. }
  8654. p += 4;
  8655. logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
  8656. if (s->publickey_blob) {
  8657. /* See if configured key is in agent. */
  8658. for (keyi = 0; keyi < s->nkeys; keyi++) {
  8659. s->pklen = toint(GET_32BIT(p));
  8660. if (s->pklen == s->publickey_bloblen &&
  8661. !memcmp(p+4, s->publickey_blob,
  8662. s->publickey_bloblen)) {
  8663. logeventf(ssh, "Pageant key #%d matches "
  8664. "configured key file", keyi);
  8665. s->keyi = keyi;
  8666. s->pkblob_in_agent = p;
  8667. break;
  8668. }
  8669. p += 4 + s->pklen;
  8670. p += toint(GET_32BIT(p)) + 4; /* comment */
  8671. }
  8672. if (!s->pkblob_in_agent) {
  8673. logevent("Configured key file not in Pageant");
  8674. s->nkeys = 0;
  8675. }
  8676. }
  8677. } else {
  8678. logevent("Failed to get reply from Pageant");
  8679. }
  8680. done_agent_query:;
  8681. }
  8682. }
  8683. /*
  8684. * We repeat this whole loop, including the username prompt,
  8685. * until we manage a successful authentication. If the user
  8686. * types the wrong _password_, they can be sent back to the
  8687. * beginning to try another username, if this is configured on.
  8688. * (If they specify a username in the config, they are never
  8689. * asked, even if they do give a wrong password.)
  8690. *
  8691. * I think this best serves the needs of
  8692. *
  8693. * - the people who have no configuration, no keys, and just
  8694. * want to try repeated (username,password) pairs until they
  8695. * type both correctly
  8696. *
  8697. * - people who have keys and configuration but occasionally
  8698. * need to fall back to passwords
  8699. *
  8700. * - people with a key held in Pageant, who might not have
  8701. * logged in to a particular machine before; so they want to
  8702. * type a username, and then _either_ their key will be
  8703. * accepted, _or_ they will type a password. If they mistype
  8704. * the username they will want to be able to get back and
  8705. * retype it!
  8706. */
  8707. s->got_username = FALSE;
  8708. while (!s->we_are_in) {
  8709. /*
  8710. * Get a username.
  8711. */
  8712. if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
  8713. /*
  8714. * We got a username last time round this loop, and
  8715. * with change_username turned off we don't try to get
  8716. * it again.
  8717. */
  8718. } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
  8719. int ret; /* need not be kept over crReturn */
  8720. s->cur_prompt = new_prompts(ssh->frontend);
  8721. s->cur_prompt->to_server = TRUE;
  8722. s->cur_prompt->name = dupstr("SSH login name");
  8723. add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
  8724. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  8725. while (ret < 0) {
  8726. ssh->send_ok = 1;
  8727. crWaitUntilV(!pktin);
  8728. ret = get_userpass_input(s->cur_prompt, in, inlen);
  8729. ssh->send_ok = 0;
  8730. }
  8731. if (!ret) {
  8732. /*
  8733. * get_userpass_input() failed to get a username.
  8734. * Terminate.
  8735. */
  8736. free_prompts(s->cur_prompt);
  8737. ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
  8738. crStopV;
  8739. }
  8740. ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
  8741. free_prompts(s->cur_prompt);
  8742. } else {
  8743. char *stuff;
  8744. if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
  8745. stuff = dupprintf(MPEXT_BOM "Using username \"%s\".\r\n", ssh->username);
  8746. c_write_str(ssh, stuff);
  8747. sfree(stuff);
  8748. }
  8749. }
  8750. s->got_username = TRUE;
  8751. /*
  8752. * Send an authentication request using method "none": (a)
  8753. * just in case it succeeds, and (b) so that we know what
  8754. * authentication methods we can usefully try next.
  8755. */
  8756. ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
  8757. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  8758. ssh2_pkt_addstring(s->pktout, ssh->username);
  8759. ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
  8760. ssh2_pkt_addstring(s->pktout, "none"); /* method */
  8761. ssh2_pkt_send(ssh, s->pktout);
  8762. s->type = AUTH_TYPE_NONE;
  8763. s->gotit = FALSE;
  8764. s->we_are_in = FALSE;
  8765. s->tried_pubkey_config = FALSE;
  8766. s->kbd_inter_refused = FALSE;
  8767. /* Reset agent request state. */
  8768. s->done_agent = FALSE;
  8769. if (s->agent_response) {
  8770. if (s->pkblob_in_agent) {
  8771. s->agentp = s->pkblob_in_agent;
  8772. } else {
  8773. s->agentp = s->agent_response + 5 + 4;
  8774. s->keyi = 0;
  8775. }
  8776. }
  8777. while (1) {
  8778. char *methods = NULL;
  8779. int methlen = 0;
  8780. /*
  8781. * Wait for the result of the last authentication request.
  8782. */
  8783. if (!s->gotit)
  8784. crWaitUntilV(pktin);
  8785. /*
  8786. * Now is a convenient point to spew any banner material
  8787. * that we've accumulated. (This should ensure that when
  8788. * we exit the auth loop, we haven't any left to deal
  8789. * with.)
  8790. */
  8791. {
  8792. int size = bufchain_size(&ssh->banner);
  8793. /*
  8794. * Don't show the banner if we're operating in
  8795. * non-verbose non-interactive mode. (It's probably
  8796. * a script, which means nobody will read the
  8797. * banner _anyway_, and moreover the printing of
  8798. * the banner will screw up processing on the
  8799. * output of (say) plink.)
  8800. */
  8801. if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
  8802. char *banner = snewn(size, char);
  8803. bufchain_fetch(&ssh->banner, banner, size);
  8804. #ifdef MPEXT
  8805. display_banner(ssh->frontend, banner, size);
  8806. #endif
  8807. c_write_untrusted(ssh, banner, size);
  8808. sfree(banner);
  8809. }
  8810. bufchain_clear(&ssh->banner);
  8811. }
  8812. if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
  8813. logevent("Access granted");
  8814. s->we_are_in = s->userauth_success = TRUE;
  8815. break;
  8816. }
  8817. if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
  8818. bombout(("Strange packet received during authentication: "
  8819. "type %d", pktin->type));
  8820. crStopV;
  8821. }
  8822. s->gotit = FALSE;
  8823. /*
  8824. * OK, we're now sitting on a USERAUTH_FAILURE message, so
  8825. * we can look at the string in it and know what we can
  8826. * helpfully try next.
  8827. */
  8828. if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
  8829. ssh_pkt_getstring(pktin, &methods, &methlen);
  8830. if (!ssh2_pkt_getbool(pktin)) {
  8831. /*
  8832. * We have received an unequivocal Access
  8833. * Denied. This can translate to a variety of
  8834. * messages, or no message at all.
  8835. *
  8836. * For forms of authentication which are attempted
  8837. * implicitly, by which I mean without printing
  8838. * anything in the window indicating that we're
  8839. * trying them, we should never print 'Access
  8840. * denied'.
  8841. *
  8842. * If we do print a message saying that we're
  8843. * attempting some kind of authentication, it's OK
  8844. * to print a followup message saying it failed -
  8845. * but the message may sometimes be more specific
  8846. * than simply 'Access denied'.
  8847. *
  8848. * Additionally, if we'd just tried password
  8849. * authentication, we should break out of this
  8850. * whole loop so as to go back to the username
  8851. * prompt (iff we're configured to allow
  8852. * username change attempts).
  8853. */
  8854. if (s->type == AUTH_TYPE_NONE) {
  8855. /* do nothing */
  8856. } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
  8857. s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
  8858. if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
  8859. c_write_str(ssh, "Server refused our key\r\n");
  8860. logevent("Server refused our key");
  8861. } else if (s->type == AUTH_TYPE_PUBLICKEY) {
  8862. /* This _shouldn't_ happen except by a
  8863. * protocol bug causing client and server to
  8864. * disagree on what is a correct signature. */
  8865. c_write_str(ssh, "Server refused public-key signature"
  8866. " despite accepting key!\r\n");
  8867. logevent("Server refused public-key signature"
  8868. " despite accepting key!");
  8869. } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
  8870. /* quiet, so no c_write */
  8871. logevent("Server refused keyboard-interactive authentication");
  8872. } else if (s->type==AUTH_TYPE_GSSAPI) {
  8873. /* always quiet, so no c_write */
  8874. /* also, the code down in the GSSAPI block has
  8875. * already logged this in the Event Log */
  8876. } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
  8877. logevent("Keyboard-interactive authentication failed");
  8878. c_write_str(ssh, "Access denied\r\n");
  8879. } else {
  8880. assert(s->type == AUTH_TYPE_PASSWORD);
  8881. logevent("Password authentication failed");
  8882. c_write_str(ssh, "Access denied\r\n");
  8883. if (conf_get_int(ssh->conf, CONF_change_username)) {
  8884. /* XXX perhaps we should allow
  8885. * keyboard-interactive to do this too? */
  8886. s->we_are_in = FALSE;
  8887. break;
  8888. }
  8889. }
  8890. } else {
  8891. c_write_str(ssh, "Further authentication required\r\n");
  8892. logevent("Further authentication required");
  8893. }
  8894. #ifdef MPEXT
  8895. logeventf(ssh, "Server offered these authentication methods: %s", methods);
  8896. #endif
  8897. s->can_pubkey =
  8898. in_commasep_string("publickey", methods, methlen);
  8899. s->can_passwd =
  8900. in_commasep_string("password", methods, methlen);
  8901. s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
  8902. in_commasep_string("keyboard-interactive", methods, methlen);
  8903. #ifndef NO_GSSAPI
  8904. if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
  8905. in_commasep_string("gssapi-with-mic", methods, methlen)) {
  8906. /* Try loading the GSS libraries and see if we
  8907. * have any. */
  8908. if (!ssh->gsslibs)
  8909. ssh->gsslibs = ssh_gss_setup(ssh->conf, ssh->frontend); // MPEXT
  8910. s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
  8911. } else {
  8912. /* No point in even bothering to try to load the
  8913. * GSS libraries, if the user configuration and
  8914. * server aren't both prepared to attempt GSSAPI
  8915. * auth in the first place. */
  8916. s->can_gssapi = FALSE;
  8917. }
  8918. #endif
  8919. }
  8920. ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
  8921. if (s->can_pubkey && !s->done_agent && s->nkeys) {
  8922. /*
  8923. * Attempt public-key authentication using a key from Pageant.
  8924. */
  8925. ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
  8926. logeventf(ssh, "Trying Pageant key #%d", s->keyi);
  8927. /* Unpack key from agent response */
  8928. s->pklen = toint(GET_32BIT(s->agentp));
  8929. s->agentp += 4;
  8930. s->pkblob = (char *)s->agentp;
  8931. s->agentp += s->pklen;
  8932. s->alglen = toint(GET_32BIT(s->pkblob));
  8933. s->alg = s->pkblob + 4;
  8934. s->commentlen = toint(GET_32BIT(s->agentp));
  8935. s->agentp += 4;
  8936. s->commentp = (char *)s->agentp;
  8937. s->agentp += s->commentlen;
  8938. /* s->agentp now points at next key, if any */
  8939. /* See if server will accept it */
  8940. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  8941. ssh2_pkt_addstring(s->pktout, ssh->username);
  8942. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  8943. /* service requested */
  8944. ssh2_pkt_addstring(s->pktout, "publickey");
  8945. /* method */
  8946. ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
  8947. ssh2_pkt_addstring_start(s->pktout);
  8948. ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
  8949. ssh2_pkt_addstring_start(s->pktout);
  8950. ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
  8951. ssh2_pkt_send(ssh, s->pktout);
  8952. s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
  8953. crWaitUntilV(pktin);
  8954. if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
  8955. /* Offer of key refused. */
  8956. s->gotit = TRUE;
  8957. } else {
  8958. void *vret;
  8959. if (flags & FLAG_VERBOSE) {
  8960. c_write_str(ssh, "Authenticating with "
  8961. "public key \"");
  8962. c_write(ssh, s->commentp, s->commentlen);
  8963. c_write_str(ssh, "\" from agent\r\n");
  8964. }
  8965. /*
  8966. * Server is willing to accept the key.
  8967. * Construct a SIGN_REQUEST.
  8968. */
  8969. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  8970. ssh2_pkt_addstring(s->pktout, ssh->username);
  8971. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  8972. /* service requested */
  8973. ssh2_pkt_addstring(s->pktout, "publickey");
  8974. /* method */
  8975. ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
  8976. ssh2_pkt_addstring_start(s->pktout);
  8977. ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
  8978. ssh2_pkt_addstring_start(s->pktout);
  8979. ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
  8980. /* Ask agent for signature. */
  8981. s->siglen = s->pktout->length - 5 + 4 +
  8982. ssh->v2_session_id_len;
  8983. if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
  8984. s->siglen -= 4;
  8985. s->len = 1; /* message type */
  8986. s->len += 4 + s->pklen; /* key blob */
  8987. s->len += 4 + s->siglen; /* data to sign */
  8988. s->len += 4; /* flags */
  8989. s->agentreq = snewn(4 + s->len, char);
  8990. PUT_32BIT(s->agentreq, s->len);
  8991. s->q = s->agentreq + 4;
  8992. *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
  8993. PUT_32BIT(s->q, s->pklen);
  8994. s->q += 4;
  8995. memcpy(s->q, s->pkblob, s->pklen);
  8996. s->q += s->pklen;
  8997. PUT_32BIT(s->q, s->siglen);
  8998. s->q += 4;
  8999. /* Now the data to be signed... */
  9000. if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
  9001. PUT_32BIT(s->q, ssh->v2_session_id_len);
  9002. s->q += 4;
  9003. }
  9004. memcpy(s->q, ssh->v2_session_id,
  9005. ssh->v2_session_id_len);
  9006. s->q += ssh->v2_session_id_len;
  9007. memcpy(s->q, s->pktout->data + 5,
  9008. s->pktout->length - 5);
  9009. s->q += s->pktout->length - 5;
  9010. /* And finally the (zero) flags word. */
  9011. PUT_32BIT(s->q, 0);
  9012. ssh->auth_agent_query = agent_query(
  9013. s->agentreq, s->len + 4, &vret, &s->retlen,
  9014. ssh_agent_callback, ssh);
  9015. if (ssh->auth_agent_query) {
  9016. do {
  9017. crReturnV;
  9018. if (pktin) {
  9019. bombout(("Unexpected data from server"
  9020. " while waiting for agent"
  9021. " response"));
  9022. crStopV;
  9023. }
  9024. } while (pktin || inlen > 0);
  9025. vret = ssh->agent_response;
  9026. s->retlen = ssh->agent_response_len;
  9027. }
  9028. s->ret = vret;
  9029. sfree(s->agentreq);
  9030. if (s->ret) {
  9031. if (s->retlen >= 9 &&
  9032. s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
  9033. GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
  9034. logevent("Sending Pageant's response");
  9035. ssh2_add_sigblob(ssh, s->pktout,
  9036. s->pkblob, s->pklen,
  9037. s->ret + 9,
  9038. GET_32BIT(s->ret + 5));
  9039. ssh2_pkt_send(ssh, s->pktout);
  9040. s->type = AUTH_TYPE_PUBLICKEY;
  9041. #ifdef MPEXT
  9042. sfree(s->ret);
  9043. #endif
  9044. } else {
  9045. /* FIXME: less drastic response */
  9046. bombout(("Pageant failed to answer challenge"));
  9047. crStopV;
  9048. }
  9049. }
  9050. }
  9051. /* Do we have any keys left to try? */
  9052. if (s->pkblob_in_agent) {
  9053. s->done_agent = TRUE;
  9054. s->tried_pubkey_config = TRUE;
  9055. } else {
  9056. s->keyi++;
  9057. if (s->keyi >= s->nkeys)
  9058. s->done_agent = TRUE;
  9059. }
  9060. } else if (s->can_pubkey && s->publickey_blob &&
  9061. s->privatekey_available && !s->tried_pubkey_config) {
  9062. struct ssh2_userkey *key; /* not live over crReturn */
  9063. char *passphrase; /* not live over crReturn */
  9064. ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
  9065. s->tried_pubkey_config = TRUE;
  9066. /*
  9067. * Try the public key supplied in the configuration.
  9068. *
  9069. * First, offer the public blob to see if the server is
  9070. * willing to accept it.
  9071. */
  9072. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9073. ssh2_pkt_addstring(s->pktout, ssh->username);
  9074. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9075. /* service requested */
  9076. ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
  9077. ssh2_pkt_addbool(s->pktout, FALSE);
  9078. /* no signature included */
  9079. ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
  9080. ssh2_pkt_addstring_start(s->pktout);
  9081. ssh2_pkt_addstring_data(s->pktout,
  9082. (char *)s->publickey_blob,
  9083. s->publickey_bloblen);
  9084. ssh2_pkt_send(ssh, s->pktout);
  9085. logevent("Offered public key");
  9086. crWaitUntilV(pktin);
  9087. if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
  9088. /* Key refused. Give up. */
  9089. s->gotit = TRUE; /* reconsider message next loop */
  9090. s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
  9091. continue; /* process this new message */
  9092. }
  9093. logevent("Offer of public key accepted");
  9094. /*
  9095. * Actually attempt a serious authentication using
  9096. * the key.
  9097. */
  9098. if (flags & FLAG_VERBOSE) {
  9099. c_write_str(ssh, "Authenticating with public key \"");
  9100. c_write_str(ssh, s->publickey_comment);
  9101. c_write_str(ssh, "\"\r\n");
  9102. }
  9103. key = NULL;
  9104. while (!key) {
  9105. const char *error; /* not live over crReturn */
  9106. if (s->privatekey_encrypted) {
  9107. /*
  9108. * Get a passphrase from the user.
  9109. */
  9110. int ret; /* need not be kept over crReturn */
  9111. s->cur_prompt = new_prompts(ssh->frontend);
  9112. s->cur_prompt->to_server = FALSE;
  9113. s->cur_prompt->name = dupstr("SSH key passphrase");
  9114. add_prompt(s->cur_prompt,
  9115. dupprintf("Passphrase for key \"%.100s\": ",
  9116. s->publickey_comment),
  9117. FALSE);
  9118. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  9119. while (ret < 0) {
  9120. ssh->send_ok = 1;
  9121. crWaitUntilV(!pktin);
  9122. ret = get_userpass_input(s->cur_prompt,
  9123. in, inlen);
  9124. ssh->send_ok = 0;
  9125. }
  9126. if (!ret) {
  9127. /* Failed to get a passphrase. Terminate. */
  9128. free_prompts(s->cur_prompt);
  9129. ssh_disconnect(ssh, NULL,
  9130. "Unable to authenticate",
  9131. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  9132. TRUE);
  9133. crStopV;
  9134. }
  9135. passphrase =
  9136. dupstr(s->cur_prompt->prompts[0]->result);
  9137. free_prompts(s->cur_prompt);
  9138. } else {
  9139. passphrase = NULL; /* no passphrase needed */
  9140. }
  9141. /*
  9142. * Try decrypting the key.
  9143. */
  9144. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  9145. key = ssh2_load_userkey(s->keyfile, passphrase, &error);
  9146. if (passphrase) {
  9147. /* burn the evidence */
  9148. smemclr(passphrase, strlen(passphrase));
  9149. sfree(passphrase);
  9150. }
  9151. if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
  9152. if (passphrase &&
  9153. (key == SSH2_WRONG_PASSPHRASE)) {
  9154. c_write_str(ssh, "Wrong passphrase\r\n");
  9155. key = NULL;
  9156. /* and loop again */
  9157. } else {
  9158. c_write_str(ssh, "Unable to load private key (");
  9159. c_write_str(ssh, error);
  9160. c_write_str(ssh, ")\r\n");
  9161. key = NULL;
  9162. break; /* try something else */
  9163. }
  9164. }
  9165. }
  9166. if (key) {
  9167. unsigned char *pkblob, *sigblob, *sigdata;
  9168. int pkblob_len, sigblob_len, sigdata_len;
  9169. int p;
  9170. /*
  9171. * We have loaded the private key and the server
  9172. * has announced that it's willing to accept it.
  9173. * Hallelujah. Generate a signature and send it.
  9174. */
  9175. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9176. ssh2_pkt_addstring(s->pktout, ssh->username);
  9177. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9178. /* service requested */
  9179. ssh2_pkt_addstring(s->pktout, "publickey");
  9180. /* method */
  9181. ssh2_pkt_addbool(s->pktout, TRUE);
  9182. /* signature follows */
  9183. ssh2_pkt_addstring(s->pktout, key->alg->name);
  9184. pkblob = key->alg->public_blob(key->data,
  9185. &pkblob_len);
  9186. ssh2_pkt_addstring_start(s->pktout);
  9187. ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
  9188. pkblob_len);
  9189. /*
  9190. * The data to be signed is:
  9191. *
  9192. * string session-id
  9193. *
  9194. * followed by everything so far placed in the
  9195. * outgoing packet.
  9196. */
  9197. sigdata_len = s->pktout->length - 5 + 4 +
  9198. ssh->v2_session_id_len;
  9199. if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
  9200. sigdata_len -= 4;
  9201. sigdata = snewn(sigdata_len, unsigned char);
  9202. p = 0;
  9203. if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
  9204. PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
  9205. p += 4;
  9206. }
  9207. memcpy(sigdata+p, ssh->v2_session_id,
  9208. ssh->v2_session_id_len);
  9209. p += ssh->v2_session_id_len;
  9210. memcpy(sigdata+p, s->pktout->data + 5,
  9211. s->pktout->length - 5);
  9212. p += s->pktout->length - 5;
  9213. assert(p == sigdata_len);
  9214. sigblob = key->alg->sign(key->data, (char *)sigdata,
  9215. sigdata_len, &sigblob_len);
  9216. ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
  9217. sigblob, sigblob_len);
  9218. sfree(pkblob);
  9219. sfree(sigblob);
  9220. sfree(sigdata);
  9221. ssh2_pkt_send(ssh, s->pktout);
  9222. logevent("Sent public key signature");
  9223. s->type = AUTH_TYPE_PUBLICKEY;
  9224. key->alg->freekey(key->data);
  9225. sfree(key->comment);
  9226. sfree(key);
  9227. }
  9228. #ifndef NO_GSSAPI
  9229. } else if (s->can_gssapi && !s->tried_gssapi) {
  9230. /* GSSAPI Authentication */
  9231. int micoffset, len;
  9232. char *data;
  9233. Ssh_gss_buf mic;
  9234. #ifdef MPEXT
  9235. const char * fullhostname;
  9236. char *loghost;
  9237. #endif
  9238. s->type = AUTH_TYPE_GSSAPI;
  9239. s->tried_gssapi = TRUE;
  9240. s->gotit = TRUE;
  9241. ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
  9242. /*
  9243. * Pick the highest GSS library on the preference
  9244. * list.
  9245. */
  9246. {
  9247. int i, j;
  9248. s->gsslib = NULL;
  9249. for (i = 0; i < ngsslibs; i++) {
  9250. int want_id = conf_get_int_int(ssh->conf,
  9251. CONF_ssh_gsslist, i);
  9252. for (j = 0; j < ssh->gsslibs->nlibraries; j++)
  9253. if (ssh->gsslibs->libraries[j].id == want_id) {
  9254. s->gsslib = &ssh->gsslibs->libraries[j];
  9255. goto got_gsslib; /* double break */
  9256. }
  9257. }
  9258. got_gsslib:
  9259. /*
  9260. * We always expect to have found something in
  9261. * the above loop: we only came here if there
  9262. * was at least one viable GSS library, and the
  9263. * preference list should always mention
  9264. * everything and only change the order.
  9265. */
  9266. assert(s->gsslib);
  9267. }
  9268. if (s->gsslib->gsslogmsg)
  9269. logevent(s->gsslib->gsslogmsg);
  9270. /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
  9271. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9272. ssh2_pkt_addstring(s->pktout, ssh->username);
  9273. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9274. ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
  9275. logevent("Attempting GSSAPI authentication");
  9276. /* add mechanism info */
  9277. s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
  9278. /* number of GSSAPI mechanisms */
  9279. ssh2_pkt_adduint32(s->pktout,1);
  9280. /* length of OID + 2 */
  9281. ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
  9282. ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
  9283. /* length of OID */
  9284. ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
  9285. ssh_pkt_adddata(s->pktout, s->gss_buf.value,
  9286. s->gss_buf.length);
  9287. ssh2_pkt_send(ssh, s->pktout);
  9288. crWaitUntilV(pktin);
  9289. if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
  9290. logevent("GSSAPI authentication request refused");
  9291. continue;
  9292. }
  9293. /* check returned packet ... */
  9294. ssh_pkt_getstring(pktin, &data, &len);
  9295. s->gss_rcvtok.value = data;
  9296. s->gss_rcvtok.length = len;
  9297. if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
  9298. ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
  9299. ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
  9300. memcmp((char *)s->gss_rcvtok.value + 2,
  9301. s->gss_buf.value,s->gss_buf.length) ) {
  9302. logevent("GSSAPI authentication - wrong response from server");
  9303. continue;
  9304. }
  9305. /* now start running */
  9306. #ifdef MPEXT
  9307. fullhostname = ssh->fullhostname;
  9308. loghost = conf_get_str(ssh->conf, CONF_loghost);
  9309. if (loghost[0] != '\0')
  9310. {
  9311. fullhostname = loghost;
  9312. }
  9313. #endif
  9314. s->gss_stat = s->gsslib->import_name(s->gsslib,
  9315. #ifdef MPEXT
  9316. fullhostname,
  9317. #else
  9318. ssh->fullhostname,
  9319. #endif
  9320. &s->gss_srv_name);
  9321. if (s->gss_stat != SSH_GSS_OK) {
  9322. if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
  9323. logevent("GSSAPI import name failed - Bad service name");
  9324. else
  9325. logevent("GSSAPI import name failed");
  9326. continue;
  9327. }
  9328. /* fetch TGT into GSS engine */
  9329. s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
  9330. if (s->gss_stat != SSH_GSS_OK) {
  9331. logevent("GSSAPI authentication failed to get credentials");
  9332. s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
  9333. continue;
  9334. }
  9335. /* initial tokens are empty */
  9336. SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
  9337. SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
  9338. /* now enter the loop */
  9339. do {
  9340. s->gss_stat = s->gsslib->init_sec_context
  9341. (s->gsslib,
  9342. &s->gss_ctx,
  9343. s->gss_srv_name,
  9344. conf_get_int(ssh->conf, CONF_gssapifwd),
  9345. &s->gss_rcvtok,
  9346. &s->gss_sndtok);
  9347. if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
  9348. s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
  9349. logevent("GSSAPI authentication initialisation failed");
  9350. if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
  9351. &s->gss_buf) == SSH_GSS_OK) {
  9352. logevent(s->gss_buf.value);
  9353. sfree(s->gss_buf.value);
  9354. }
  9355. break;
  9356. }
  9357. logevent("GSSAPI authentication initialised");
  9358. /* Client and server now exchange tokens until GSSAPI
  9359. * no longer says CONTINUE_NEEDED */
  9360. if (s->gss_sndtok.length != 0) {
  9361. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
  9362. ssh_pkt_addstring_start(s->pktout);
  9363. ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
  9364. ssh2_pkt_send(ssh, s->pktout);
  9365. s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
  9366. }
  9367. if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
  9368. crWaitUntilV(pktin);
  9369. if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
  9370. logevent("GSSAPI authentication - bad server response");
  9371. s->gss_stat = SSH_GSS_FAILURE;
  9372. break;
  9373. }
  9374. ssh_pkt_getstring(pktin, &data, &len);
  9375. s->gss_rcvtok.value = data;
  9376. s->gss_rcvtok.length = len;
  9377. }
  9378. } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
  9379. if (s->gss_stat != SSH_GSS_OK) {
  9380. s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
  9381. s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
  9382. continue;
  9383. }
  9384. logevent("GSSAPI authentication loop finished OK");
  9385. /* Now send the MIC */
  9386. s->pktout = ssh2_pkt_init(0);
  9387. micoffset = s->pktout->length;
  9388. ssh_pkt_addstring_start(s->pktout);
  9389. ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
  9390. ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
  9391. ssh_pkt_addstring(s->pktout, ssh->username);
  9392. ssh_pkt_addstring(s->pktout, "ssh-connection");
  9393. ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
  9394. s->gss_buf.value = (char *)s->pktout->data + micoffset;
  9395. s->gss_buf.length = s->pktout->length - micoffset;
  9396. s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
  9397. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
  9398. ssh_pkt_addstring_start(s->pktout);
  9399. ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
  9400. ssh2_pkt_send(ssh, s->pktout);
  9401. s->gsslib->free_mic(s->gsslib, &mic);
  9402. s->gotit = FALSE;
  9403. s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
  9404. s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
  9405. continue;
  9406. #endif
  9407. } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
  9408. /*
  9409. * Keyboard-interactive authentication.
  9410. */
  9411. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
  9412. ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
  9413. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9414. ssh2_pkt_addstring(s->pktout, ssh->username);
  9415. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9416. /* service requested */
  9417. ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
  9418. /* method */
  9419. ssh2_pkt_addstring(s->pktout, ""); /* lang */
  9420. ssh2_pkt_addstring(s->pktout, ""); /* submethods */
  9421. ssh2_pkt_send(ssh, s->pktout);
  9422. logevent("Attempting keyboard-interactive authentication");
  9423. crWaitUntilV(pktin);
  9424. if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
  9425. /* Server is not willing to do keyboard-interactive
  9426. * at all (or, bizarrely but legally, accepts the
  9427. * user without actually issuing any prompts).
  9428. * Give up on it entirely. */
  9429. s->gotit = TRUE;
  9430. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
  9431. s->kbd_inter_refused = TRUE; /* don't try it again */
  9432. continue;
  9433. }
  9434. /*
  9435. * Loop while the server continues to send INFO_REQUESTs.
  9436. */
  9437. while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
  9438. char *name, *inst, *lang;
  9439. int name_len, inst_len, lang_len;
  9440. int i;
  9441. /*
  9442. * We've got a fresh USERAUTH_INFO_REQUEST.
  9443. * Get the preamble and start building a prompt.
  9444. */
  9445. ssh_pkt_getstring(pktin, &name, &name_len);
  9446. ssh_pkt_getstring(pktin, &inst, &inst_len);
  9447. ssh_pkt_getstring(pktin, &lang, &lang_len);
  9448. s->cur_prompt = new_prompts(ssh->frontend);
  9449. s->cur_prompt->to_server = TRUE;
  9450. /*
  9451. * Get any prompt(s) from the packet.
  9452. */
  9453. s->num_prompts = ssh_pkt_getuint32(pktin);
  9454. for (i = 0; i < s->num_prompts; i++) {
  9455. char *prompt;
  9456. int prompt_len;
  9457. int echo;
  9458. static char noprompt[] =
  9459. "<server failed to send prompt>: ";
  9460. ssh_pkt_getstring(pktin, &prompt, &prompt_len);
  9461. echo = ssh2_pkt_getbool(pktin);
  9462. if (!prompt_len) {
  9463. prompt = noprompt;
  9464. prompt_len = lenof(noprompt)-1;
  9465. }
  9466. add_prompt(s->cur_prompt,
  9467. dupprintf("%.*s", prompt_len, prompt),
  9468. echo);
  9469. }
  9470. if (name_len) {
  9471. /* FIXME: better prefix to distinguish from
  9472. * local prompts? */
  9473. s->cur_prompt->name =
  9474. dupprintf("SSH server: %.*s", name_len, name);
  9475. s->cur_prompt->name_reqd = TRUE;
  9476. } else {
  9477. s->cur_prompt->name =
  9478. dupstr("SSH server authentication");
  9479. s->cur_prompt->name_reqd = FALSE;
  9480. }
  9481. /* We add a prefix to try to make it clear that a prompt
  9482. * has come from the server.
  9483. * FIXME: ugly to print "Using..." in prompt _every_
  9484. * time round. Can this be done more subtly? */
  9485. /* Special case: for reasons best known to themselves,
  9486. * some servers send k-i requests with no prompts and
  9487. * nothing to display. Keep quiet in this case. */
  9488. if (s->num_prompts || name_len || inst_len) {
  9489. s->cur_prompt->instruction =
  9490. dupprintf("Using keyboard-interactive authentication.%s%.*s",
  9491. inst_len ? "\n" : "", inst_len, inst);
  9492. s->cur_prompt->instr_reqd = TRUE;
  9493. } else {
  9494. s->cur_prompt->instr_reqd = FALSE;
  9495. }
  9496. /*
  9497. * Display any instructions, and get the user's
  9498. * response(s).
  9499. */
  9500. {
  9501. int ret; /* not live over crReturn */
  9502. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  9503. while (ret < 0) {
  9504. ssh->send_ok = 1;
  9505. crWaitUntilV(!pktin);
  9506. ret = get_userpass_input(s->cur_prompt, in, inlen);
  9507. ssh->send_ok = 0;
  9508. }
  9509. if (!ret) {
  9510. /*
  9511. * Failed to get responses. Terminate.
  9512. */
  9513. free_prompts(s->cur_prompt);
  9514. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  9515. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  9516. TRUE);
  9517. crStopV;
  9518. }
  9519. }
  9520. /*
  9521. * Send the response(s) to the server.
  9522. */
  9523. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
  9524. ssh2_pkt_adduint32(s->pktout, s->num_prompts);
  9525. for (i=0; i < s->num_prompts; i++) {
  9526. ssh2_pkt_addstring(s->pktout,
  9527. s->cur_prompt->prompts[i]->result);
  9528. }
  9529. ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
  9530. /*
  9531. * Free the prompts structure from this iteration.
  9532. * If there's another, a new one will be allocated
  9533. * when we return to the top of this while loop.
  9534. */
  9535. free_prompts(s->cur_prompt);
  9536. /*
  9537. * Get the next packet in case it's another
  9538. * INFO_REQUEST.
  9539. */
  9540. crWaitUntilV(pktin);
  9541. }
  9542. /*
  9543. * We should have SUCCESS or FAILURE now.
  9544. */
  9545. s->gotit = TRUE;
  9546. } else if (s->can_passwd) {
  9547. /*
  9548. * Plain old password authentication.
  9549. */
  9550. int ret; /* not live over crReturn */
  9551. int changereq_first_time; /* not live over crReturn */
  9552. ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
  9553. #ifdef MPEXT
  9554. s->change_password = conf_get_int(ssh->conf, CONF_change_password);
  9555. if (s->change_password != 0)
  9556. {
  9557. s->password = dupstr("");
  9558. s->type = AUTH_TYPE_PASSWORD;
  9559. }
  9560. else
  9561. {
  9562. /* no indentation to ease merges */
  9563. #endif
  9564. s->cur_prompt = new_prompts(ssh->frontend);
  9565. s->cur_prompt->to_server = TRUE;
  9566. s->cur_prompt->name = dupstr("SSH password");
  9567. #ifdef _DEBUG
  9568. // To suppress CodeGuard warning
  9569. add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
  9570. #else
  9571. add_prompt(s->cur_prompt, dupprintf("%.90s@%.90s's password: ",
  9572. #endif
  9573. ssh->username,
  9574. ssh->savedhost),
  9575. FALSE);
  9576. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  9577. while (ret < 0) {
  9578. ssh->send_ok = 1;
  9579. crWaitUntilV(!pktin);
  9580. ret = get_userpass_input(s->cur_prompt, in, inlen);
  9581. ssh->send_ok = 0;
  9582. }
  9583. if (!ret) {
  9584. /*
  9585. * Failed to get responses. Terminate.
  9586. */
  9587. free_prompts(s->cur_prompt);
  9588. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  9589. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  9590. TRUE);
  9591. crStopV;
  9592. }
  9593. /*
  9594. * Squirrel away the password. (We may need it later if
  9595. * asked to change it.)
  9596. */
  9597. s->password = dupstr(s->cur_prompt->prompts[0]->result);
  9598. free_prompts(s->cur_prompt);
  9599. /*
  9600. * Send the password packet.
  9601. *
  9602. * We pad out the password packet to 256 bytes to make
  9603. * it harder for an attacker to find the length of the
  9604. * user's password.
  9605. *
  9606. * Anyone using a password longer than 256 bytes
  9607. * probably doesn't have much to worry about from
  9608. * people who find out how long their password is!
  9609. */
  9610. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9611. ssh2_pkt_addstring(s->pktout, ssh->username);
  9612. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9613. /* service requested */
  9614. ssh2_pkt_addstring(s->pktout, "password");
  9615. ssh2_pkt_addbool(s->pktout, FALSE);
  9616. ssh2_pkt_addstring(s->pktout, s->password);
  9617. ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
  9618. logevent("Sent password");
  9619. s->type = AUTH_TYPE_PASSWORD;
  9620. /*
  9621. * Wait for next packet, in case it's a password change
  9622. * request.
  9623. */
  9624. crWaitUntilV(pktin);
  9625. #ifdef MPEXT
  9626. }
  9627. #endif
  9628. changereq_first_time = TRUE;
  9629. while ((pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ)
  9630. #ifdef MPEXT
  9631. || (s->change_password != 0)
  9632. #endif
  9633. ) {
  9634. /*
  9635. * We're being asked for a new password
  9636. * (perhaps not for the first time).
  9637. * Loop until the server accepts it.
  9638. */
  9639. int got_new = FALSE; /* not live over crReturn */
  9640. char *prompt; /* not live over crReturn */
  9641. int prompt_len; /* not live over crReturn */
  9642. #ifdef MPEXT
  9643. if (s->change_password == 0)
  9644. #endif
  9645. {
  9646. const char *msg;
  9647. if (changereq_first_time)
  9648. msg = "Server requested password change";
  9649. else
  9650. msg = "Server rejected new password";
  9651. logevent(msg);
  9652. c_write_str(ssh, msg);
  9653. c_write_str(ssh, "\r\n");
  9654. }
  9655. #ifdef MPEXT
  9656. s->change_password = 0;
  9657. #endif
  9658. ssh_pkt_getstring(pktin, &prompt, &prompt_len);
  9659. s->cur_prompt = new_prompts(ssh->frontend);
  9660. s->cur_prompt->to_server = TRUE;
  9661. s->cur_prompt->name = dupstr("New SSH password");
  9662. s->cur_prompt->instruction =
  9663. dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
  9664. s->cur_prompt->instr_reqd = TRUE;
  9665. /*
  9666. * There's no explicit requirement in the protocol
  9667. * for the "old" passwords in the original and
  9668. * password-change messages to be the same, and
  9669. * apparently some Cisco kit supports password change
  9670. * by the user entering a blank password originally
  9671. * and the real password subsequently, so,
  9672. * reluctantly, we prompt for the old password again.
  9673. *
  9674. * (On the other hand, some servers don't even bother
  9675. * to check this field.)
  9676. */
  9677. add_prompt(s->cur_prompt,
  9678. dupstr("Current password (blank for previously entered password): "),
  9679. FALSE);
  9680. add_prompt(s->cur_prompt, dupstr("Enter new password: "),
  9681. FALSE);
  9682. add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
  9683. FALSE);
  9684. /*
  9685. * Loop until the user manages to enter the same
  9686. * password twice.
  9687. */
  9688. while (!got_new) {
  9689. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  9690. while (ret < 0) {
  9691. ssh->send_ok = 1;
  9692. crWaitUntilV(!pktin);
  9693. ret = get_userpass_input(s->cur_prompt, in, inlen);
  9694. ssh->send_ok = 0;
  9695. }
  9696. if (!ret) {
  9697. /*
  9698. * Failed to get responses. Terminate.
  9699. */
  9700. /* burn the evidence */
  9701. free_prompts(s->cur_prompt);
  9702. smemclr(s->password, strlen(s->password));
  9703. sfree(s->password);
  9704. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  9705. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  9706. TRUE);
  9707. crStopV;
  9708. }
  9709. /*
  9710. * If the user specified a new original password
  9711. * (IYSWIM), overwrite any previously specified
  9712. * one.
  9713. * (A side effect is that the user doesn't have to
  9714. * re-enter it if they louse up the new password.)
  9715. */
  9716. if (s->cur_prompt->prompts[0]->result[0]) {
  9717. smemclr(s->password, strlen(s->password));
  9718. /* burn the evidence */
  9719. sfree(s->password);
  9720. s->password =
  9721. dupstr(s->cur_prompt->prompts[0]->result);
  9722. }
  9723. /*
  9724. * Check the two new passwords match.
  9725. */
  9726. got_new = (strcmp(s->cur_prompt->prompts[1]->result,
  9727. s->cur_prompt->prompts[2]->result)
  9728. == 0);
  9729. if (!got_new)
  9730. /* They don't. Silly user. */
  9731. c_write_str(ssh, "Passwords do not match\r\n");
  9732. }
  9733. /*
  9734. * Send the new password (along with the old one).
  9735. * (see above for padding rationale)
  9736. */
  9737. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9738. ssh2_pkt_addstring(s->pktout, ssh->username);
  9739. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9740. /* service requested */
  9741. ssh2_pkt_addstring(s->pktout, "password");
  9742. ssh2_pkt_addbool(s->pktout, TRUE);
  9743. ssh2_pkt_addstring(s->pktout, s->password);
  9744. ssh2_pkt_addstring(s->pktout,
  9745. s->cur_prompt->prompts[1]->result);
  9746. free_prompts(s->cur_prompt);
  9747. ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
  9748. logevent("Sent new password");
  9749. /*
  9750. * Now see what the server has to say about it.
  9751. * (If it's CHANGEREQ again, it's not happy with the
  9752. * new password.)
  9753. */
  9754. crWaitUntilV(pktin);
  9755. changereq_first_time = FALSE;
  9756. }
  9757. /*
  9758. * We need to reexamine the current pktin at the top
  9759. * of the loop. Either:
  9760. * - we weren't asked to change password at all, in
  9761. * which case it's a SUCCESS or FAILURE with the
  9762. * usual meaning
  9763. * - we sent a new password, and the server was
  9764. * either OK with it (SUCCESS or FAILURE w/partial
  9765. * success) or unhappy with the _old_ password
  9766. * (FAILURE w/o partial success)
  9767. * In any of these cases, we go back to the top of
  9768. * the loop and start again.
  9769. */
  9770. s->gotit = TRUE;
  9771. /*
  9772. * We don't need the old password any more, in any
  9773. * case. Burn the evidence.
  9774. */
  9775. smemclr(s->password, strlen(s->password));
  9776. sfree(s->password);
  9777. } else {
  9778. char *str = dupprintf("No supported authentication methods available"
  9779. " (server sent: %.*s)",
  9780. methlen, methods);
  9781. ssh_disconnect(ssh, str,
  9782. "No supported authentication methods available",
  9783. SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
  9784. FALSE);
  9785. sfree(str);
  9786. crStopV;
  9787. }
  9788. }
  9789. }
  9790. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
  9791. /* Clear up various bits and pieces from authentication. */
  9792. if (s->publickey_blob) {
  9793. sfree(s->publickey_algorithm);
  9794. sfree(s->publickey_blob);
  9795. sfree(s->publickey_comment);
  9796. }
  9797. if (s->agent_response)
  9798. sfree(s->agent_response);
  9799. if (s->userauth_success && !ssh->bare_connection) {
  9800. /*
  9801. * We've just received USERAUTH_SUCCESS, and we haven't sent any
  9802. * packets since. Signal the transport layer to consider enacting
  9803. * delayed compression.
  9804. *
  9805. * (Relying on we_are_in is not sufficient, as
  9806. * draft-miller-secsh-compression-delayed is quite clear that it
  9807. * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
  9808. * become set for other reasons.)
  9809. */
  9810. do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
  9811. }
  9812. ssh->channels = newtree234(ssh_channelcmp);
  9813. /*
  9814. * Set up handlers for some connection protocol messages, so we
  9815. * don't have to handle them repeatedly in this coroutine.
  9816. */
  9817. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
  9818. ssh2_msg_channel_window_adjust;
  9819. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
  9820. ssh2_msg_global_request;
  9821. /*
  9822. * Create the main session channel.
  9823. */
  9824. if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
  9825. ssh->mainchan = NULL;
  9826. } else {
  9827. ssh->mainchan = snew(struct ssh_channel);
  9828. ssh->mainchan->ssh = ssh;
  9829. ssh_channel_init(ssh->mainchan);
  9830. if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
  9831. /*
  9832. * Just start a direct-tcpip channel and use it as the main
  9833. * channel.
  9834. */
  9835. ssh_send_port_open(ssh->mainchan,
  9836. conf_get_str(ssh->conf, CONF_ssh_nc_host),
  9837. conf_get_int(ssh->conf, CONF_ssh_nc_port),
  9838. "main channel");
  9839. ssh->ncmode = TRUE;
  9840. } else {
  9841. s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
  9842. logevent("Opening session as main channel");
  9843. ssh2_pkt_send(ssh, s->pktout);
  9844. ssh->ncmode = FALSE;
  9845. }
  9846. crWaitUntilV(pktin);
  9847. if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
  9848. pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE) {
  9849. bombout(("Server sent strange packet %d in response to main "
  9850. "channel open request", pktin->type));
  9851. crStopV;
  9852. }
  9853. if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
  9854. bombout(("Server's response to main channel open cited wrong"
  9855. " channel number"));
  9856. crStopV;
  9857. }
  9858. if (pktin->type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
  9859. char *errtext = ssh2_channel_open_failure_error_text(pktin);
  9860. bombout(("Server refused to open main channel: %s", errtext));
  9861. sfree(errtext);
  9862. crStopV;
  9863. }
  9864. ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
  9865. ssh->mainchan->halfopen = FALSE;
  9866. ssh->mainchan->type = CHAN_MAINSESSION;
  9867. ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
  9868. ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
  9869. update_specials_menu(ssh->frontend);
  9870. logevent("Opened main channel");
  9871. }
  9872. /*
  9873. * Now we have a channel, make dispatch table entries for
  9874. * general channel-based messages.
  9875. */
  9876. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
  9877. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
  9878. ssh2_msg_channel_data;
  9879. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
  9880. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
  9881. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
  9882. ssh2_msg_channel_open_confirmation;
  9883. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
  9884. ssh2_msg_channel_open_failure;
  9885. ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
  9886. ssh2_msg_channel_request;
  9887. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
  9888. ssh2_msg_channel_open;
  9889. ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
  9890. ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
  9891. /*
  9892. * Now the connection protocol is properly up and running, with
  9893. * all those dispatch table entries, so it's safe to let
  9894. * downstreams start trying to open extra channels through us.
  9895. */
  9896. if (ssh->connshare)
  9897. share_activate(ssh->connshare, ssh->v_s);
  9898. if (ssh->mainchan && ssh_is_simple(ssh)) {
  9899. /*
  9900. * This message indicates to the server that we promise
  9901. * not to try to run any other channel in parallel with
  9902. * this one, so it's safe for it to advertise a very large
  9903. * window and leave the flow control to TCP.
  9904. */
  9905. s->pktout = ssh2_chanreq_init(ssh->mainchan,
  9906. "[email protected]",
  9907. NULL, NULL);
  9908. ssh2_pkt_send(ssh, s->pktout);
  9909. }
  9910. /*
  9911. * Enable port forwardings.
  9912. */
  9913. ssh_setup_portfwd(ssh, ssh->conf);
  9914. if (ssh->mainchan && !ssh->ncmode) {
  9915. /*
  9916. * Send the CHANNEL_REQUESTS for the main session channel.
  9917. * Each one is handled by its own little asynchronous
  9918. * co-routine.
  9919. */
  9920. /* Potentially enable X11 forwarding. */
  9921. if (conf_get_int(ssh->conf, CONF_x11_forward)) {
  9922. ssh->x11disp =
  9923. x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
  9924. ssh->conf);
  9925. if (!ssh->x11disp) {
  9926. /* FIXME: return an error message from x11_setup_display */
  9927. logevent("X11 forwarding not enabled: unable to"
  9928. " initialise X display");
  9929. } else {
  9930. ssh->x11auth = x11_invent_fake_auth
  9931. (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
  9932. ssh->x11auth->disp = ssh->x11disp;
  9933. ssh2_setup_x11(ssh->mainchan, NULL, NULL);
  9934. }
  9935. }
  9936. /* Potentially enable agent forwarding. */
  9937. if (ssh_agent_forwarding_permitted(ssh))
  9938. ssh2_setup_agent(ssh->mainchan, NULL, NULL);
  9939. /* Now allocate a pty for the session. */
  9940. if (!conf_get_int(ssh->conf, CONF_nopty))
  9941. ssh2_setup_pty(ssh->mainchan, NULL, NULL);
  9942. /* Send environment variables. */
  9943. ssh2_setup_env(ssh->mainchan, NULL, NULL);
  9944. /*
  9945. * Start a shell or a remote command. We may have to attempt
  9946. * this twice if the config data has provided a second choice
  9947. * of command.
  9948. */
  9949. while (1) {
  9950. int subsys;
  9951. char *cmd;
  9952. if (ssh->fallback_cmd) {
  9953. subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
  9954. cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
  9955. } else {
  9956. subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
  9957. cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
  9958. }
  9959. if (subsys) {
  9960. s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
  9961. ssh2_response_authconn, NULL);
  9962. ssh2_pkt_addstring(s->pktout, cmd);
  9963. } else if (*cmd) {
  9964. s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
  9965. ssh2_response_authconn, NULL);
  9966. ssh2_pkt_addstring(s->pktout, cmd);
  9967. } else {
  9968. s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
  9969. ssh2_response_authconn, NULL);
  9970. }
  9971. ssh2_pkt_send(ssh, s->pktout);
  9972. crWaitUntilV(pktin);
  9973. if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
  9974. if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
  9975. bombout(("Unexpected response to shell/command request:"
  9976. " packet type %d", pktin->type));
  9977. crStopV;
  9978. }
  9979. /*
  9980. * We failed to start the command. If this is the
  9981. * fallback command, we really are finished; if it's
  9982. * not, and if the fallback command exists, try falling
  9983. * back to it before complaining.
  9984. */
  9985. if (!ssh->fallback_cmd &&
  9986. (*conf_get_str(ssh->conf, CONF_remote_cmd2)
  9987. #ifdef MPEXT
  9988. ||
  9989. conf_get_int(ssh->conf, CONF_force_remote_cmd2)
  9990. #endif
  9991. )
  9992. ) {
  9993. logevent("Primary command failed; attempting fallback");
  9994. ssh->fallback_cmd = TRUE;
  9995. continue;
  9996. }
  9997. bombout(("Server refused to start a shell/command"));
  9998. crStopV;
  9999. } else {
  10000. logevent("Started a shell/command");
  10001. }
  10002. break;
  10003. }
  10004. } else {
  10005. ssh->editing = ssh->echoing = TRUE;
  10006. }
  10007. ssh->state = SSH_STATE_SESSION;
  10008. if (ssh->size_needed)
  10009. ssh_size(ssh, ssh->term_width, ssh->term_height);
  10010. if (ssh->eof_needed)
  10011. ssh_special(ssh, TS_EOF);
  10012. /*
  10013. * Transfer data!
  10014. */
  10015. if (ssh->ldisc)
  10016. ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
  10017. if (ssh->mainchan)
  10018. ssh->send_ok = 1;
  10019. while (1) {
  10020. crReturnV;
  10021. if (pktin) {
  10022. /*
  10023. * _All_ the connection-layer packets we expect to
  10024. * receive are now handled by the dispatch table.
  10025. * Anything that reaches here must be bogus.
  10026. */
  10027. bombout(("Strange packet received: type %d", pktin->type));
  10028. crStopV;
  10029. } else if (ssh->mainchan) {
  10030. /*
  10031. * We have spare data. Add it to the channel buffer.
  10032. */
  10033. ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
  10034. }
  10035. }
  10036. crFinishV;
  10037. }
  10038. /*
  10039. * Handlers for SSH-2 messages that might arrive at any moment.
  10040. */
  10041. static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
  10042. {
  10043. /* log reason code in disconnect message */
  10044. char *buf, *msg;
  10045. int reason, msglen;
  10046. reason = ssh_pkt_getuint32(pktin);
  10047. ssh_pkt_getstring(pktin, &msg, &msglen);
  10048. if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
  10049. buf = dupprintf("Received disconnect message (%s)",
  10050. ssh2_disconnect_reasons[reason]);
  10051. } else {
  10052. buf = dupprintf("Received disconnect message (unknown"
  10053. " type %d)", reason);
  10054. }
  10055. logevent(buf);
  10056. sfree(buf);
  10057. buf = dupprintf("Disconnection message text: %.*s",
  10058. msglen, NULLTOEMPTY(msg));
  10059. logevent(buf);
  10060. bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
  10061. reason,
  10062. (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
  10063. ssh2_disconnect_reasons[reason] : "unknown",
  10064. msglen, NULLTOEMPTY(msg)));
  10065. sfree(buf);
  10066. }
  10067. static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
  10068. {
  10069. /* log the debug message */
  10070. char *msg;
  10071. int msglen;
  10072. /* XXX maybe we should actually take notice of the return value */
  10073. ssh2_pkt_getbool(pktin);
  10074. ssh_pkt_getstring(pktin, &msg, &msglen);
  10075. logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
  10076. }
  10077. static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
  10078. {
  10079. do_ssh2_transport(ssh, NULL, 0, pktin);
  10080. }
  10081. /*
  10082. * Called if we receive a packet that isn't allowed by the protocol.
  10083. * This only applies to packets whose meaning PuTTY understands.
  10084. * Entirely unknown packets are handled below.
  10085. */
  10086. static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
  10087. {
  10088. char *buf = dupprintf("Server protocol violation: unexpected %s packet",
  10089. ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
  10090. pktin->type));
  10091. ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
  10092. sfree(buf);
  10093. }
  10094. static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
  10095. {
  10096. struct Packet *pktout;
  10097. pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
  10098. ssh2_pkt_adduint32(pktout, pktin->sequence);
  10099. /*
  10100. * UNIMPLEMENTED messages MUST appear in the same order as the
  10101. * messages they respond to. Hence, never queue them.
  10102. */
  10103. ssh2_pkt_send_noqueue(ssh, pktout);
  10104. }
  10105. /*
  10106. * Handle the top-level SSH-2 protocol.
  10107. */
  10108. static void ssh2_protocol_setup(Ssh ssh)
  10109. {
  10110. int i;
  10111. /*
  10112. * Most messages cause SSH2_MSG_UNIMPLEMENTED.
  10113. */
  10114. for (i = 0; i < 256; i++)
  10115. ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
  10116. /*
  10117. * Initially, we only accept transport messages (and a few generic
  10118. * ones). do_ssh2_authconn will add more when it starts.
  10119. * Messages that are understood but not currently acceptable go to
  10120. * ssh2_msg_unexpected.
  10121. */
  10122. ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
  10123. ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
  10124. ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
  10125. ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
  10126. ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
  10127. ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
  10128. ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
  10129. /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
  10130. /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
  10131. ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
  10132. ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
  10133. ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
  10134. ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
  10135. ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
  10136. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
  10137. ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
  10138. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
  10139. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
  10140. ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
  10141. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
  10142. ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
  10143. ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
  10144. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
  10145. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
  10146. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
  10147. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
  10148. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
  10149. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
  10150. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
  10151. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
  10152. ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
  10153. ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
  10154. ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
  10155. /*
  10156. * These messages have a special handler from the start.
  10157. */
  10158. ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
  10159. ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
  10160. ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
  10161. }
  10162. static void ssh2_bare_connection_protocol_setup(Ssh ssh)
  10163. {
  10164. int i;
  10165. /*
  10166. * Most messages cause SSH2_MSG_UNIMPLEMENTED.
  10167. */
  10168. for (i = 0; i < 256; i++)
  10169. ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
  10170. /*
  10171. * Initially, we set all ssh-connection messages to 'unexpected';
  10172. * do_ssh2_authconn will fill things in properly. We also handle a
  10173. * couple of messages from the transport protocol which aren't
  10174. * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
  10175. * DISCONNECT).
  10176. */
  10177. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
  10178. ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
  10179. ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
  10180. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
  10181. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
  10182. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
  10183. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
  10184. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
  10185. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
  10186. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
  10187. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
  10188. ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
  10189. ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
  10190. ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
  10191. ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
  10192. /*
  10193. * These messages have a special handler from the start.
  10194. */
  10195. ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
  10196. ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
  10197. ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
  10198. }
  10199. static void ssh2_timer(void *ctx, unsigned long now)
  10200. {
  10201. Ssh ssh = (Ssh)ctx;
  10202. if (ssh->state == SSH_STATE_CLOSED)
  10203. return;
  10204. if (!ssh->kex_in_progress && !ssh->bare_connection &&
  10205. conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
  10206. #ifdef MPEXT
  10207. // our call from call_ssh_timer() does not guarantee the `now` to be exactly as scheduled
  10208. (now >= ssh->next_rekey)) {
  10209. #else
  10210. now == ssh->next_rekey) {
  10211. #endif
  10212. do_ssh2_transport(ssh, "timeout", -1, NULL);
  10213. }
  10214. }
  10215. static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
  10216. struct Packet *pktin)
  10217. {
  10218. const unsigned char *in = (const unsigned char *)vin;
  10219. if (ssh->state == SSH_STATE_CLOSED)
  10220. return;
  10221. if (pktin) {
  10222. ssh->incoming_data_size += pktin->encrypted_len;
  10223. if (!ssh->kex_in_progress &&
  10224. ssh->max_data_size != 0 &&
  10225. ssh->incoming_data_size > ssh->max_data_size)
  10226. do_ssh2_transport(ssh, "too much data received", -1, NULL);
  10227. }
  10228. if (pktin)
  10229. ssh->packet_dispatch[pktin->type](ssh, pktin);
  10230. else if (!ssh->protocol_initial_phase_done)
  10231. do_ssh2_transport(ssh, in, inlen, pktin);
  10232. else
  10233. do_ssh2_authconn(ssh, in, inlen, pktin);
  10234. }
  10235. static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
  10236. struct Packet *pktin)
  10237. {
  10238. const unsigned char *in = (const unsigned char *)vin;
  10239. if (ssh->state == SSH_STATE_CLOSED)
  10240. return;
  10241. if (pktin)
  10242. ssh->packet_dispatch[pktin->type](ssh, pktin);
  10243. else
  10244. do_ssh2_authconn(ssh, in, inlen, pktin);
  10245. }
  10246. static void ssh_cache_conf_values(Ssh ssh)
  10247. {
  10248. ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
  10249. }
  10250. /*
  10251. * Called to set up the connection.
  10252. *
  10253. * Returns an error message, or NULL on success.
  10254. */
  10255. static const char *ssh_init(void *frontend_handle, void **backend_handle,
  10256. Conf *conf,
  10257. const char *host, int port, char **realhost,
  10258. int nodelay, int keepalive)
  10259. {
  10260. const char *p;
  10261. Ssh ssh;
  10262. ssh = snew(struct ssh_tag);
  10263. ssh->conf = conf_copy(conf);
  10264. ssh_cache_conf_values(ssh);
  10265. ssh->version = 0; /* when not ready yet */
  10266. ssh->s = NULL;
  10267. ssh->cipher = NULL;
  10268. ssh->v1_cipher_ctx = NULL;
  10269. ssh->crcda_ctx = NULL;
  10270. ssh->cscipher = NULL;
  10271. ssh->cs_cipher_ctx = NULL;
  10272. ssh->sccipher = NULL;
  10273. ssh->sc_cipher_ctx = NULL;
  10274. ssh->csmac = NULL;
  10275. ssh->cs_mac_ctx = NULL;
  10276. ssh->scmac = NULL;
  10277. ssh->sc_mac_ctx = NULL;
  10278. ssh->cscomp = NULL;
  10279. ssh->cs_comp_ctx = NULL;
  10280. ssh->sccomp = NULL;
  10281. ssh->sc_comp_ctx = NULL;
  10282. ssh->kex = NULL;
  10283. ssh->kex_ctx = NULL;
  10284. ssh->hostkey = NULL;
  10285. ssh->hostkey_str = NULL;
  10286. ssh->exitcode = -1;
  10287. ssh->close_expected = FALSE;
  10288. ssh->clean_exit = FALSE;
  10289. ssh->state = SSH_STATE_PREPACKET;
  10290. ssh->size_needed = FALSE;
  10291. ssh->eof_needed = FALSE;
  10292. ssh->ldisc = NULL;
  10293. ssh->logctx = NULL;
  10294. ssh->deferred_send_data = NULL;
  10295. ssh->deferred_len = 0;
  10296. ssh->deferred_size = 0;
  10297. ssh->fallback_cmd = 0;
  10298. ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
  10299. ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
  10300. ssh->x11disp = NULL;
  10301. ssh->x11auth = NULL;
  10302. ssh->x11authtree = newtree234(x11_authcmp);
  10303. ssh->v1_compressing = FALSE;
  10304. ssh->v2_outgoing_sequence = 0;
  10305. ssh->ssh1_rdpkt_crstate = 0;
  10306. ssh->ssh2_rdpkt_crstate = 0;
  10307. ssh->ssh2_bare_rdpkt_crstate = 0;
  10308. ssh->ssh_gotdata_crstate = 0;
  10309. ssh->do_ssh1_connection_crstate = 0;
  10310. ssh->do_ssh_init_state = NULL;
  10311. ssh->do_ssh_connection_init_state = NULL;
  10312. ssh->do_ssh1_login_state = NULL;
  10313. ssh->do_ssh2_transport_state = NULL;
  10314. ssh->do_ssh2_authconn_state = NULL;
  10315. ssh->v_c = NULL;
  10316. ssh->v_s = NULL;
  10317. ssh->mainchan = NULL;
  10318. ssh->throttled_all = 0;
  10319. ssh->v1_stdout_throttling = 0;
  10320. ssh->queue = NULL;
  10321. ssh->queuelen = ssh->queuesize = 0;
  10322. ssh->queueing = FALSE;
  10323. ssh->qhead = ssh->qtail = NULL;
  10324. ssh->deferred_rekey_reason = NULL;
  10325. bufchain_init(&ssh->queued_incoming_data);
  10326. ssh->frozen = FALSE;
  10327. ssh->username = NULL;
  10328. ssh->sent_console_eof = FALSE;
  10329. ssh->got_pty = FALSE;
  10330. ssh->bare_connection = FALSE;
  10331. ssh->X11_fwd_enabled = FALSE;
  10332. ssh->connshare = NULL;
  10333. ssh->attempting_connshare = FALSE;
  10334. ssh->session_started = FALSE;
  10335. ssh->specials = NULL;
  10336. ssh->n_uncert_hostkeys = 0;
  10337. ssh->cross_certifying = FALSE;
  10338. *backend_handle = ssh;
  10339. #ifdef MPEXT
  10340. // random_unref is always called from ssh_free,
  10341. // so we must call random_ref also always, even if we fail, to match it
  10342. random_ref();
  10343. #endif
  10344. #ifdef MSCRYPTOAPI
  10345. if (crypto_startup() == 0)
  10346. return "Microsoft high encryption pack not installed!";
  10347. #endif
  10348. ssh->frontend = frontend_handle;
  10349. ssh->term_width = conf_get_int(ssh->conf, CONF_width);
  10350. ssh->term_height = conf_get_int(ssh->conf, CONF_height);
  10351. ssh->channels = NULL;
  10352. ssh->rportfwds = NULL;
  10353. ssh->portfwds = NULL;
  10354. ssh->send_ok = 0;
  10355. ssh->editing = 0;
  10356. ssh->echoing = 0;
  10357. ssh->conn_throttle_count = 0;
  10358. ssh->overall_bufsize = 0;
  10359. ssh->fallback_cmd = 0;
  10360. ssh->protocol = NULL;
  10361. ssh->protocol_initial_phase_done = FALSE;
  10362. ssh->pinger = NULL;
  10363. ssh->incoming_data_size = ssh->outgoing_data_size =
  10364. ssh->deferred_data_size = 0L;
  10365. ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
  10366. CONF_ssh_rekey_data));
  10367. ssh->kex_in_progress = FALSE;
  10368. ssh->auth_agent_query = NULL;
  10369. #ifndef NO_GSSAPI
  10370. ssh->gsslibs = NULL;
  10371. #endif
  10372. random_ref(); /* do this now - may be needed by sharing setup code */
  10373. p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
  10374. if (p != NULL) {
  10375. random_unref();
  10376. return p;
  10377. }
  10378. random_ref();
  10379. return NULL;
  10380. }
  10381. static void ssh_free(void *handle)
  10382. {
  10383. Ssh ssh = (Ssh) handle;
  10384. struct ssh_channel *c;
  10385. struct ssh_rportfwd *pf;
  10386. struct X11FakeAuth *auth;
  10387. if (ssh->v1_cipher_ctx)
  10388. ssh->cipher->free_context(ssh->v1_cipher_ctx);
  10389. if (ssh->cs_cipher_ctx)
  10390. ssh->cscipher->free_context(ssh->cs_cipher_ctx);
  10391. if (ssh->sc_cipher_ctx)
  10392. ssh->sccipher->free_context(ssh->sc_cipher_ctx);
  10393. if (ssh->cs_mac_ctx)
  10394. ssh->csmac->free_context(ssh->cs_mac_ctx);
  10395. if (ssh->sc_mac_ctx)
  10396. ssh->scmac->free_context(ssh->sc_mac_ctx);
  10397. if (ssh->cs_comp_ctx) {
  10398. if (ssh->cscomp)
  10399. ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
  10400. else
  10401. zlib_compress_cleanup(ssh->cs_comp_ctx);
  10402. }
  10403. if (ssh->sc_comp_ctx) {
  10404. if (ssh->sccomp)
  10405. ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
  10406. else
  10407. zlib_decompress_cleanup(ssh->sc_comp_ctx);
  10408. }
  10409. if (ssh->kex_ctx)
  10410. dh_cleanup(ssh->kex_ctx);
  10411. sfree(ssh->savedhost);
  10412. while (ssh->queuelen-- > 0)
  10413. ssh_free_packet(ssh->queue[ssh->queuelen]);
  10414. sfree(ssh->queue);
  10415. while (ssh->qhead) {
  10416. struct queued_handler *qh = ssh->qhead;
  10417. ssh->qhead = qh->next;
  10418. sfree(qh);
  10419. }
  10420. ssh->qhead = ssh->qtail = NULL;
  10421. if (ssh->channels) {
  10422. while ((c = delpos234(ssh->channels, 0)) != NULL) {
  10423. ssh_channel_close_local(c, NULL);
  10424. if (ssh->version == 2) {
  10425. struct outstanding_channel_request *ocr, *nocr;
  10426. ocr = c->v.v2.chanreq_head;
  10427. while (ocr) {
  10428. ocr->handler(c, NULL, ocr->ctx);
  10429. nocr = ocr->next;
  10430. sfree(ocr);
  10431. ocr = nocr;
  10432. }
  10433. bufchain_clear(&c->v.v2.outbuffer);
  10434. }
  10435. sfree(c);
  10436. }
  10437. freetree234(ssh->channels);
  10438. ssh->channels = NULL;
  10439. }
  10440. if (ssh->connshare)
  10441. sharestate_free(ssh->connshare);
  10442. if (ssh->rportfwds) {
  10443. while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
  10444. free_rportfwd(pf);
  10445. freetree234(ssh->rportfwds);
  10446. ssh->rportfwds = NULL;
  10447. }
  10448. sfree(ssh->deferred_send_data);
  10449. if (ssh->x11disp)
  10450. x11_free_display(ssh->x11disp);
  10451. while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
  10452. x11_free_fake_auth(auth);
  10453. freetree234(ssh->x11authtree);
  10454. sfree(ssh->do_ssh_init_state);
  10455. sfree(ssh->do_ssh1_login_state);
  10456. sfree(ssh->do_ssh2_transport_state);
  10457. sfree(ssh->do_ssh2_authconn_state);
  10458. sfree(ssh->v_c);
  10459. sfree(ssh->v_s);
  10460. sfree(ssh->fullhostname);
  10461. sfree(ssh->hostkey_str);
  10462. sfree(ssh->specials);
  10463. if (ssh->crcda_ctx) {
  10464. crcda_free_context(ssh->crcda_ctx);
  10465. ssh->crcda_ctx = NULL;
  10466. }
  10467. if (ssh->s)
  10468. ssh_do_close(ssh, TRUE);
  10469. expire_timer_context(ssh);
  10470. if (ssh->pinger)
  10471. pinger_free(ssh->pinger);
  10472. bufchain_clear(&ssh->queued_incoming_data);
  10473. sfree(ssh->username);
  10474. conf_free(ssh->conf);
  10475. if (ssh->auth_agent_query)
  10476. agent_cancel_query(ssh->auth_agent_query);
  10477. #ifndef NO_GSSAPI
  10478. if (ssh->gsslibs)
  10479. ssh_gss_cleanup(ssh->gsslibs);
  10480. #endif
  10481. sfree(ssh);
  10482. random_unref();
  10483. }
  10484. /*
  10485. * Reconfigure the SSH backend.
  10486. */
  10487. static void ssh_reconfig(void *handle, Conf *conf)
  10488. {
  10489. Ssh ssh = (Ssh) handle;
  10490. const char *rekeying = NULL;
  10491. int rekey_mandatory = FALSE;
  10492. unsigned long old_max_data_size;
  10493. int i, rekey_time;
  10494. pinger_reconfig(ssh->pinger, ssh->conf, conf);
  10495. if (ssh->portfwds)
  10496. ssh_setup_portfwd(ssh, conf);
  10497. rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
  10498. if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
  10499. rekey_time != 0) {
  10500. unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
  10501. unsigned long now = GETTICKCOUNT();
  10502. if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
  10503. rekeying = "timeout shortened";
  10504. } else {
  10505. ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
  10506. }
  10507. }
  10508. old_max_data_size = ssh->max_data_size;
  10509. ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
  10510. CONF_ssh_rekey_data));
  10511. if (old_max_data_size != ssh->max_data_size &&
  10512. ssh->max_data_size != 0) {
  10513. if (ssh->outgoing_data_size > ssh->max_data_size ||
  10514. ssh->incoming_data_size > ssh->max_data_size)
  10515. rekeying = "data limit lowered";
  10516. }
  10517. if (conf_get_int(ssh->conf, CONF_compression) !=
  10518. conf_get_int(conf, CONF_compression)) {
  10519. rekeying = "compression setting changed";
  10520. rekey_mandatory = TRUE;
  10521. }
  10522. for (i = 0; i < CIPHER_MAX; i++)
  10523. if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
  10524. conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
  10525. rekeying = "cipher settings changed";
  10526. rekey_mandatory = TRUE;
  10527. }
  10528. if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
  10529. conf_get_int(conf, CONF_ssh2_des_cbc)) {
  10530. rekeying = "cipher settings changed";
  10531. rekey_mandatory = TRUE;
  10532. }
  10533. conf_free(ssh->conf);
  10534. ssh->conf = conf_copy(conf);
  10535. ssh_cache_conf_values(ssh);
  10536. if (!ssh->bare_connection && rekeying) {
  10537. if (!ssh->kex_in_progress) {
  10538. do_ssh2_transport(ssh, rekeying, -1, NULL);
  10539. } else if (rekey_mandatory) {
  10540. ssh->deferred_rekey_reason = rekeying;
  10541. }
  10542. }
  10543. }
  10544. /*
  10545. * Called to send data down the SSH connection.
  10546. */
  10547. static int ssh_send(void *handle, const char *buf, int len)
  10548. {
  10549. Ssh ssh = (Ssh) handle;
  10550. if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
  10551. return 0;
  10552. ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
  10553. return ssh_sendbuffer(ssh);
  10554. }
  10555. /*
  10556. * Called to query the current amount of buffered stdin data.
  10557. */
  10558. static int ssh_sendbuffer(void *handle)
  10559. {
  10560. Ssh ssh = (Ssh) handle;
  10561. int override_value;
  10562. if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
  10563. return 0;
  10564. /*
  10565. * If the SSH socket itself has backed up, add the total backup
  10566. * size on that to any individual buffer on the stdin channel.
  10567. */
  10568. override_value = 0;
  10569. if (ssh->throttled_all)
  10570. override_value = ssh->overall_bufsize;
  10571. if (ssh->version == 1) {
  10572. return override_value;
  10573. } else if (ssh->version == 2) {
  10574. if (!ssh->mainchan)
  10575. return override_value;
  10576. else
  10577. return (override_value +
  10578. bufchain_size(&ssh->mainchan->v.v2.outbuffer));
  10579. }
  10580. return 0;
  10581. }
  10582. /*
  10583. * Called to set the size of the window from SSH's POV.
  10584. */
  10585. static void ssh_size(void *handle, int width, int height)
  10586. {
  10587. Ssh ssh = (Ssh) handle;
  10588. struct Packet *pktout;
  10589. ssh->term_width = width;
  10590. ssh->term_height = height;
  10591. switch (ssh->state) {
  10592. case SSH_STATE_BEFORE_SIZE:
  10593. case SSH_STATE_PREPACKET:
  10594. case SSH_STATE_CLOSED:
  10595. break; /* do nothing */
  10596. case SSH_STATE_INTERMED:
  10597. ssh->size_needed = TRUE; /* buffer for later */
  10598. break;
  10599. case SSH_STATE_SESSION:
  10600. if (!conf_get_int(ssh->conf, CONF_nopty)) {
  10601. if (ssh->version == 1) {
  10602. send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
  10603. PKT_INT, ssh->term_height,
  10604. PKT_INT, ssh->term_width,
  10605. PKT_INT, 0, PKT_INT, 0, PKT_END);
  10606. } else if (ssh->mainchan) {
  10607. pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
  10608. NULL, NULL);
  10609. ssh2_pkt_adduint32(pktout, ssh->term_width);
  10610. ssh2_pkt_adduint32(pktout, ssh->term_height);
  10611. ssh2_pkt_adduint32(pktout, 0);
  10612. ssh2_pkt_adduint32(pktout, 0);
  10613. ssh2_pkt_send(ssh, pktout);
  10614. }
  10615. }
  10616. break;
  10617. }
  10618. }
  10619. /*
  10620. * Return a list of the special codes that make sense in this
  10621. * protocol.
  10622. */
  10623. static const struct telnet_special *ssh_get_specials(void *handle)
  10624. {
  10625. static const struct telnet_special ssh1_ignore_special[] = {
  10626. {"IGNORE message", TS_NOP}
  10627. };
  10628. static const struct telnet_special ssh2_ignore_special[] = {
  10629. {"IGNORE message", TS_NOP},
  10630. };
  10631. static const struct telnet_special ssh2_rekey_special[] = {
  10632. {"Repeat key exchange", TS_REKEY},
  10633. };
  10634. static const struct telnet_special ssh2_session_specials[] = {
  10635. {NULL, TS_SEP},
  10636. {"Break", TS_BRK},
  10637. /* These are the signal names defined by RFC 4254.
  10638. * They include all the ISO C signals, but are a subset of the POSIX
  10639. * required signals. */
  10640. {"SIGINT (Interrupt)", TS_SIGINT},
  10641. {"SIGTERM (Terminate)", TS_SIGTERM},
  10642. {"SIGKILL (Kill)", TS_SIGKILL},
  10643. {"SIGQUIT (Quit)", TS_SIGQUIT},
  10644. {"SIGHUP (Hangup)", TS_SIGHUP},
  10645. {"More signals", TS_SUBMENU},
  10646. {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
  10647. {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
  10648. {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
  10649. {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
  10650. {NULL, TS_EXITMENU}
  10651. };
  10652. static const struct telnet_special specials_end[] = {
  10653. {NULL, TS_EXITMENU}
  10654. };
  10655. struct telnet_special *specials = NULL;
  10656. int nspecials = 0, specialsize = 0;
  10657. Ssh ssh = (Ssh) handle;
  10658. sfree(ssh->specials);
  10659. #define ADD_SPECIALS(name) do \
  10660. { \
  10661. int len = lenof(name); \
  10662. if (nspecials + len > specialsize) { \
  10663. specialsize = (nspecials + len) * 5 / 4 + 32; \
  10664. specials = sresize(specials, specialsize, struct telnet_special); \
  10665. } \
  10666. memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
  10667. nspecials += len; \
  10668. } while (0)
  10669. if (ssh->version == 1) {
  10670. /* Don't bother offering IGNORE if we've decided the remote
  10671. * won't cope with it, since we wouldn't bother sending it if
  10672. * asked anyway. */
  10673. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
  10674. ADD_SPECIALS(ssh1_ignore_special);
  10675. } else if (ssh->version == 2) {
  10676. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
  10677. ADD_SPECIALS(ssh2_ignore_special);
  10678. if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
  10679. ADD_SPECIALS(ssh2_rekey_special);
  10680. if (ssh->mainchan)
  10681. ADD_SPECIALS(ssh2_session_specials);
  10682. if (ssh->n_uncert_hostkeys) {
  10683. static const struct telnet_special uncert_start[] = {
  10684. {NULL, TS_SEP},
  10685. {"Cache new host key type", TS_SUBMENU},
  10686. };
  10687. static const struct telnet_special uncert_end[] = {
  10688. {NULL, TS_EXITMENU},
  10689. };
  10690. int i;
  10691. ADD_SPECIALS(uncert_start);
  10692. for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
  10693. struct telnet_special uncert[1];
  10694. const struct ssh_signkey *alg =
  10695. hostkey_algs[ssh->uncert_hostkeys[i]].alg;
  10696. uncert[0].name = alg->name;
  10697. uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
  10698. ADD_SPECIALS(uncert);
  10699. }
  10700. ADD_SPECIALS(uncert_end);
  10701. }
  10702. } /* else we're not ready yet */
  10703. if (nspecials)
  10704. ADD_SPECIALS(specials_end);
  10705. ssh->specials = specials;
  10706. if (nspecials) {
  10707. return specials;
  10708. } else {
  10709. return NULL;
  10710. }
  10711. #undef ADD_SPECIALS
  10712. }
  10713. /*
  10714. * Send special codes. TS_EOF is useful for `plink', so you
  10715. * can send an EOF and collect resulting output (e.g. `plink
  10716. * hostname sort').
  10717. */
  10718. static void ssh_special(void *handle, Telnet_Special code)
  10719. {
  10720. Ssh ssh = (Ssh) handle;
  10721. struct Packet *pktout;
  10722. if (code == TS_EOF) {
  10723. if (ssh->state != SSH_STATE_SESSION) {
  10724. /*
  10725. * Buffer the EOF in case we are pre-SESSION, so we can
  10726. * send it as soon as we reach SESSION.
  10727. */
  10728. if (code == TS_EOF)
  10729. ssh->eof_needed = TRUE;
  10730. return;
  10731. }
  10732. if (ssh->version == 1) {
  10733. send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
  10734. } else if (ssh->mainchan) {
  10735. sshfwd_write_eof(ssh->mainchan);
  10736. ssh->send_ok = 0; /* now stop trying to read from stdin */
  10737. }
  10738. logevent("Sent EOF message");
  10739. } else if (code == TS_PING || code == TS_NOP) {
  10740. if (ssh->state == SSH_STATE_CLOSED
  10741. || ssh->state == SSH_STATE_PREPACKET) return;
  10742. if (ssh->version == 1) {
  10743. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
  10744. send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
  10745. } else {
  10746. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
  10747. pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
  10748. ssh2_pkt_addstring_start(pktout);
  10749. ssh2_pkt_send_noqueue(ssh, pktout);
  10750. }
  10751. }
  10752. } else if (code == TS_REKEY) {
  10753. if (!ssh->kex_in_progress && !ssh->bare_connection &&
  10754. ssh->version == 2) {
  10755. do_ssh2_transport(ssh, "at user request", -1, NULL);
  10756. }
  10757. } else if (code >= TS_LOCALSTART) {
  10758. ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
  10759. ssh->cross_certifying = TRUE;
  10760. if (!ssh->kex_in_progress && !ssh->bare_connection &&
  10761. ssh->version == 2) {
  10762. do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
  10763. }
  10764. } else if (code == TS_BRK) {
  10765. if (ssh->state == SSH_STATE_CLOSED
  10766. || ssh->state == SSH_STATE_PREPACKET) return;
  10767. if (ssh->version == 1) {
  10768. logevent("Unable to send BREAK signal in SSH-1");
  10769. } else if (ssh->mainchan) {
  10770. pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
  10771. ssh2_pkt_adduint32(pktout, 0); /* default break length */
  10772. ssh2_pkt_send(ssh, pktout);
  10773. }
  10774. } else {
  10775. /* Is is a POSIX signal? */
  10776. const char *signame = NULL;
  10777. if (code == TS_SIGABRT) signame = "ABRT";
  10778. if (code == TS_SIGALRM) signame = "ALRM";
  10779. if (code == TS_SIGFPE) signame = "FPE";
  10780. if (code == TS_SIGHUP) signame = "HUP";
  10781. if (code == TS_SIGILL) signame = "ILL";
  10782. if (code == TS_SIGINT) signame = "INT";
  10783. if (code == TS_SIGKILL) signame = "KILL";
  10784. if (code == TS_SIGPIPE) signame = "PIPE";
  10785. if (code == TS_SIGQUIT) signame = "QUIT";
  10786. if (code == TS_SIGSEGV) signame = "SEGV";
  10787. if (code == TS_SIGTERM) signame = "TERM";
  10788. if (code == TS_SIGUSR1) signame = "USR1";
  10789. if (code == TS_SIGUSR2) signame = "USR2";
  10790. /* The SSH-2 protocol does in principle support arbitrary named
  10791. * signals, including signame@domain, but we don't support those. */
  10792. if (signame) {
  10793. /* It's a signal. */
  10794. if (ssh->version == 2 && ssh->mainchan) {
  10795. pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
  10796. ssh2_pkt_addstring(pktout, signame);
  10797. ssh2_pkt_send(ssh, pktout);
  10798. logeventf(ssh, "Sent signal SIG%s", signame);
  10799. }
  10800. } else {
  10801. /* Never heard of it. Do nothing */
  10802. }
  10803. }
  10804. }
  10805. void *new_sock_channel(void *handle, struct PortForwarding *pf)
  10806. {
  10807. Ssh ssh = (Ssh) handle;
  10808. struct ssh_channel *c;
  10809. c = snew(struct ssh_channel);
  10810. c->ssh = ssh;
  10811. ssh_channel_init(c);
  10812. c->halfopen = TRUE;
  10813. c->type = CHAN_SOCKDATA;/* identify channel type */
  10814. c->u.pfd.pf = pf;
  10815. return c;
  10816. }
  10817. unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
  10818. {
  10819. struct ssh_channel *c;
  10820. c = snew(struct ssh_channel);
  10821. c->ssh = ssh;
  10822. ssh_channel_init(c);
  10823. c->type = CHAN_SHARING;
  10824. c->u.sharing.ctx = sharing_ctx;
  10825. return c->localid;
  10826. }
  10827. void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
  10828. {
  10829. struct ssh_channel *c;
  10830. c = find234(ssh->channels, &localid, ssh_channelfind);
  10831. if (c)
  10832. ssh_channel_destroy(c);
  10833. }
  10834. void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
  10835. const void *data, int datalen,
  10836. const char *additional_log_text)
  10837. {
  10838. struct Packet *pkt;
  10839. pkt = ssh2_pkt_init(type);
  10840. pkt->downstream_id = id;
  10841. pkt->additional_log_text = additional_log_text;
  10842. ssh2_pkt_adddata(pkt, data, datalen);
  10843. ssh2_pkt_send(ssh, pkt);
  10844. }
  10845. /*
  10846. * This is called when stdout/stderr (the entity to which
  10847. * from_backend sends data) manages to clear some backlog.
  10848. */
  10849. static void ssh_unthrottle(void *handle, int bufsize)
  10850. {
  10851. Ssh ssh = (Ssh) handle;
  10852. if (ssh->version == 1) {
  10853. if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
  10854. ssh->v1_stdout_throttling = 0;
  10855. ssh_throttle_conn(ssh, -1);
  10856. }
  10857. } else {
  10858. if (ssh->mainchan)
  10859. ssh_channel_unthrottle(ssh->mainchan, bufsize);
  10860. }
  10861. /*
  10862. * Now process any SSH connection data that was stashed in our
  10863. * queue while we were frozen.
  10864. */
  10865. ssh_process_queued_incoming_data(ssh);
  10866. }
  10867. void ssh_send_port_open(void *channel, const char *hostname, int port,
  10868. const char *org)
  10869. {
  10870. struct ssh_channel *c = (struct ssh_channel *)channel;
  10871. Ssh ssh = c->ssh;
  10872. struct Packet *pktout;
  10873. logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
  10874. if (ssh->version == 1) {
  10875. send_packet(ssh, SSH1_MSG_PORT_OPEN,
  10876. PKT_INT, c->localid,
  10877. PKT_STR, hostname,
  10878. PKT_INT, port,
  10879. /* PKT_STR, <org:orgport>, */
  10880. PKT_END);
  10881. } else {
  10882. pktout = ssh2_chanopen_init(c, "direct-tcpip");
  10883. {
  10884. char *trimmed_host = host_strduptrim(hostname);
  10885. ssh2_pkt_addstring(pktout, trimmed_host);
  10886. sfree(trimmed_host);
  10887. }
  10888. ssh2_pkt_adduint32(pktout, port);
  10889. /*
  10890. * We make up values for the originator data; partly it's
  10891. * too much hassle to keep track, and partly I'm not
  10892. * convinced the server should be told details like that
  10893. * about my local network configuration.
  10894. * The "originator IP address" is syntactically a numeric
  10895. * IP address, and some servers (e.g., Tectia) get upset
  10896. * if it doesn't match this syntax.
  10897. */
  10898. ssh2_pkt_addstring(pktout, "0.0.0.0");
  10899. ssh2_pkt_adduint32(pktout, 0);
  10900. ssh2_pkt_send(ssh, pktout);
  10901. }
  10902. }
  10903. static int ssh_connected(void *handle)
  10904. {
  10905. Ssh ssh = (Ssh) handle;
  10906. return ssh->s != NULL;
  10907. }
  10908. static int ssh_sendok(void *handle)
  10909. {
  10910. Ssh ssh = (Ssh) handle;
  10911. return ssh->send_ok;
  10912. }
  10913. static int ssh_ldisc(void *handle, int option)
  10914. {
  10915. Ssh ssh = (Ssh) handle;
  10916. if (option == LD_ECHO)
  10917. return ssh->echoing;
  10918. if (option == LD_EDIT)
  10919. return ssh->editing;
  10920. return FALSE;
  10921. }
  10922. static void ssh_provide_ldisc(void *handle, void *ldisc)
  10923. {
  10924. Ssh ssh = (Ssh) handle;
  10925. ssh->ldisc = ldisc;
  10926. }
  10927. static void ssh_provide_logctx(void *handle, void *logctx)
  10928. {
  10929. Ssh ssh = (Ssh) handle;
  10930. ssh->logctx = logctx;
  10931. }
  10932. static int ssh_return_exitcode(void *handle)
  10933. {
  10934. Ssh ssh = (Ssh) handle;
  10935. if (ssh->s != NULL)
  10936. return -1;
  10937. else
  10938. return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
  10939. }
  10940. /*
  10941. * cfg_info for SSH is the protocol running in this session.
  10942. * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
  10943. * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
  10944. */
  10945. static int ssh_cfg_info(void *handle)
  10946. {
  10947. Ssh ssh = (Ssh) handle;
  10948. if (ssh->version == 0)
  10949. return 0; /* don't know yet */
  10950. else if (ssh->bare_connection)
  10951. return -1;
  10952. else
  10953. return ssh->version;
  10954. }
  10955. /*
  10956. * Gross hack: pscp will try to start SFTP but fall back to scp1 if
  10957. * that fails. This variable is the means by which scp.c can reach
  10958. * into the SSH code and find out which one it got.
  10959. */
  10960. extern int ssh_fallback_cmd(void *handle)
  10961. {
  10962. Ssh ssh = (Ssh) handle;
  10963. return ssh->fallback_cmd;
  10964. }
  10965. Backend ssh_backend = {
  10966. ssh_init,
  10967. ssh_free,
  10968. ssh_reconfig,
  10969. ssh_send,
  10970. ssh_sendbuffer,
  10971. ssh_size,
  10972. ssh_special,
  10973. ssh_get_specials,
  10974. ssh_connected,
  10975. ssh_return_exitcode,
  10976. ssh_sendok,
  10977. ssh_ldisc,
  10978. ssh_provide_ldisc,
  10979. ssh_provide_logctx,
  10980. ssh_unthrottle,
  10981. ssh_cfg_info,
  10982. ssh_test_for_upstream,
  10983. "ssh",
  10984. PROT_SSH,
  10985. 22
  10986. };
  10987. #ifdef MPEXT
  10988. #include "puttyexp.h"
  10989. void ssh_close(void * handle)
  10990. {
  10991. ssh_do_close((Ssh)handle, FALSE);
  10992. }
  10993. int is_ssh(void * handle)
  10994. {
  10995. Plug fn = (Plug)handle;
  10996. return (*fn)->closing == ssh_closing;
  10997. }
  10998. void call_ssh_timer(void * handle)
  10999. {
  11000. if (((Ssh)handle)->version == 2)
  11001. {
  11002. ssh2_timer(handle, GETTICKCOUNT());
  11003. }
  11004. }
  11005. int get_ssh_version(void * handle)
  11006. {
  11007. return ((Ssh)handle)->version;
  11008. }
  11009. void * get_ssh_frontend(void * handle)
  11010. {
  11011. return ((Ssh)handle)->frontend;
  11012. }
  11013. int get_ssh1_compressing(void * handle)
  11014. {
  11015. return ((Ssh)handle)->v1_compressing;
  11016. }
  11017. const struct ssh_cipher * get_cipher(void * handle)
  11018. {
  11019. return ((Ssh)handle)->cipher;
  11020. }
  11021. const struct ssh2_cipher * get_cscipher(void * handle)
  11022. {
  11023. return ((Ssh)handle)->cscipher;
  11024. }
  11025. const struct ssh2_cipher * get_sccipher(void * handle)
  11026. {
  11027. return ((Ssh)handle)->sccipher;
  11028. }
  11029. const struct ssh_compress * get_cscomp(void * handle)
  11030. {
  11031. return ((Ssh)handle)->cscomp;
  11032. }
  11033. const struct ssh_compress * get_sccomp(void * handle)
  11034. {
  11035. return ((Ssh)handle)->sccomp;
  11036. }
  11037. int get_ssh_state(void * handle)
  11038. {
  11039. return ((Ssh)handle)->state;
  11040. }
  11041. int get_ssh_state_closed(void * handle)
  11042. {
  11043. return ((Ssh)handle)->state == SSH_STATE_CLOSED;
  11044. }
  11045. int get_ssh_state_session(void * handle)
  11046. {
  11047. return ((Ssh)handle)->state == SSH_STATE_SESSION;
  11048. }
  11049. int get_ssh_exitcode(void * handle)
  11050. {
  11051. return ssh_return_exitcode(handle);
  11052. }
  11053. const unsigned int * ssh2_remmaxpkt(void * handle)
  11054. {
  11055. return &((Ssh)handle)->mainchan->v.v2.remmaxpkt;
  11056. }
  11057. const unsigned int * ssh2_remwindow(void * handle)
  11058. {
  11059. return &((Ssh)handle)->mainchan->v.v2.remwindow;
  11060. }
  11061. void md5checksum(const char * buffer, int len, unsigned char output[16])
  11062. {
  11063. struct MD5Context md5c;
  11064. MD5Init(&md5c);
  11065. MD5Update(&md5c, buffer, len);
  11066. MD5Final(output, &md5c);
  11067. }
  11068. void get_hostkey_algs(int * count, cp_ssh_signkey * SignKeys)
  11069. {
  11070. int i;
  11071. assert(lenof(hostkey_algs) <= *count);
  11072. *count = lenof(hostkey_algs);
  11073. for (i = 0; i < *count; i++)
  11074. {
  11075. *(SignKeys + i) = hostkey_algs[i].alg;
  11076. }
  11077. }
  11078. void get_macs(int * count, const struct ssh_mac *** amacs)
  11079. {
  11080. *amacs = macs;
  11081. *count = lenof(macs);
  11082. }
  11083. #endif