channels.c 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019
  1. /* $OpenBSD: channels.c,v 1.402 2020/09/20 05:47:25 djm Exp $ */
  2. /*
  3. * Author: Tatu Ylonen <ylo@cs.hut.fi>
  4. * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
  5. * All rights reserved
  6. * This file contains functions for generic socket connection forwarding.
  7. * There is also code for initiating connection forwarding for X11 connections,
  8. * arbitrary tcp/ip connections, and the authentication agent connection.
  9. *
  10. * As far as I am concerned, the code I have written for this software
  11. * can be used freely for any purpose. Any derived versions of this
  12. * software must be clearly marked as such, and if the derived work is
  13. * incompatible with the protocol description in the RFC file, it must be
  14. * called by a name other than "ssh" or "Secure Shell".
  15. *
  16. * SSH2 support added by Markus Friedl.
  17. * Copyright (c) 1999, 2000, 2001, 2002 Markus Friedl. All rights reserved.
  18. * Copyright (c) 1999 Dug Song. All rights reserved.
  19. * Copyright (c) 1999 Theo de Raadt. All rights reserved.
  20. *
  21. * Redistribution and use in source and binary forms, with or without
  22. * modification, are permitted provided that the following conditions
  23. * are met:
  24. * 1. Redistributions of source code must retain the above copyright
  25. * notice, this list of conditions and the following disclaimer.
  26. * 2. Redistributions in binary form must reproduce the above copyright
  27. * notice, this list of conditions and the following disclaimer in the
  28. * documentation and/or other materials provided with the distribution.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  31. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  33. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  34. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  35. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  36. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  37. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  38. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  39. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  40. */
  41. #include "includes.h"
  42. #include <sys/types.h>
  43. #include <sys/stat.h>
  44. #include <sys/ioctl.h>
  45. #include <sys/un.h>
  46. #include <sys/socket.h>
  47. #ifdef HAVE_SYS_TIME_H
  48. # include <sys/time.h>
  49. #endif
  50. #include <netinet/in.h>
  51. #include <arpa/inet.h>
  52. #include <errno.h>
  53. #include <fcntl.h>
  54. #include <limits.h>
  55. #include <netdb.h>
  56. #include <stdarg.h>
  57. #ifdef HAVE_STDINT_H
  58. # include <stdint.h>
  59. #endif
  60. #include <stdio.h>
  61. #include <stdlib.h>
  62. #include <string.h>
  63. #include <termios.h>
  64. #include <unistd.h>
  65. #include "openbsd-compat/sys-queue.h"
  66. #include "xmalloc.h"
  67. #include "ssh.h"
  68. #include "ssh2.h"
  69. #include "ssherr.h"
  70. #include "sshbuf.h"
  71. #include "packet.h"
  72. #include "log.h"
  73. #include "misc.h"
  74. #include "channels.h"
  75. #include "compat.h"
  76. #include "canohost.h"
  77. #include "sshkey.h"
  78. #include "authfd.h"
  79. #include "pathnames.h"
  80. #include "match.h"
  81. /* -- agent forwarding */
  82. #define NUM_SOCKS 10
  83. /* -- tcp forwarding */
  84. /* special-case port number meaning allow any port */
  85. #define FWD_PERMIT_ANY_PORT 0
  86. /* special-case wildcard meaning allow any host */
  87. #define FWD_PERMIT_ANY_HOST "*"
  88. /* -- X11 forwarding */
  89. /* Maximum number of fake X11 displays to try. */
  90. #define MAX_DISPLAYS 1000
  91. /* Per-channel callback for pre/post select() actions */
  92. typedef void chan_fn(struct ssh *, Channel *c,
  93. fd_set *readset, fd_set *writeset);
  94. /*
  95. * Data structure for storing which hosts are permitted for forward requests.
  96. * The local sides of any remote forwards are stored in this array to prevent
  97. * a corrupt remote server from accessing arbitrary TCP/IP ports on our local
  98. * network (which might be behind a firewall).
  99. */
  100. /* XXX: streamlocal wants a path instead of host:port */
  101. /* Overload host_to_connect; we could just make this match Forward */
  102. /* XXX - can we use listen_host instead of listen_path? */
  103. struct permission {
  104. char *host_to_connect; /* Connect to 'host'. */
  105. int port_to_connect; /* Connect to 'port'. */
  106. char *listen_host; /* Remote side should listen address. */
  107. char *listen_path; /* Remote side should listen path. */
  108. int listen_port; /* Remote side should listen port. */
  109. Channel *downstream; /* Downstream mux*/
  110. };
  111. /*
  112. * Stores the forwarding permission state for a single direction (local or
  113. * remote).
  114. */
  115. struct permission_set {
  116. /*
  117. * List of all local permitted host/port pairs to allow for the
  118. * user.
  119. */
  120. u_int num_permitted_user;
  121. struct permission *permitted_user;
  122. /*
  123. * List of all permitted host/port pairs to allow for the admin.
  124. */
  125. u_int num_permitted_admin;
  126. struct permission *permitted_admin;
  127. /*
  128. * If this is true, all opens/listens are permitted. This is the
  129. * case on the server on which we have to trust the client anyway,
  130. * and the user could do anything after logging in.
  131. */
  132. int all_permitted;
  133. };
  134. /* Master structure for channels state */
  135. struct ssh_channels {
  136. /*
  137. * Pointer to an array containing all allocated channels. The array
  138. * is dynamically extended as needed.
  139. */
  140. Channel **channels;
  141. /*
  142. * Size of the channel array. All slots of the array must always be
  143. * initialized (at least the type field); unused slots set to NULL
  144. */
  145. u_int channels_alloc;
  146. /*
  147. * Maximum file descriptor value used in any of the channels. This is
  148. * updated in channel_new.
  149. */
  150. int channel_max_fd;
  151. /*
  152. * 'channel_pre*' are called just before select() to add any bits
  153. * relevant to channels in the select bitmasks.
  154. *
  155. * 'channel_post*': perform any appropriate operations for
  156. * channels which have events pending.
  157. */
  158. chan_fn **channel_pre;
  159. chan_fn **channel_post;
  160. /* -- tcp forwarding */
  161. struct permission_set local_perms;
  162. struct permission_set remote_perms;
  163. /* -- X11 forwarding */
  164. /* Saved X11 local (client) display. */
  165. char *x11_saved_display;
  166. /* Saved X11 authentication protocol name. */
  167. char *x11_saved_proto;
  168. /* Saved X11 authentication data. This is the real data. */
  169. char *x11_saved_data;
  170. u_int x11_saved_data_len;
  171. /* Deadline after which all X11 connections are refused */
  172. u_int x11_refuse_time;
  173. /*
  174. * Fake X11 authentication data. This is what the server will be
  175. * sending us; we should replace any occurrences of this by the
  176. * real data.
  177. */
  178. u_char *x11_fake_data;
  179. u_int x11_fake_data_len;
  180. /* AF_UNSPEC or AF_INET or AF_INET6 */
  181. int IPv4or6;
  182. };
  183. /* helper */
  184. static void port_open_helper(struct ssh *ssh, Channel *c, char *rtype);
  185. static const char *channel_rfwd_bind_host(const char *listen_host);
  186. /* non-blocking connect helpers */
  187. static int connect_next(struct channel_connect *);
  188. static void channel_connect_ctx_free(struct channel_connect *);
  189. static Channel *rdynamic_connect_prepare(struct ssh *, char *, char *);
  190. static int rdynamic_connect_finish(struct ssh *, Channel *);
  191. /* Setup helper */
  192. static void channel_handler_init(struct ssh_channels *sc);
  193. static int hpn_disabled = 0;
  194. static int hpn_buffer_size = 6 * 1024 * 1024;
  195. /* -- channel core */
  196. void
  197. channel_init_channels(struct ssh *ssh)
  198. {
  199. struct ssh_channels *sc;
  200. if ((sc = calloc(1, sizeof(*sc))) == NULL)
  201. fatal("%s: allocation failed", __func__);
  202. sc->channels_alloc = 10;
  203. sc->channels = xcalloc(sc->channels_alloc, sizeof(*sc->channels));
  204. sc->IPv4or6 = AF_UNSPEC;
  205. channel_handler_init(sc);
  206. ssh->chanctxt = sc;
  207. }
  208. Channel *
  209. channel_by_id(struct ssh *ssh, int id)
  210. {
  211. Channel *c;
  212. if (id < 0 || (u_int)id >= ssh->chanctxt->channels_alloc) {
  213. logit("%s: %d: bad id", __func__, id);
  214. return NULL;
  215. }
  216. c = ssh->chanctxt->channels[id];
  217. if (c == NULL) {
  218. logit("%s: %d: bad id: channel free", __func__, id);
  219. return NULL;
  220. }
  221. return c;
  222. }
  223. Channel *
  224. channel_by_remote_id(struct ssh *ssh, u_int remote_id)
  225. {
  226. Channel *c;
  227. u_int i;
  228. for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
  229. c = ssh->chanctxt->channels[i];
  230. if (c != NULL && c->have_remote_id && c->remote_id == remote_id)
  231. return c;
  232. }
  233. return NULL;
  234. }
  235. /*
  236. * Returns the channel if it is allowed to receive protocol messages.
  237. * Private channels, like listening sockets, may not receive messages.
  238. */
  239. Channel *
  240. channel_lookup(struct ssh *ssh, int id)
  241. {
  242. Channel *c;
  243. if ((c = channel_by_id(ssh, id)) == NULL)
  244. return NULL;
  245. switch (c->type) {
  246. case SSH_CHANNEL_X11_OPEN:
  247. case SSH_CHANNEL_LARVAL:
  248. case SSH_CHANNEL_CONNECTING:
  249. case SSH_CHANNEL_DYNAMIC:
  250. case SSH_CHANNEL_RDYNAMIC_OPEN:
  251. case SSH_CHANNEL_RDYNAMIC_FINISH:
  252. case SSH_CHANNEL_OPENING:
  253. case SSH_CHANNEL_OPEN:
  254. case SSH_CHANNEL_ABANDONED:
  255. case SSH_CHANNEL_MUX_PROXY:
  256. return c;
  257. }
  258. logit("Non-public channel %d, type %d.", id, c->type);
  259. return NULL;
  260. }
  261. /*
  262. * Register filedescriptors for a channel, used when allocating a channel or
  263. * when the channel consumer/producer is ready, e.g. shell exec'd
  264. */
  265. static void
  266. channel_register_fds(struct ssh *ssh, Channel *c, int rfd, int wfd, int efd,
  267. int extusage, int nonblock, int is_tty)
  268. {
  269. struct ssh_channels *sc = ssh->chanctxt;
  270. /* Update the maximum file descriptor value. */
  271. sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, rfd);
  272. sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, wfd);
  273. sc->channel_max_fd = MAXIMUM(sc->channel_max_fd, efd);
  274. if (rfd != -1)
  275. fcntl(rfd, F_SETFD, FD_CLOEXEC);
  276. if (wfd != -1 && wfd != rfd)
  277. fcntl(wfd, F_SETFD, FD_CLOEXEC);
  278. if (efd != -1 && efd != rfd && efd != wfd)
  279. fcntl(efd, F_SETFD, FD_CLOEXEC);
  280. c->rfd = rfd;
  281. c->wfd = wfd;
  282. c->sock = (rfd == wfd) ? rfd : -1;
  283. c->efd = efd;
  284. c->extended_usage = extusage;
  285. if ((c->isatty = is_tty) != 0)
  286. debug2("channel %d: rfd %d isatty", c->self, c->rfd);
  287. #ifdef _AIX
  288. /* XXX: Later AIX versions can't push as much data to tty */
  289. c->wfd_isatty = is_tty || isatty(c->wfd);
  290. #endif
  291. /* enable nonblocking mode */
  292. if (nonblock) {
  293. if (rfd >= 0)
  294. set_nonblock(rfd);
  295. if (wfd >= 0)
  296. set_nonblock(wfd);
  297. if (efd >= 0)
  298. set_nonblock(efd);
  299. }
  300. }
  301. /*
  302. * Allocate a new channel object and set its type and socket. This will cause
  303. * remote_name to be freed.
  304. */
  305. Channel *
  306. channel_new(struct ssh *ssh, char *ctype, int type, int rfd, int wfd, int efd,
  307. u_int window, u_int maxpack, int extusage, char *remote_name, int nonblock)
  308. {
  309. struct ssh_channels *sc = ssh->chanctxt;
  310. u_int i, found;
  311. Channel *c;
  312. int r;
  313. /* Try to find a free slot where to put the new channel. */
  314. for (i = 0; i < sc->channels_alloc; i++) {
  315. if (sc->channels[i] == NULL) {
  316. /* Found a free slot. */
  317. found = i;
  318. break;
  319. }
  320. }
  321. if (i >= sc->channels_alloc) {
  322. /*
  323. * There are no free slots. Take last+1 slot and expand
  324. * the array.
  325. */
  326. found = sc->channels_alloc;
  327. if (sc->channels_alloc > CHANNELS_MAX_CHANNELS)
  328. fatal("%s: internal error: channels_alloc %d too big",
  329. __func__, sc->channels_alloc);
  330. sc->channels = xrecallocarray(sc->channels, sc->channels_alloc,
  331. sc->channels_alloc + 10, sizeof(*sc->channels));
  332. sc->channels_alloc += 10;
  333. debug2("channel: expanding %d", sc->channels_alloc);
  334. }
  335. /* Initialize and return new channel. */
  336. c = sc->channels[found] = xcalloc(1, sizeof(Channel));
  337. if ((c->input = sshbuf_new()) == NULL ||
  338. (c->output = sshbuf_new()) == NULL ||
  339. (c->extended = sshbuf_new()) == NULL)
  340. fatal("%s: sshbuf_new failed", __func__);
  341. if ((r = sshbuf_set_max_size(c->input, CHAN_INPUT_MAX)) != 0)
  342. fatal("%s: sshbuf_set_max_size: %s", __func__, ssh_err(r));
  343. c->ostate = CHAN_OUTPUT_OPEN;
  344. c->istate = CHAN_INPUT_OPEN;
  345. channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, 0);
  346. c->self = found;
  347. c->type = type;
  348. c->ctype = ctype;
  349. c->local_window = window;
  350. c->local_window_max = window;
  351. c->local_maxpacket = maxpack;
  352. c->dynamic_window = 0;
  353. c->remote_name = xstrdup(remote_name);
  354. c->ctl_chan = -1;
  355. c->delayed = 1; /* prevent call to channel_post handler */
  356. TAILQ_INIT(&c->status_confirms);
  357. debug("channel %d: new [%s]", found, remote_name);
  358. return c;
  359. }
  360. static void
  361. channel_find_maxfd(struct ssh_channels *sc)
  362. {
  363. u_int i;
  364. int max = 0;
  365. Channel *c;
  366. for (i = 0; i < sc->channels_alloc; i++) {
  367. c = sc->channels[i];
  368. if (c != NULL) {
  369. max = MAXIMUM(max, c->rfd);
  370. max = MAXIMUM(max, c->wfd);
  371. max = MAXIMUM(max, c->efd);
  372. }
  373. }
  374. sc->channel_max_fd = max;
  375. }
  376. int
  377. channel_close_fd(struct ssh *ssh, int *fdp)
  378. {
  379. struct ssh_channels *sc = ssh->chanctxt;
  380. int ret = 0, fd = *fdp;
  381. if (fd != -1) {
  382. ret = close(fd);
  383. *fdp = -1;
  384. if (fd == sc->channel_max_fd)
  385. channel_find_maxfd(sc);
  386. }
  387. return ret;
  388. }
  389. /* Close all channel fd/socket. */
  390. static void
  391. channel_close_fds(struct ssh *ssh, Channel *c)
  392. {
  393. int sock = c->sock, rfd = c->rfd, wfd = c->wfd, efd = c->efd;
  394. channel_close_fd(ssh, &c->sock);
  395. if (rfd != sock)
  396. channel_close_fd(ssh, &c->rfd);
  397. if (wfd != sock && wfd != rfd)
  398. channel_close_fd(ssh, &c->wfd);
  399. if (efd != sock && efd != rfd && efd != wfd)
  400. channel_close_fd(ssh, &c->efd);
  401. }
  402. static void
  403. fwd_perm_clear(struct permission *perm)
  404. {
  405. free(perm->host_to_connect);
  406. free(perm->listen_host);
  407. free(perm->listen_path);
  408. memset(perm, 0, sizeof(*perm));
  409. }
  410. /* Returns an printable name for the specified forwarding permission list */
  411. static const char *
  412. fwd_ident(int who, int where)
  413. {
  414. if (who == FORWARD_ADM) {
  415. if (where == FORWARD_LOCAL)
  416. return "admin local";
  417. else if (where == FORWARD_REMOTE)
  418. return "admin remote";
  419. } else if (who == FORWARD_USER) {
  420. if (where == FORWARD_LOCAL)
  421. return "user local";
  422. else if (where == FORWARD_REMOTE)
  423. return "user remote";
  424. }
  425. fatal("Unknown forward permission list %d/%d", who, where);
  426. }
  427. /* Returns the forwarding permission list for the specified direction */
  428. static struct permission_set *
  429. permission_set_get(struct ssh *ssh, int where)
  430. {
  431. struct ssh_channels *sc = ssh->chanctxt;
  432. switch (where) {
  433. case FORWARD_LOCAL:
  434. return &sc->local_perms;
  435. break;
  436. case FORWARD_REMOTE:
  437. return &sc->remote_perms;
  438. break;
  439. default:
  440. fatal("%s: invalid forwarding direction %d", __func__, where);
  441. }
  442. }
  443. /* Returns pointers to the specified forwarding list and its element count */
  444. static void
  445. permission_set_get_array(struct ssh *ssh, int who, int where,
  446. struct permission ***permpp, u_int **npermpp)
  447. {
  448. struct permission_set *pset = permission_set_get(ssh, where);
  449. switch (who) {
  450. case FORWARD_USER:
  451. *permpp = &pset->permitted_user;
  452. *npermpp = &pset->num_permitted_user;
  453. break;
  454. case FORWARD_ADM:
  455. *permpp = &pset->permitted_admin;
  456. *npermpp = &pset->num_permitted_admin;
  457. break;
  458. default:
  459. fatal("%s: invalid forwarding client %d", __func__, who);
  460. }
  461. }
  462. /* Adds an entry to the spcified forwarding list */
  463. static int
  464. permission_set_add(struct ssh *ssh, int who, int where,
  465. const char *host_to_connect, int port_to_connect,
  466. const char *listen_host, const char *listen_path, int listen_port,
  467. Channel *downstream)
  468. {
  469. struct permission **permp;
  470. u_int n, *npermp;
  471. permission_set_get_array(ssh, who, where, &permp, &npermp);
  472. if (*npermp >= INT_MAX)
  473. fatal("%s: %s overflow", __func__, fwd_ident(who, where));
  474. *permp = xrecallocarray(*permp, *npermp, *npermp + 1, sizeof(**permp));
  475. n = (*npermp)++;
  476. #define MAYBE_DUP(s) ((s == NULL) ? NULL : xstrdup(s))
  477. (*permp)[n].host_to_connect = MAYBE_DUP(host_to_connect);
  478. (*permp)[n].port_to_connect = port_to_connect;
  479. (*permp)[n].listen_host = MAYBE_DUP(listen_host);
  480. (*permp)[n].listen_path = MAYBE_DUP(listen_path);
  481. (*permp)[n].listen_port = listen_port;
  482. (*permp)[n].downstream = downstream;
  483. #undef MAYBE_DUP
  484. return (int)n;
  485. }
  486. static void
  487. mux_remove_remote_forwardings(struct ssh *ssh, Channel *c)
  488. {
  489. struct ssh_channels *sc = ssh->chanctxt;
  490. struct permission_set *pset = &sc->local_perms;
  491. struct permission *perm;
  492. int r;
  493. u_int i;
  494. for (i = 0; i < pset->num_permitted_user; i++) {
  495. perm = &pset->permitted_user[i];
  496. if (perm->downstream != c)
  497. continue;
  498. /* cancel on the server, since mux client is gone */
  499. debug("channel %d: cleanup remote forward for %s:%u",
  500. c->self, perm->listen_host, perm->listen_port);
  501. if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
  502. (r = sshpkt_put_cstring(ssh,
  503. "cancel-tcpip-forward")) != 0 ||
  504. (r = sshpkt_put_u8(ssh, 0)) != 0 ||
  505. (r = sshpkt_put_cstring(ssh,
  506. channel_rfwd_bind_host(perm->listen_host))) != 0 ||
  507. (r = sshpkt_put_u32(ssh, perm->listen_port)) != 0 ||
  508. (r = sshpkt_send(ssh)) != 0) {
  509. fatal("%s: channel %i: %s", __func__,
  510. c->self, ssh_err(r));
  511. }
  512. fwd_perm_clear(perm); /* unregister */
  513. }
  514. }
  515. /* Free the channel and close its fd/socket. */
  516. void
  517. channel_free(struct ssh *ssh, Channel *c)
  518. {
  519. struct ssh_channels *sc = ssh->chanctxt;
  520. char *s;
  521. u_int i, n;
  522. Channel *other;
  523. struct channel_confirm *cc;
  524. for (n = 0, i = 0; i < sc->channels_alloc; i++) {
  525. if ((other = sc->channels[i]) == NULL)
  526. continue;
  527. n++;
  528. /* detach from mux client and prepare for closing */
  529. if (c->type == SSH_CHANNEL_MUX_CLIENT &&
  530. other->type == SSH_CHANNEL_MUX_PROXY &&
  531. other->mux_ctx == c) {
  532. other->mux_ctx = NULL;
  533. other->type = SSH_CHANNEL_OPEN;
  534. other->istate = CHAN_INPUT_CLOSED;
  535. other->ostate = CHAN_OUTPUT_CLOSED;
  536. }
  537. }
  538. debug("channel %d: free: %s, nchannels %u", c->self,
  539. c->remote_name ? c->remote_name : "???", n);
  540. if (c->type == SSH_CHANNEL_MUX_CLIENT)
  541. mux_remove_remote_forwardings(ssh, c);
  542. else if (c->type == SSH_CHANNEL_MUX_LISTENER) {
  543. free(c->mux_ctx);
  544. c->mux_ctx = NULL;
  545. }
  546. if (log_level_get() >= SYSLOG_LEVEL_DEBUG3) {
  547. s = channel_open_message(ssh);
  548. debug3("channel %d: status: %s", c->self, s);
  549. free(s);
  550. }
  551. channel_close_fds(ssh, c);
  552. sshbuf_free(c->input);
  553. sshbuf_free(c->output);
  554. sshbuf_free(c->extended);
  555. c->input = c->output = c->extended = NULL;
  556. free(c->remote_name);
  557. c->remote_name = NULL;
  558. free(c->path);
  559. c->path = NULL;
  560. free(c->listening_addr);
  561. c->listening_addr = NULL;
  562. while ((cc = TAILQ_FIRST(&c->status_confirms)) != NULL) {
  563. if (cc->abandon_cb != NULL)
  564. cc->abandon_cb(ssh, c, cc->ctx);
  565. TAILQ_REMOVE(&c->status_confirms, cc, entry);
  566. freezero(cc, sizeof(*cc));
  567. }
  568. if (c->filter_cleanup != NULL && c->filter_ctx != NULL)
  569. c->filter_cleanup(ssh, c->self, c->filter_ctx);
  570. sc->channels[c->self] = NULL;
  571. freezero(c, sizeof(*c));
  572. }
  573. void
  574. channel_free_all(struct ssh *ssh)
  575. {
  576. u_int i;
  577. struct ssh_channels *sc = ssh->chanctxt;
  578. for (i = 0; i < sc->channels_alloc; i++)
  579. if (sc->channels[i] != NULL)
  580. channel_free(ssh, sc->channels[i]);
  581. free(sc->channels);
  582. sc->channels = NULL;
  583. sc->channels_alloc = 0;
  584. sc->channel_max_fd = 0;
  585. free(sc->x11_saved_display);
  586. sc->x11_saved_display = NULL;
  587. free(sc->x11_saved_proto);
  588. sc->x11_saved_proto = NULL;
  589. free(sc->x11_saved_data);
  590. sc->x11_saved_data = NULL;
  591. sc->x11_saved_data_len = 0;
  592. free(sc->x11_fake_data);
  593. sc->x11_fake_data = NULL;
  594. sc->x11_fake_data_len = 0;
  595. }
  596. /*
  597. * Closes the sockets/fds of all channels. This is used to close extra file
  598. * descriptors after a fork.
  599. */
  600. void
  601. channel_close_all(struct ssh *ssh)
  602. {
  603. u_int i;
  604. for (i = 0; i < ssh->chanctxt->channels_alloc; i++)
  605. if (ssh->chanctxt->channels[i] != NULL)
  606. channel_close_fds(ssh, ssh->chanctxt->channels[i]);
  607. }
  608. /*
  609. * Stop listening to channels.
  610. */
  611. void
  612. channel_stop_listening(struct ssh *ssh)
  613. {
  614. u_int i;
  615. Channel *c;
  616. for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
  617. c = ssh->chanctxt->channels[i];
  618. if (c != NULL) {
  619. switch (c->type) {
  620. case SSH_CHANNEL_AUTH_SOCKET:
  621. case SSH_CHANNEL_PORT_LISTENER:
  622. case SSH_CHANNEL_RPORT_LISTENER:
  623. case SSH_CHANNEL_X11_LISTENER:
  624. case SSH_CHANNEL_UNIX_LISTENER:
  625. case SSH_CHANNEL_RUNIX_LISTENER:
  626. channel_close_fd(ssh, &c->sock);
  627. channel_free(ssh, c);
  628. break;
  629. }
  630. }
  631. }
  632. }
  633. /*
  634. * Returns true if no channel has too much buffered data, and false if one or
  635. * more channel is overfull.
  636. */
  637. int
  638. channel_not_very_much_buffered_data(struct ssh *ssh)
  639. {
  640. u_int i;
  641. u_int maxsize = ssh_packet_get_maxsize(ssh);
  642. Channel *c;
  643. for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
  644. c = ssh->chanctxt->channels[i];
  645. if (c == NULL || c->type != SSH_CHANNEL_OPEN)
  646. continue;
  647. if (sshbuf_len(c->output) > maxsize) {
  648. debug2("channel %d: big output buffer %zu > %u",
  649. c->self, sshbuf_len(c->output), maxsize);
  650. return 0;
  651. }
  652. }
  653. return 1;
  654. }
  655. /* Returns true if any channel is still open. */
  656. int
  657. channel_still_open(struct ssh *ssh)
  658. {
  659. u_int i;
  660. Channel *c;
  661. for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
  662. c = ssh->chanctxt->channels[i];
  663. if (c == NULL)
  664. continue;
  665. switch (c->type) {
  666. case SSH_CHANNEL_X11_LISTENER:
  667. case SSH_CHANNEL_PORT_LISTENER:
  668. case SSH_CHANNEL_RPORT_LISTENER:
  669. case SSH_CHANNEL_MUX_LISTENER:
  670. case SSH_CHANNEL_CLOSED:
  671. case SSH_CHANNEL_AUTH_SOCKET:
  672. case SSH_CHANNEL_DYNAMIC:
  673. case SSH_CHANNEL_RDYNAMIC_OPEN:
  674. case SSH_CHANNEL_CONNECTING:
  675. case SSH_CHANNEL_ZOMBIE:
  676. case SSH_CHANNEL_ABANDONED:
  677. case SSH_CHANNEL_UNIX_LISTENER:
  678. case SSH_CHANNEL_RUNIX_LISTENER:
  679. continue;
  680. case SSH_CHANNEL_LARVAL:
  681. continue;
  682. case SSH_CHANNEL_OPENING:
  683. case SSH_CHANNEL_OPEN:
  684. case SSH_CHANNEL_RDYNAMIC_FINISH:
  685. case SSH_CHANNEL_X11_OPEN:
  686. case SSH_CHANNEL_MUX_CLIENT:
  687. case SSH_CHANNEL_MUX_PROXY:
  688. return 1;
  689. default:
  690. fatal("%s: bad channel type %d", __func__, c->type);
  691. /* NOTREACHED */
  692. }
  693. }
  694. return 0;
  695. }
  696. /* Returns the id of an open channel suitable for keepaliving */
  697. int
  698. channel_find_open(struct ssh *ssh)
  699. {
  700. u_int i;
  701. Channel *c;
  702. for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
  703. c = ssh->chanctxt->channels[i];
  704. if (c == NULL || !c->have_remote_id)
  705. continue;
  706. switch (c->type) {
  707. case SSH_CHANNEL_CLOSED:
  708. case SSH_CHANNEL_DYNAMIC:
  709. case SSH_CHANNEL_RDYNAMIC_OPEN:
  710. case SSH_CHANNEL_RDYNAMIC_FINISH:
  711. case SSH_CHANNEL_X11_LISTENER:
  712. case SSH_CHANNEL_PORT_LISTENER:
  713. case SSH_CHANNEL_RPORT_LISTENER:
  714. case SSH_CHANNEL_MUX_LISTENER:
  715. case SSH_CHANNEL_MUX_CLIENT:
  716. case SSH_CHANNEL_MUX_PROXY:
  717. case SSH_CHANNEL_OPENING:
  718. case SSH_CHANNEL_CONNECTING:
  719. case SSH_CHANNEL_ZOMBIE:
  720. case SSH_CHANNEL_ABANDONED:
  721. case SSH_CHANNEL_UNIX_LISTENER:
  722. case SSH_CHANNEL_RUNIX_LISTENER:
  723. continue;
  724. case SSH_CHANNEL_LARVAL:
  725. case SSH_CHANNEL_AUTH_SOCKET:
  726. case SSH_CHANNEL_OPEN:
  727. case SSH_CHANNEL_X11_OPEN:
  728. return i;
  729. default:
  730. fatal("%s: bad channel type %d", __func__, c->type);
  731. /* NOTREACHED */
  732. }
  733. }
  734. return -1;
  735. }
  736. /* Returns the state of the channel's extended usage flag */
  737. const char *
  738. channel_format_extended_usage(const Channel *c)
  739. {
  740. if (c->efd == -1)
  741. return "closed";
  742. switch (c->extended_usage) {
  743. case CHAN_EXTENDED_WRITE:
  744. return "write";
  745. case CHAN_EXTENDED_READ:
  746. return "read";
  747. case CHAN_EXTENDED_IGNORE:
  748. return "ignore";
  749. default:
  750. return "UNKNOWN";
  751. }
  752. }
  753. static char *
  754. channel_format_status(const Channel *c)
  755. {
  756. char *ret = NULL;
  757. xasprintf(&ret, "t%d %s%u i%u/%zu o%u/%zu e[%s]/%zu "
  758. "fd %d/%d/%d sock %d cc %d",
  759. c->type,
  760. c->have_remote_id ? "r" : "nr", c->remote_id,
  761. c->istate, sshbuf_len(c->input),
  762. c->ostate, sshbuf_len(c->output),
  763. channel_format_extended_usage(c), sshbuf_len(c->extended),
  764. c->rfd, c->wfd, c->efd, c->sock, c->ctl_chan);
  765. return ret;
  766. }
  767. /*
  768. * Returns a message describing the currently open forwarded connections,
  769. * suitable for sending to the client. The message contains crlf pairs for
  770. * newlines.
  771. */
  772. char *
  773. channel_open_message(struct ssh *ssh)
  774. {
  775. struct sshbuf *buf;
  776. Channel *c;
  777. u_int i;
  778. int r;
  779. char *cp, *ret;
  780. if ((buf = sshbuf_new()) == NULL)
  781. fatal("%s: sshbuf_new", __func__);
  782. if ((r = sshbuf_putf(buf,
  783. "The following connections are open:\r\n")) != 0)
  784. fatal("%s: sshbuf_putf: %s", __func__, ssh_err(r));
  785. for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
  786. c = ssh->chanctxt->channels[i];
  787. if (c == NULL)
  788. continue;
  789. switch (c->type) {
  790. case SSH_CHANNEL_X11_LISTENER:
  791. case SSH_CHANNEL_PORT_LISTENER:
  792. case SSH_CHANNEL_RPORT_LISTENER:
  793. case SSH_CHANNEL_CLOSED:
  794. case SSH_CHANNEL_AUTH_SOCKET:
  795. case SSH_CHANNEL_ZOMBIE:
  796. case SSH_CHANNEL_ABANDONED:
  797. case SSH_CHANNEL_MUX_LISTENER:
  798. case SSH_CHANNEL_UNIX_LISTENER:
  799. case SSH_CHANNEL_RUNIX_LISTENER:
  800. continue;
  801. case SSH_CHANNEL_LARVAL:
  802. case SSH_CHANNEL_OPENING:
  803. case SSH_CHANNEL_CONNECTING:
  804. case SSH_CHANNEL_DYNAMIC:
  805. case SSH_CHANNEL_RDYNAMIC_OPEN:
  806. case SSH_CHANNEL_RDYNAMIC_FINISH:
  807. case SSH_CHANNEL_OPEN:
  808. case SSH_CHANNEL_X11_OPEN:
  809. case SSH_CHANNEL_MUX_PROXY:
  810. case SSH_CHANNEL_MUX_CLIENT:
  811. cp = channel_format_status(c);
  812. if ((r = sshbuf_putf(buf, " #%d %.300s (%s)\r\n",
  813. c->self, c->remote_name, cp)) != 0) {
  814. free(cp);
  815. fatal("%s: sshbuf_putf: %s",
  816. __func__, ssh_err(r));
  817. }
  818. free(cp);
  819. continue;
  820. default:
  821. fatal("%s: bad channel type %d", __func__, c->type);
  822. /* NOTREACHED */
  823. }
  824. }
  825. if ((ret = sshbuf_dup_string(buf)) == NULL)
  826. fatal("%s: sshbuf_dup_string", __func__);
  827. sshbuf_free(buf);
  828. return ret;
  829. }
  830. static void
  831. open_preamble(struct ssh *ssh, const char *where, Channel *c, const char *type)
  832. {
  833. int r;
  834. if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN)) != 0 ||
  835. (r = sshpkt_put_cstring(ssh, type)) != 0 ||
  836. (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
  837. (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
  838. (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
  839. fatal("%s: channel %i: open: %s", where, c->self, ssh_err(r));
  840. }
  841. }
  842. void
  843. channel_send_open(struct ssh *ssh, int id)
  844. {
  845. Channel *c = channel_lookup(ssh, id);
  846. int r;
  847. if (c == NULL) {
  848. logit("channel_send_open: %d: bad id", id);
  849. return;
  850. }
  851. debug2("channel %d: send open", id);
  852. open_preamble(ssh, __func__, c, c->ctype);
  853. if ((r = sshpkt_send(ssh)) != 0)
  854. fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
  855. }
  856. void
  857. channel_request_start(struct ssh *ssh, int id, char *service, int wantconfirm)
  858. {
  859. Channel *c = channel_lookup(ssh, id);
  860. int r;
  861. if (c == NULL) {
  862. logit("%s: %d: unknown channel id", __func__, id);
  863. return;
  864. }
  865. if (!c->have_remote_id)
  866. fatal(":%s: channel %d: no remote id", __func__, c->self);
  867. debug2("channel %d: request %s confirm %d", id, service, wantconfirm);
  868. if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_REQUEST)) != 0 ||
  869. (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
  870. (r = sshpkt_put_cstring(ssh, service)) != 0 ||
  871. (r = sshpkt_put_u8(ssh, wantconfirm)) != 0) {
  872. fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
  873. }
  874. }
  875. void
  876. channel_register_status_confirm(struct ssh *ssh, int id,
  877. channel_confirm_cb *cb, channel_confirm_abandon_cb *abandon_cb, void *ctx)
  878. {
  879. struct channel_confirm *cc;
  880. Channel *c;
  881. if ((c = channel_lookup(ssh, id)) == NULL)
  882. fatal("%s: %d: bad id", __func__, id);
  883. cc = xcalloc(1, sizeof(*cc));
  884. cc->cb = cb;
  885. cc->abandon_cb = abandon_cb;
  886. cc->ctx = ctx;
  887. TAILQ_INSERT_TAIL(&c->status_confirms, cc, entry);
  888. }
  889. void
  890. channel_register_open_confirm(struct ssh *ssh, int id,
  891. channel_open_fn *fn, void *ctx)
  892. {
  893. Channel *c = channel_lookup(ssh, id);
  894. if (c == NULL) {
  895. logit("%s: %d: bad id", __func__, id);
  896. return;
  897. }
  898. c->open_confirm = fn;
  899. c->open_confirm_ctx = ctx;
  900. }
  901. void
  902. channel_register_cleanup(struct ssh *ssh, int id,
  903. channel_callback_fn *fn, int do_close)
  904. {
  905. Channel *c = channel_by_id(ssh, id);
  906. if (c == NULL) {
  907. logit("%s: %d: bad id", __func__, id);
  908. return;
  909. }
  910. c->detach_user = fn;
  911. c->detach_close = do_close;
  912. }
  913. void
  914. channel_cancel_cleanup(struct ssh *ssh, int id)
  915. {
  916. Channel *c = channel_by_id(ssh, id);
  917. if (c == NULL) {
  918. logit("%s: %d: bad id", __func__, id);
  919. return;
  920. }
  921. c->detach_user = NULL;
  922. c->detach_close = 0;
  923. }
  924. void
  925. channel_register_filter(struct ssh *ssh, int id, channel_infilter_fn *ifn,
  926. channel_outfilter_fn *ofn, channel_filter_cleanup_fn *cfn, void *ctx)
  927. {
  928. Channel *c = channel_lookup(ssh, id);
  929. if (c == NULL) {
  930. logit("%s: %d: bad id", __func__, id);
  931. return;
  932. }
  933. c->input_filter = ifn;
  934. c->output_filter = ofn;
  935. c->filter_ctx = ctx;
  936. c->filter_cleanup = cfn;
  937. }
  938. void
  939. channel_set_fds(struct ssh *ssh, int id, int rfd, int wfd, int efd,
  940. int extusage, int nonblock, int is_tty, u_int window_max)
  941. {
  942. Channel *c = channel_lookup(ssh, id);
  943. int r;
  944. if (c == NULL || c->type != SSH_CHANNEL_LARVAL)
  945. fatal("channel_activate for non-larval channel %d.", id);
  946. if (!c->have_remote_id)
  947. fatal(":%s: channel %d: no remote id", __func__, c->self);
  948. channel_register_fds(ssh, c, rfd, wfd, efd, extusage, nonblock, is_tty);
  949. c->type = SSH_CHANNEL_OPEN;
  950. c->local_window = c->local_window_max = window_max;
  951. if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
  952. (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
  953. (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
  954. (r = sshpkt_send(ssh)) != 0)
  955. fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
  956. }
  957. static void
  958. channel_pre_listener(struct ssh *ssh, Channel *c,
  959. fd_set *readset, fd_set *writeset)
  960. {
  961. FD_SET(c->sock, readset);
  962. }
  963. static void
  964. channel_pre_connecting(struct ssh *ssh, Channel *c,
  965. fd_set *readset, fd_set *writeset)
  966. {
  967. debug3("channel %d: waiting for connection", c->self);
  968. FD_SET(c->sock, writeset);
  969. }
  970. static int
  971. channel_tcpwinsz(struct ssh *ssh)
  972. {
  973. u_int32_t tcpwinsz = 0;
  974. socklen_t optsz = sizeof(tcpwinsz);
  975. int ret = -1;
  976. /* if we aren't on a socket return 128KB */
  977. if (!ssh_packet_connection_is_on_socket(ssh))
  978. return 128 * 1024;
  979. ret = getsockopt(ssh_packet_get_connection_in(ssh),
  980. SOL_SOCKET, SO_RCVBUF, &tcpwinsz, &optsz);
  981. /* return no more than SSHBUF_SIZE_MAX (currently 256MB) */
  982. if ((ret == 0) && tcpwinsz > SSHBUF_SIZE_MAX)
  983. tcpwinsz = SSHBUF_SIZE_MAX;
  984. debug2("tcpwinsz: tcp connection %d, Receive window: %d",
  985. ssh_packet_get_connection_in(ssh), tcpwinsz);
  986. return tcpwinsz;
  987. }
  988. static void
  989. channel_pre_open(struct ssh *ssh, Channel *c,
  990. fd_set *readset, fd_set *writeset)
  991. {
  992. if (c->istate == CHAN_INPUT_OPEN &&
  993. c->remote_window > 0 &&
  994. sshbuf_len(c->input) < c->remote_window &&
  995. sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
  996. FD_SET(c->rfd, readset);
  997. if (c->ostate == CHAN_OUTPUT_OPEN ||
  998. c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
  999. if (sshbuf_len(c->output) > 0) {
  1000. FD_SET(c->wfd, writeset);
  1001. } else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
  1002. if (CHANNEL_EFD_OUTPUT_ACTIVE(c))
  1003. debug2("channel %d: "
  1004. "obuf_empty delayed efd %d/(%zu)", c->self,
  1005. c->efd, sshbuf_len(c->extended));
  1006. else
  1007. chan_obuf_empty(ssh, c);
  1008. }
  1009. }
  1010. /** XXX check close conditions, too */
  1011. if (c->efd != -1 && !(c->istate == CHAN_INPUT_CLOSED &&
  1012. c->ostate == CHAN_OUTPUT_CLOSED)) {
  1013. if (c->extended_usage == CHAN_EXTENDED_WRITE &&
  1014. sshbuf_len(c->extended) > 0)
  1015. FD_SET(c->efd, writeset);
  1016. else if (c->efd != -1 && !(c->flags & CHAN_EOF_SENT) &&
  1017. (c->extended_usage == CHAN_EXTENDED_READ ||
  1018. c->extended_usage == CHAN_EXTENDED_IGNORE) &&
  1019. sshbuf_len(c->extended) < c->remote_window)
  1020. FD_SET(c->efd, readset);
  1021. }
  1022. /* XXX: What about efd? races? */
  1023. }
  1024. /*
  1025. * This is a special state for X11 authentication spoofing. An opened X11
  1026. * connection (when authentication spoofing is being done) remains in this
  1027. * state until the first packet has been completely read. The authentication
  1028. * data in that packet is then substituted by the real data if it matches the
  1029. * fake data, and the channel is put into normal mode.
  1030. * XXX All this happens at the client side.
  1031. * Returns: 0 = need more data, -1 = wrong cookie, 1 = ok
  1032. */
  1033. static int
  1034. x11_open_helper(struct ssh *ssh, struct sshbuf *b)
  1035. {
  1036. struct ssh_channels *sc = ssh->chanctxt;
  1037. u_char *ucp;
  1038. u_int proto_len, data_len;
  1039. /* Is this being called after the refusal deadline? */
  1040. if (sc->x11_refuse_time != 0 &&
  1041. (u_int)monotime() >= sc->x11_refuse_time) {
  1042. verbose("Rejected X11 connection after ForwardX11Timeout "
  1043. "expired");
  1044. return -1;
  1045. }
  1046. /* Check if the fixed size part of the packet is in buffer. */
  1047. if (sshbuf_len(b) < 12)
  1048. return 0;
  1049. /* Parse the lengths of variable-length fields. */
  1050. ucp = sshbuf_mutable_ptr(b);
  1051. if (ucp[0] == 0x42) { /* Byte order MSB first. */
  1052. proto_len = 256 * ucp[6] + ucp[7];
  1053. data_len = 256 * ucp[8] + ucp[9];
  1054. } else if (ucp[0] == 0x6c) { /* Byte order LSB first. */
  1055. proto_len = ucp[6] + 256 * ucp[7];
  1056. data_len = ucp[8] + 256 * ucp[9];
  1057. } else {
  1058. debug2("Initial X11 packet contains bad byte order byte: 0x%x",
  1059. ucp[0]);
  1060. return -1;
  1061. }
  1062. /* Check if the whole packet is in buffer. */
  1063. if (sshbuf_len(b) <
  1064. 12 + ((proto_len + 3) & ~3) + ((data_len + 3) & ~3))
  1065. return 0;
  1066. /* Check if authentication protocol matches. */
  1067. if (proto_len != strlen(sc->x11_saved_proto) ||
  1068. memcmp(ucp + 12, sc->x11_saved_proto, proto_len) != 0) {
  1069. debug2("X11 connection uses different authentication protocol.");
  1070. return -1;
  1071. }
  1072. /* Check if authentication data matches our fake data. */
  1073. if (data_len != sc->x11_fake_data_len ||
  1074. timingsafe_bcmp(ucp + 12 + ((proto_len + 3) & ~3),
  1075. sc->x11_fake_data, sc->x11_fake_data_len) != 0) {
  1076. debug2("X11 auth data does not match fake data.");
  1077. return -1;
  1078. }
  1079. /* Check fake data length */
  1080. if (sc->x11_fake_data_len != sc->x11_saved_data_len) {
  1081. error("X11 fake_data_len %d != saved_data_len %d",
  1082. sc->x11_fake_data_len, sc->x11_saved_data_len);
  1083. return -1;
  1084. }
  1085. /*
  1086. * Received authentication protocol and data match
  1087. * our fake data. Substitute the fake data with real
  1088. * data.
  1089. */
  1090. memcpy(ucp + 12 + ((proto_len + 3) & ~3),
  1091. sc->x11_saved_data, sc->x11_saved_data_len);
  1092. return 1;
  1093. }
  1094. static void
  1095. channel_pre_x11_open(struct ssh *ssh, Channel *c,
  1096. fd_set *readset, fd_set *writeset)
  1097. {
  1098. int ret = x11_open_helper(ssh, c->output);
  1099. /* c->force_drain = 1; */
  1100. if (ret == 1) {
  1101. c->type = SSH_CHANNEL_OPEN;
  1102. channel_pre_open(ssh, c, readset, writeset);
  1103. } else if (ret == -1) {
  1104. logit("X11 connection rejected because of wrong authentication.");
  1105. debug2("X11 rejected %d i%d/o%d",
  1106. c->self, c->istate, c->ostate);
  1107. chan_read_failed(ssh, c);
  1108. sshbuf_reset(c->input);
  1109. chan_ibuf_empty(ssh, c);
  1110. sshbuf_reset(c->output);
  1111. chan_write_failed(ssh, c);
  1112. debug2("X11 closed %d i%d/o%d", c->self, c->istate, c->ostate);
  1113. }
  1114. }
  1115. static void
  1116. channel_pre_mux_client(struct ssh *ssh,
  1117. Channel *c, fd_set *readset, fd_set *writeset)
  1118. {
  1119. if (c->istate == CHAN_INPUT_OPEN && !c->mux_pause &&
  1120. sshbuf_check_reserve(c->input, CHAN_RBUF) == 0)
  1121. FD_SET(c->rfd, readset);
  1122. if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
  1123. /* clear buffer immediately (discard any partial packet) */
  1124. sshbuf_reset(c->input);
  1125. chan_ibuf_empty(ssh, c);
  1126. /* Start output drain. XXX just kill chan? */
  1127. chan_rcvd_oclose(ssh, c);
  1128. }
  1129. if (c->ostate == CHAN_OUTPUT_OPEN ||
  1130. c->ostate == CHAN_OUTPUT_WAIT_DRAIN) {
  1131. if (sshbuf_len(c->output) > 0)
  1132. FD_SET(c->wfd, writeset);
  1133. else if (c->ostate == CHAN_OUTPUT_WAIT_DRAIN)
  1134. chan_obuf_empty(ssh, c);
  1135. }
  1136. }
  1137. /* try to decode a socks4 header */
  1138. static int
  1139. channel_decode_socks4(Channel *c, struct sshbuf *input, struct sshbuf *output)
  1140. {
  1141. const u_char *p;
  1142. char *host;
  1143. u_int len, have, i, found, need;
  1144. char username[256];
  1145. struct {
  1146. u_int8_t version;
  1147. u_int8_t command;
  1148. u_int16_t dest_port;
  1149. struct in_addr dest_addr;
  1150. } s4_req, s4_rsp;
  1151. int r;
  1152. debug2("channel %d: decode socks4", c->self);
  1153. have = sshbuf_len(input);
  1154. len = sizeof(s4_req);
  1155. if (have < len)
  1156. return 0;
  1157. p = sshbuf_ptr(input);
  1158. need = 1;
  1159. /* SOCKS4A uses an invalid IP address 0.0.0.x */
  1160. if (p[4] == 0 && p[5] == 0 && p[6] == 0 && p[7] != 0) {
  1161. debug2("channel %d: socks4a request", c->self);
  1162. /* ... and needs an extra string (the hostname) */
  1163. need = 2;
  1164. }
  1165. /* Check for terminating NUL on the string(s) */
  1166. for (found = 0, i = len; i < have; i++) {
  1167. if (p[i] == '\0') {
  1168. found++;
  1169. if (found == need)
  1170. break;
  1171. }
  1172. if (i > 1024) {
  1173. /* the peer is probably sending garbage */
  1174. debug("channel %d: decode socks4: too long",
  1175. c->self);
  1176. return -1;
  1177. }
  1178. }
  1179. if (found < need)
  1180. return 0;
  1181. if ((r = sshbuf_get(input, &s4_req.version, 1)) != 0 ||
  1182. (r = sshbuf_get(input, &s4_req.command, 1)) != 0 ||
  1183. (r = sshbuf_get(input, &s4_req.dest_port, 2)) != 0 ||
  1184. (r = sshbuf_get(input, &s4_req.dest_addr, 4)) != 0) {
  1185. debug("channels %d: decode socks4: %s", c->self, ssh_err(r));
  1186. return -1;
  1187. }
  1188. have = sshbuf_len(input);
  1189. p = sshbuf_ptr(input);
  1190. if (memchr(p, '\0', have) == NULL) {
  1191. error("channel %d: decode socks4: user not nul terminated",
  1192. c->self);
  1193. return -1;
  1194. }
  1195. len = strlen(p);
  1196. debug2("channel %d: decode socks4: user %s/%d", c->self, p, len);
  1197. len++; /* trailing '\0' */
  1198. strlcpy(username, p, sizeof(username));
  1199. if ((r = sshbuf_consume(input, len)) != 0) {
  1200. fatal("%s: channel %d: consume: %s", __func__,
  1201. c->self, ssh_err(r));
  1202. }
  1203. free(c->path);
  1204. c->path = NULL;
  1205. if (need == 1) { /* SOCKS4: one string */
  1206. host = inet_ntoa(s4_req.dest_addr);
  1207. c->path = xstrdup(host);
  1208. } else { /* SOCKS4A: two strings */
  1209. have = sshbuf_len(input);
  1210. p = sshbuf_ptr(input);
  1211. if (memchr(p, '\0', have) == NULL) {
  1212. error("channel %d: decode socks4a: host not nul "
  1213. "terminated", c->self);
  1214. return -1;
  1215. }
  1216. len = strlen(p);
  1217. debug2("channel %d: decode socks4a: host %s/%d",
  1218. c->self, p, len);
  1219. len++; /* trailing '\0' */
  1220. if (len > NI_MAXHOST) {
  1221. error("channel %d: hostname \"%.100s\" too long",
  1222. c->self, p);
  1223. return -1;
  1224. }
  1225. c->path = xstrdup(p);
  1226. if ((r = sshbuf_consume(input, len)) != 0) {
  1227. fatal("%s: channel %d: consume: %s", __func__,
  1228. c->self, ssh_err(r));
  1229. }
  1230. }
  1231. c->host_port = ntohs(s4_req.dest_port);
  1232. debug2("channel %d: dynamic request: socks4 host %s port %u command %u",
  1233. c->self, c->path, c->host_port, s4_req.command);
  1234. if (s4_req.command != 1) {
  1235. debug("channel %d: cannot handle: %s cn %d",
  1236. c->self, need == 1 ? "SOCKS4" : "SOCKS4A", s4_req.command);
  1237. return -1;
  1238. }
  1239. s4_rsp.version = 0; /* vn: 0 for reply */
  1240. s4_rsp.command = 90; /* cd: req granted */
  1241. s4_rsp.dest_port = 0; /* ignored */
  1242. s4_rsp.dest_addr.s_addr = INADDR_ANY; /* ignored */
  1243. if ((r = sshbuf_put(output, &s4_rsp, sizeof(s4_rsp))) != 0) {
  1244. fatal("%s: channel %d: append reply: %s", __func__,
  1245. c->self, ssh_err(r));
  1246. }
  1247. return 1;
  1248. }
  1249. /* try to decode a socks5 header */
  1250. #define SSH_SOCKS5_AUTHDONE 0x1000
  1251. #define SSH_SOCKS5_NOAUTH 0x00
  1252. #define SSH_SOCKS5_IPV4 0x01
  1253. #define SSH_SOCKS5_DOMAIN 0x03
  1254. #define SSH_SOCKS5_IPV6 0x04
  1255. #define SSH_SOCKS5_CONNECT 0x01
  1256. #define SSH_SOCKS5_SUCCESS 0x00
  1257. static int
  1258. channel_decode_socks5(Channel *c, struct sshbuf *input, struct sshbuf *output)
  1259. {
  1260. /* XXX use get/put_u8 instead of trusting struct padding */
  1261. struct {
  1262. u_int8_t version;
  1263. u_int8_t command;
  1264. u_int8_t reserved;
  1265. u_int8_t atyp;
  1266. } s5_req, s5_rsp;
  1267. u_int16_t dest_port;
  1268. char dest_addr[255+1], ntop[INET6_ADDRSTRLEN];
  1269. const u_char *p;
  1270. u_int have, need, i, found, nmethods, addrlen, af;
  1271. int r;
  1272. debug2("channel %d: decode socks5", c->self);
  1273. p = sshbuf_ptr(input);
  1274. if (p[0] != 0x05)
  1275. return -1;
  1276. have = sshbuf_len(input);
  1277. if (!(c->flags & SSH_SOCKS5_AUTHDONE)) {
  1278. /* format: ver | nmethods | methods */
  1279. if (have < 2)
  1280. return 0;
  1281. nmethods = p[1];
  1282. if (have < nmethods + 2)
  1283. return 0;
  1284. /* look for method: "NO AUTHENTICATION REQUIRED" */
  1285. for (found = 0, i = 2; i < nmethods + 2; i++) {
  1286. if (p[i] == SSH_SOCKS5_NOAUTH) {
  1287. found = 1;
  1288. break;
  1289. }
  1290. }
  1291. if (!found) {
  1292. debug("channel %d: method SSH_SOCKS5_NOAUTH not found",
  1293. c->self);
  1294. return -1;
  1295. }
  1296. if ((r = sshbuf_consume(input, nmethods + 2)) != 0) {
  1297. fatal("%s: channel %d: consume: %s", __func__,
  1298. c->self, ssh_err(r));
  1299. }
  1300. /* version, method */
  1301. if ((r = sshbuf_put_u8(output, 0x05)) != 0 ||
  1302. (r = sshbuf_put_u8(output, SSH_SOCKS5_NOAUTH)) != 0) {
  1303. fatal("%s: channel %d: append reply: %s", __func__,
  1304. c->self, ssh_err(r));
  1305. }
  1306. c->flags |= SSH_SOCKS5_AUTHDONE;
  1307. debug2("channel %d: socks5 auth done", c->self);
  1308. return 0; /* need more */
  1309. }
  1310. debug2("channel %d: socks5 post auth", c->self);
  1311. if (have < sizeof(s5_req)+1)
  1312. return 0; /* need more */
  1313. memcpy(&s5_req, p, sizeof(s5_req));
  1314. if (s5_req.version != 0x05 ||
  1315. s5_req.command != SSH_SOCKS5_CONNECT ||
  1316. s5_req.reserved != 0x00) {
  1317. debug2("channel %d: only socks5 connect supported", c->self);
  1318. return -1;
  1319. }
  1320. switch (s5_req.atyp){
  1321. case SSH_SOCKS5_IPV4:
  1322. addrlen = 4;
  1323. af = AF_INET;
  1324. break;
  1325. case SSH_SOCKS5_DOMAIN:
  1326. addrlen = p[sizeof(s5_req)];
  1327. af = -1;
  1328. break;
  1329. case SSH_SOCKS5_IPV6:
  1330. addrlen = 16;
  1331. af = AF_INET6;
  1332. break;
  1333. default:
  1334. debug2("channel %d: bad socks5 atyp %d", c->self, s5_req.atyp);
  1335. return -1;
  1336. }
  1337. need = sizeof(s5_req) + addrlen + 2;
  1338. if (s5_req.atyp == SSH_SOCKS5_DOMAIN)
  1339. need++;
  1340. if (have < need)
  1341. return 0;
  1342. if ((r = sshbuf_consume(input, sizeof(s5_req))) != 0) {
  1343. fatal("%s: channel %d: consume: %s", __func__,
  1344. c->self, ssh_err(r));
  1345. }
  1346. if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
  1347. /* host string length */
  1348. if ((r = sshbuf_consume(input, 1)) != 0) {
  1349. fatal("%s: channel %d: consume: %s", __func__,
  1350. c->self, ssh_err(r));
  1351. }
  1352. }
  1353. if ((r = sshbuf_get(input, &dest_addr, addrlen)) != 0 ||
  1354. (r = sshbuf_get(input, &dest_port, 2)) != 0) {
  1355. debug("channel %d: parse addr/port: %s", c->self, ssh_err(r));
  1356. return -1;
  1357. }
  1358. dest_addr[addrlen] = '\0';
  1359. free(c->path);
  1360. c->path = NULL;
  1361. if (s5_req.atyp == SSH_SOCKS5_DOMAIN) {
  1362. if (addrlen >= NI_MAXHOST) {
  1363. error("channel %d: dynamic request: socks5 hostname "
  1364. "\"%.100s\" too long", c->self, dest_addr);
  1365. return -1;
  1366. }
  1367. c->path = xstrdup(dest_addr);
  1368. } else {
  1369. if (inet_ntop(af, dest_addr, ntop, sizeof(ntop)) == NULL)
  1370. return -1;
  1371. c->path = xstrdup(ntop);
  1372. }
  1373. c->host_port = ntohs(dest_port);
  1374. debug2("channel %d: dynamic request: socks5 host %s port %u command %u",
  1375. c->self, c->path, c->host_port, s5_req.command);
  1376. s5_rsp.version = 0x05;
  1377. s5_rsp.command = SSH_SOCKS5_SUCCESS;
  1378. s5_rsp.reserved = 0; /* ignored */
  1379. s5_rsp.atyp = SSH_SOCKS5_IPV4;
  1380. dest_port = 0; /* ignored */
  1381. if ((r = sshbuf_put(output, &s5_rsp, sizeof(s5_rsp))) != 0 ||
  1382. (r = sshbuf_put_u32(output, ntohl(INADDR_ANY))) != 0 ||
  1383. (r = sshbuf_put(output, &dest_port, sizeof(dest_port))) != 0)
  1384. fatal("%s: channel %d: append reply: %s", __func__,
  1385. c->self, ssh_err(r));
  1386. return 1;
  1387. }
  1388. Channel *
  1389. channel_connect_stdio_fwd(struct ssh *ssh,
  1390. const char *host_to_connect, u_short port_to_connect, int in, int out)
  1391. {
  1392. Channel *c;
  1393. debug("%s %s:%d", __func__, host_to_connect, port_to_connect);
  1394. c = channel_new(ssh, "stdio-forward", SSH_CHANNEL_OPENING, in, out,
  1395. -1, CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
  1396. 0, "stdio-forward", /*nonblock*/0);
  1397. c->path = xstrdup(host_to_connect);
  1398. c->host_port = port_to_connect;
  1399. c->listening_port = 0;
  1400. c->force_drain = 1;
  1401. channel_register_fds(ssh, c, in, out, -1, 0, 1, 0);
  1402. port_open_helper(ssh, c, "direct-tcpip");
  1403. return c;
  1404. }
  1405. /* dynamic port forwarding */
  1406. static void
  1407. channel_pre_dynamic(struct ssh *ssh, Channel *c,
  1408. fd_set *readset, fd_set *writeset)
  1409. {
  1410. const u_char *p;
  1411. u_int have;
  1412. int ret;
  1413. have = sshbuf_len(c->input);
  1414. debug2("channel %d: pre_dynamic: have %d", c->self, have);
  1415. /* sshbuf_dump(c->input, stderr); */
  1416. /* check if the fixed size part of the packet is in buffer. */
  1417. if (have < 3) {
  1418. /* need more */
  1419. FD_SET(c->sock, readset);
  1420. return;
  1421. }
  1422. /* try to guess the protocol */
  1423. p = sshbuf_ptr(c->input);
  1424. /* XXX sshbuf_peek_u8? */
  1425. switch (p[0]) {
  1426. case 0x04:
  1427. ret = channel_decode_socks4(c, c->input, c->output);
  1428. break;
  1429. case 0x05:
  1430. ret = channel_decode_socks5(c, c->input, c->output);
  1431. break;
  1432. default:
  1433. ret = -1;
  1434. break;
  1435. }
  1436. if (ret < 0) {
  1437. chan_mark_dead(ssh, c);
  1438. } else if (ret == 0) {
  1439. debug2("channel %d: pre_dynamic: need more", c->self);
  1440. /* need more */
  1441. FD_SET(c->sock, readset);
  1442. if (sshbuf_len(c->output))
  1443. FD_SET(c->sock, writeset);
  1444. } else {
  1445. /* switch to the next state */
  1446. c->type = SSH_CHANNEL_OPENING;
  1447. port_open_helper(ssh, c, "direct-tcpip");
  1448. }
  1449. }
  1450. /* simulate read-error */
  1451. static void
  1452. rdynamic_close(struct ssh *ssh, Channel *c)
  1453. {
  1454. c->type = SSH_CHANNEL_OPEN;
  1455. chan_read_failed(ssh, c);
  1456. sshbuf_reset(c->input);
  1457. chan_ibuf_empty(ssh, c);
  1458. sshbuf_reset(c->output);
  1459. chan_write_failed(ssh, c);
  1460. }
  1461. /* reverse dynamic port forwarding */
  1462. static void
  1463. channel_before_prepare_select_rdynamic(struct ssh *ssh, Channel *c)
  1464. {
  1465. const u_char *p;
  1466. u_int have, len;
  1467. int r, ret;
  1468. have = sshbuf_len(c->output);
  1469. debug2("channel %d: pre_rdynamic: have %d", c->self, have);
  1470. /* sshbuf_dump(c->output, stderr); */
  1471. /* EOF received */
  1472. if (c->flags & CHAN_EOF_RCVD) {
  1473. if ((r = sshbuf_consume(c->output, have)) != 0) {
  1474. fatal("%s: channel %d: consume: %s",
  1475. __func__, c->self, ssh_err(r));
  1476. }
  1477. rdynamic_close(ssh, c);
  1478. return;
  1479. }
  1480. /* check if the fixed size part of the packet is in buffer. */
  1481. if (have < 3)
  1482. return;
  1483. /* try to guess the protocol */
  1484. p = sshbuf_ptr(c->output);
  1485. switch (p[0]) {
  1486. case 0x04:
  1487. /* switch input/output for reverse forwarding */
  1488. ret = channel_decode_socks4(c, c->output, c->input);
  1489. break;
  1490. case 0x05:
  1491. ret = channel_decode_socks5(c, c->output, c->input);
  1492. break;
  1493. default:
  1494. ret = -1;
  1495. break;
  1496. }
  1497. if (ret < 0) {
  1498. rdynamic_close(ssh, c);
  1499. } else if (ret == 0) {
  1500. debug2("channel %d: pre_rdynamic: need more", c->self);
  1501. /* send socks request to peer */
  1502. len = sshbuf_len(c->input);
  1503. if (len > 0 && len < c->remote_window) {
  1504. if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
  1505. (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
  1506. (r = sshpkt_put_stringb(ssh, c->input)) != 0 ||
  1507. (r = sshpkt_send(ssh)) != 0) {
  1508. fatal("%s: channel %i: rdynamic: %s", __func__,
  1509. c->self, ssh_err(r));
  1510. }
  1511. if ((r = sshbuf_consume(c->input, len)) != 0) {
  1512. fatal("%s: channel %d: consume: %s",
  1513. __func__, c->self, ssh_err(r));
  1514. }
  1515. c->remote_window -= len;
  1516. }
  1517. } else if (rdynamic_connect_finish(ssh, c) < 0) {
  1518. /* the connect failed */
  1519. rdynamic_close(ssh, c);
  1520. }
  1521. }
  1522. /* This is our fake X11 server socket. */
  1523. static void
  1524. channel_post_x11_listener(struct ssh *ssh, Channel *c,
  1525. fd_set *readset, fd_set *writeset)
  1526. {
  1527. Channel *nc;
  1528. struct sockaddr_storage addr;
  1529. int r, newsock, oerrno, remote_port;
  1530. socklen_t addrlen;
  1531. char buf[16384], *remote_ipaddr;
  1532. if (!FD_ISSET(c->sock, readset))
  1533. return;
  1534. debug("X11 connection requested.");
  1535. addrlen = sizeof(addr);
  1536. newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
  1537. if (c->single_connection) {
  1538. oerrno = errno;
  1539. debug2("single_connection: closing X11 listener.");
  1540. channel_close_fd(ssh, &c->sock);
  1541. chan_mark_dead(ssh, c);
  1542. errno = oerrno;
  1543. }
  1544. if (newsock == -1) {
  1545. if (errno != EINTR && errno != EWOULDBLOCK &&
  1546. errno != ECONNABORTED)
  1547. error("accept: %.100s", strerror(errno));
  1548. if (errno == EMFILE || errno == ENFILE)
  1549. c->notbefore = monotime() + 1;
  1550. return;
  1551. }
  1552. set_nodelay(newsock);
  1553. remote_ipaddr = get_peer_ipaddr(newsock);
  1554. remote_port = get_peer_port(newsock);
  1555. snprintf(buf, sizeof buf, "X11 connection from %.200s port %d",
  1556. remote_ipaddr, remote_port);
  1557. nc = channel_new(ssh, "accepted x11 socket",
  1558. SSH_CHANNEL_OPENING, newsock, newsock, -1,
  1559. c->local_window_max, c->local_maxpacket, 0, buf, 1);
  1560. open_preamble(ssh, __func__, nc, "x11");
  1561. if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
  1562. (r = sshpkt_put_u32(ssh, remote_port)) != 0) {
  1563. fatal("%s: channel %i: reply %s", __func__,
  1564. c->self, ssh_err(r));
  1565. }
  1566. if ((r = sshpkt_send(ssh)) != 0)
  1567. fatal("%s: channel %i: send %s", __func__, c->self, ssh_err(r));
  1568. free(remote_ipaddr);
  1569. }
  1570. static void
  1571. port_open_helper(struct ssh *ssh, Channel *c, char *rtype)
  1572. {
  1573. char *local_ipaddr = get_local_ipaddr(c->sock);
  1574. int local_port = c->sock == -1 ? 65536 : get_local_port(c->sock);
  1575. char *remote_ipaddr = get_peer_ipaddr(c->sock);
  1576. int remote_port = get_peer_port(c->sock);
  1577. int r;
  1578. if (remote_port == -1) {
  1579. /* Fake addr/port to appease peers that validate it (Tectia) */
  1580. free(remote_ipaddr);
  1581. remote_ipaddr = xstrdup("127.0.0.1");
  1582. remote_port = 65535;
  1583. }
  1584. free(c->remote_name);
  1585. xasprintf(&c->remote_name,
  1586. "%s: listening port %d for %.100s port %d, "
  1587. "connect from %.200s port %d to %.100s port %d",
  1588. rtype, c->listening_port, c->path, c->host_port,
  1589. remote_ipaddr, remote_port, local_ipaddr, local_port);
  1590. open_preamble(ssh, __func__, c, rtype);
  1591. if (strcmp(rtype, "direct-tcpip") == 0) {
  1592. /* target host, port */
  1593. if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
  1594. (r = sshpkt_put_u32(ssh, c->host_port)) != 0) {
  1595. fatal("%s: channel %i: reply %s", __func__,
  1596. c->self, ssh_err(r));
  1597. }
  1598. } else if (strcmp(rtype, "direct-streamlocal@openssh.com") == 0) {
  1599. /* target path */
  1600. if ((r = sshpkt_put_cstring(ssh, c->path)) != 0) {
  1601. fatal("%s: channel %i: reply %s", __func__,
  1602. c->self, ssh_err(r));
  1603. }
  1604. } else if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
  1605. /* listen path */
  1606. if ((r = sshpkt_put_cstring(ssh, c->path)) != 0) {
  1607. fatal("%s: channel %i: reply %s", __func__,
  1608. c->self, ssh_err(r));
  1609. }
  1610. } else {
  1611. /* listen address, port */
  1612. if ((r = sshpkt_put_cstring(ssh, c->path)) != 0 ||
  1613. (r = sshpkt_put_u32(ssh, local_port)) != 0) {
  1614. fatal("%s: channel %i: reply %s", __func__,
  1615. c->self, ssh_err(r));
  1616. }
  1617. }
  1618. if (strcmp(rtype, "forwarded-streamlocal@openssh.com") == 0) {
  1619. /* reserved for future owner/mode info */
  1620. if ((r = sshpkt_put_cstring(ssh, "")) != 0) {
  1621. fatal("%s: channel %i: reply %s", __func__,
  1622. c->self, ssh_err(r));
  1623. }
  1624. } else {
  1625. /* originator host and port */
  1626. if ((r = sshpkt_put_cstring(ssh, remote_ipaddr)) != 0 ||
  1627. (r = sshpkt_put_u32(ssh, (u_int)remote_port)) != 0) {
  1628. fatal("%s: channel %i: reply %s", __func__,
  1629. c->self, ssh_err(r));
  1630. }
  1631. }
  1632. if ((r = sshpkt_send(ssh)) != 0)
  1633. fatal("%s: channel %i: send %s", __func__, c->self, ssh_err(r));
  1634. free(remote_ipaddr);
  1635. free(local_ipaddr);
  1636. }
  1637. void
  1638. channel_set_x11_refuse_time(struct ssh *ssh, u_int refuse_time)
  1639. {
  1640. ssh->chanctxt->x11_refuse_time = refuse_time;
  1641. }
  1642. /*
  1643. * This socket is listening for connections to a forwarded TCP/IP port.
  1644. */
  1645. static void
  1646. channel_post_port_listener(struct ssh *ssh, Channel *c,
  1647. fd_set *readset, fd_set *writeset)
  1648. {
  1649. Channel *nc;
  1650. struct sockaddr_storage addr;
  1651. int newsock, nextstate;
  1652. socklen_t addrlen;
  1653. char *rtype;
  1654. if (!FD_ISSET(c->sock, readset))
  1655. return;
  1656. debug("Connection to port %d forwarding to %.100s port %d requested.",
  1657. c->listening_port, c->path, c->host_port);
  1658. if (c->type == SSH_CHANNEL_RPORT_LISTENER) {
  1659. nextstate = SSH_CHANNEL_OPENING;
  1660. rtype = "forwarded-tcpip";
  1661. } else if (c->type == SSH_CHANNEL_RUNIX_LISTENER) {
  1662. nextstate = SSH_CHANNEL_OPENING;
  1663. rtype = "forwarded-streamlocal@openssh.com";
  1664. } else if (c->host_port == PORT_STREAMLOCAL) {
  1665. nextstate = SSH_CHANNEL_OPENING;
  1666. rtype = "direct-streamlocal@openssh.com";
  1667. } else if (c->host_port == 0) {
  1668. nextstate = SSH_CHANNEL_DYNAMIC;
  1669. rtype = "dynamic-tcpip";
  1670. } else {
  1671. nextstate = SSH_CHANNEL_OPENING;
  1672. rtype = "direct-tcpip";
  1673. }
  1674. addrlen = sizeof(addr);
  1675. newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
  1676. if (newsock == -1) {
  1677. if (errno != EINTR && errno != EWOULDBLOCK &&
  1678. errno != ECONNABORTED)
  1679. error("accept: %.100s", strerror(errno));
  1680. if (errno == EMFILE || errno == ENFILE)
  1681. c->notbefore = monotime() + 1;
  1682. return;
  1683. }
  1684. if (c->host_port != PORT_STREAMLOCAL)
  1685. set_nodelay(newsock);
  1686. nc = channel_new(ssh, rtype, nextstate, newsock, newsock, -1,
  1687. c->local_window_max, c->local_maxpacket, 0, rtype, 1);
  1688. nc->listening_port = c->listening_port;
  1689. nc->host_port = c->host_port;
  1690. if (c->path != NULL)
  1691. nc->path = xstrdup(c->path);
  1692. if (nextstate != SSH_CHANNEL_DYNAMIC)
  1693. port_open_helper(ssh, nc, rtype);
  1694. }
  1695. /*
  1696. * This is the authentication agent socket listening for connections from
  1697. * clients.
  1698. */
  1699. static void
  1700. channel_post_auth_listener(struct ssh *ssh, Channel *c,
  1701. fd_set *readset, fd_set *writeset)
  1702. {
  1703. Channel *nc;
  1704. int r, newsock;
  1705. struct sockaddr_storage addr;
  1706. socklen_t addrlen;
  1707. if (!FD_ISSET(c->sock, readset))
  1708. return;
  1709. addrlen = sizeof(addr);
  1710. newsock = accept(c->sock, (struct sockaddr *)&addr, &addrlen);
  1711. if (newsock == -1) {
  1712. error("accept from auth socket: %.100s", strerror(errno));
  1713. if (errno == EMFILE || errno == ENFILE)
  1714. c->notbefore = monotime() + 1;
  1715. return;
  1716. }
  1717. nc = channel_new(ssh, "accepted auth socket",
  1718. SSH_CHANNEL_OPENING, newsock, newsock, -1,
  1719. c->local_window_max, c->local_maxpacket,
  1720. 0, "accepted auth socket", 1);
  1721. open_preamble(ssh, __func__, nc, "auth-agent@openssh.com");
  1722. if ((r = sshpkt_send(ssh)) != 0)
  1723. fatal("%s: channel %i: %s", __func__, c->self, ssh_err(r));
  1724. }
  1725. static void
  1726. channel_post_connecting(struct ssh *ssh, Channel *c,
  1727. fd_set *readset, fd_set *writeset)
  1728. {
  1729. int err = 0, sock, isopen, r;
  1730. socklen_t sz = sizeof(err);
  1731. if (!FD_ISSET(c->sock, writeset))
  1732. return;
  1733. if (!c->have_remote_id)
  1734. fatal(":%s: channel %d: no remote id", __func__, c->self);
  1735. /* for rdynamic the OPEN_CONFIRMATION has been sent already */
  1736. isopen = (c->type == SSH_CHANNEL_RDYNAMIC_FINISH);
  1737. if (getsockopt(c->sock, SOL_SOCKET, SO_ERROR, &err, &sz) == -1) {
  1738. err = errno;
  1739. error("getsockopt SO_ERROR failed");
  1740. }
  1741. if (err == 0) {
  1742. debug("channel %d: connected to %s port %d",
  1743. c->self, c->connect_ctx.host, c->connect_ctx.port);
  1744. channel_connect_ctx_free(&c->connect_ctx);
  1745. c->type = SSH_CHANNEL_OPEN;
  1746. if (isopen) {
  1747. /* no message necessary */
  1748. } else {
  1749. if ((r = sshpkt_start(ssh,
  1750. SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
  1751. (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
  1752. (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
  1753. (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
  1754. (r = sshpkt_put_u32(ssh, c->local_maxpacket))
  1755. != 0)
  1756. fatal("%s: channel %i: confirm: %s", __func__,
  1757. c->self, ssh_err(r));
  1758. if ((r = sshpkt_send(ssh)) != 0)
  1759. fatal("%s: channel %i: %s", __func__, c->self,
  1760. ssh_err(r));
  1761. }
  1762. } else {
  1763. debug("channel %d: connection failed: %s",
  1764. c->self, strerror(err));
  1765. /* Try next address, if any */
  1766. if ((sock = connect_next(&c->connect_ctx)) > 0) {
  1767. close(c->sock);
  1768. c->sock = c->rfd = c->wfd = sock;
  1769. channel_find_maxfd(ssh->chanctxt);
  1770. return;
  1771. }
  1772. /* Exhausted all addresses */
  1773. error("connect_to %.100s port %d: failed.",
  1774. c->connect_ctx.host, c->connect_ctx.port);
  1775. channel_connect_ctx_free(&c->connect_ctx);
  1776. if (isopen) {
  1777. rdynamic_close(ssh, c);
  1778. } else {
  1779. if ((r = sshpkt_start(ssh,
  1780. SSH2_MSG_CHANNEL_OPEN_FAILURE)) != 0 ||
  1781. (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
  1782. (r = sshpkt_put_u32(ssh,
  1783. SSH2_OPEN_CONNECT_FAILED)) != 0 ||
  1784. (r = sshpkt_put_cstring(ssh, strerror(err))) != 0 ||
  1785. (r = sshpkt_put_cstring(ssh, "")) != 0) {
  1786. fatal("%s: channel %i: failure: %s", __func__,
  1787. c->self, ssh_err(r));
  1788. }
  1789. if ((r = sshpkt_send(ssh)) != 0)
  1790. fatal("%s: channel %i: %s", __func__, c->self,
  1791. ssh_err(r));
  1792. chan_mark_dead(ssh, c);
  1793. }
  1794. }
  1795. }
  1796. static int
  1797. channel_handle_rfd(struct ssh *ssh, Channel *c,
  1798. fd_set *readset, fd_set *writeset)
  1799. {
  1800. char buf[CHAN_RBUF];
  1801. ssize_t len;
  1802. int r, force;
  1803. force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
  1804. if (c->rfd == -1 || (!force && !FD_ISSET(c->rfd, readset)))
  1805. return 1;
  1806. errno = 0;
  1807. len = read(c->rfd, buf, sizeof(buf));
  1808. if (len == -1 && (errno == EINTR ||
  1809. ((errno == EAGAIN || errno == EWOULDBLOCK) && !force)))
  1810. return 1;
  1811. #ifndef PTY_ZEROREAD
  1812. if (len <= 0) {
  1813. #else
  1814. if ((!c->isatty && len <= 0) ||
  1815. (c->isatty && (len < 0 || (len == 0 && errno != 0)))) {
  1816. #endif
  1817. debug2("channel %d: read<=0 rfd %d len %zd",
  1818. c->self, c->rfd, len);
  1819. if (c->type != SSH_CHANNEL_OPEN) {
  1820. debug2("channel %d: not open", c->self);
  1821. chan_mark_dead(ssh, c);
  1822. return -1;
  1823. } else {
  1824. chan_read_failed(ssh, c);
  1825. }
  1826. return -1;
  1827. }
  1828. if (c->input_filter != NULL) {
  1829. if (c->input_filter(ssh, c, buf, len) == -1) {
  1830. debug2("channel %d: filter stops", c->self);
  1831. chan_read_failed(ssh, c);
  1832. }
  1833. } else if (c->datagram) {
  1834. if ((r = sshbuf_put_string(c->input, buf, len)) != 0)
  1835. fatal("%s: channel %d: put datagram: %s", __func__,
  1836. c->self, ssh_err(r));
  1837. } else if ((r = sshbuf_put(c->input, buf, len)) != 0) {
  1838. fatal("%s: channel %d: put data: %s", __func__,
  1839. c->self, ssh_err(r));
  1840. }
  1841. return 1;
  1842. }
  1843. static int
  1844. channel_handle_wfd(struct ssh *ssh, Channel *c,
  1845. fd_set *readset, fd_set *writeset)
  1846. {
  1847. struct termios tio;
  1848. u_char *data = NULL, *buf; /* XXX const; need filter API change */
  1849. size_t dlen, olen = 0;
  1850. int r, len;
  1851. if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
  1852. sshbuf_len(c->output) == 0)
  1853. return 1;
  1854. /* Send buffered output data to the socket. */
  1855. olen = sshbuf_len(c->output);
  1856. if (c->output_filter != NULL) {
  1857. if ((buf = c->output_filter(ssh, c, &data, &dlen)) == NULL) {
  1858. debug2("channel %d: filter stops", c->self);
  1859. if (c->type != SSH_CHANNEL_OPEN)
  1860. chan_mark_dead(ssh, c);
  1861. else
  1862. chan_write_failed(ssh, c);
  1863. return -1;
  1864. }
  1865. } else if (c->datagram) {
  1866. if ((r = sshbuf_get_string(c->output, &data, &dlen)) != 0)
  1867. fatal("%s: channel %d: get datagram: %s", __func__,
  1868. c->self, ssh_err(r));
  1869. buf = data;
  1870. } else {
  1871. buf = data = sshbuf_mutable_ptr(c->output);
  1872. dlen = sshbuf_len(c->output);
  1873. }
  1874. if (c->datagram) {
  1875. /* ignore truncated writes, datagrams might get lost */
  1876. len = write(c->wfd, buf, dlen);
  1877. free(data);
  1878. if (len == -1 && (errno == EINTR || errno == EAGAIN ||
  1879. errno == EWOULDBLOCK))
  1880. return 1;
  1881. if (len <= 0)
  1882. goto write_fail;
  1883. goto out;
  1884. }
  1885. #ifdef _AIX
  1886. /* XXX: Later AIX versions can't push as much data to tty */
  1887. if (c->wfd_isatty)
  1888. dlen = MIN(dlen, 8*1024);
  1889. #endif
  1890. len = write(c->wfd, buf, dlen);
  1891. if (len == -1 &&
  1892. (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK))
  1893. return 1;
  1894. if (len <= 0) {
  1895. write_fail:
  1896. if (c->type != SSH_CHANNEL_OPEN) {
  1897. debug2("channel %d: not open", c->self);
  1898. chan_mark_dead(ssh, c);
  1899. return -1;
  1900. } else {
  1901. chan_write_failed(ssh, c);
  1902. }
  1903. return -1;
  1904. }
  1905. #ifndef BROKEN_TCGETATTR_ICANON
  1906. if (c->isatty && dlen >= 1 && buf[0] != '\r') {
  1907. if (tcgetattr(c->wfd, &tio) == 0 &&
  1908. !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
  1909. /*
  1910. * Simulate echo to reduce the impact of
  1911. * traffic analysis. We need to match the
  1912. * size of a SSH2_MSG_CHANNEL_DATA message
  1913. * (4 byte channel id + buf)
  1914. */
  1915. if ((r = sshpkt_msg_ignore(ssh, 4+len)) != 0 ||
  1916. (r = sshpkt_send(ssh)) != 0)
  1917. fatal("%s: channel %d: ignore: %s",
  1918. __func__, c->self, ssh_err(r));
  1919. }
  1920. }
  1921. #endif /* BROKEN_TCGETATTR_ICANON */
  1922. if ((r = sshbuf_consume(c->output, len)) != 0) {
  1923. fatal("%s: channel %d: consume: %s",
  1924. __func__, c->self, ssh_err(r));
  1925. }
  1926. out:
  1927. c->local_consumed += olen - sshbuf_len(c->output);
  1928. return 1;
  1929. }
  1930. static int
  1931. channel_handle_efd_write(struct ssh *ssh, Channel *c,
  1932. fd_set *readset, fd_set *writeset)
  1933. {
  1934. int r;
  1935. ssize_t len;
  1936. if (!FD_ISSET(c->efd, writeset) || sshbuf_len(c->extended) == 0)
  1937. return 1;
  1938. len = write(c->efd, sshbuf_ptr(c->extended),
  1939. sshbuf_len(c->extended));
  1940. debug2("channel %d: written %zd to efd %d", c->self, len, c->efd);
  1941. if (len == -1 && (errno == EINTR || errno == EAGAIN ||
  1942. errno == EWOULDBLOCK))
  1943. return 1;
  1944. if (len <= 0) {
  1945. debug2("channel %d: closing write-efd %d", c->self, c->efd);
  1946. channel_close_fd(ssh, &c->efd);
  1947. } else {
  1948. if ((r = sshbuf_consume(c->extended, len)) != 0) {
  1949. fatal("%s: channel %d: consume: %s",
  1950. __func__, c->self, ssh_err(r));
  1951. }
  1952. c->local_consumed += len;
  1953. }
  1954. return 1;
  1955. }
  1956. static int
  1957. channel_handle_efd_read(struct ssh *ssh, Channel *c,
  1958. fd_set *readset, fd_set *writeset)
  1959. {
  1960. char buf[CHAN_RBUF];
  1961. ssize_t len;
  1962. int r, force;
  1963. force = c->isatty && c->detach_close && c->istate != CHAN_INPUT_CLOSED;
  1964. if (c->efd == -1 || (!force && !FD_ISSET(c->efd, readset)))
  1965. return 1;
  1966. len = read(c->efd, buf, sizeof(buf));
  1967. debug2("channel %d: read %zd from efd %d", c->self, len, c->efd);
  1968. if (len == -1 && (errno == EINTR || ((errno == EAGAIN ||
  1969. errno == EWOULDBLOCK) && !force)))
  1970. return 1;
  1971. if (len <= 0) {
  1972. debug2("channel %d: closing read-efd %d",
  1973. c->self, c->efd);
  1974. channel_close_fd(ssh, &c->efd);
  1975. } else {
  1976. if (c->extended_usage == CHAN_EXTENDED_IGNORE) {
  1977. debug3("channel %d: discard efd",
  1978. c->self);
  1979. } else if ((r = sshbuf_put(c->extended, buf, len)) != 0) {
  1980. fatal("%s: channel %d: append: %s",
  1981. __func__, c->self, ssh_err(r));
  1982. }
  1983. }
  1984. return 1;
  1985. }
  1986. static int
  1987. channel_handle_efd(struct ssh *ssh, Channel *c,
  1988. fd_set *readset, fd_set *writeset)
  1989. {
  1990. if (c->efd == -1)
  1991. return 1;
  1992. /** XXX handle drain efd, too */
  1993. if (c->extended_usage == CHAN_EXTENDED_WRITE)
  1994. return channel_handle_efd_write(ssh, c, readset, writeset);
  1995. else if (c->extended_usage == CHAN_EXTENDED_READ ||
  1996. c->extended_usage == CHAN_EXTENDED_IGNORE)
  1997. return channel_handle_efd_read(ssh, c, readset, writeset);
  1998. return 1;
  1999. }
  2000. static int
  2001. channel_check_window(struct ssh *ssh, Channel *c)
  2002. {
  2003. int r;
  2004. if (c->type == SSH_CHANNEL_OPEN &&
  2005. !(c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD)) &&
  2006. ((ssh_packet_is_interactive(ssh) &&
  2007. c->local_window_max - c->local_window > c->local_maxpacket*3) ||
  2008. c->local_window < c->local_window_max/2) &&
  2009. c->local_consumed > 0) {
  2010. u_int addition = 0;
  2011. u_int32_t tcpwinsz = channel_tcpwinsz(ssh);
  2012. /* adjust max window size if we are in a dynamic environment */
  2013. if (c->dynamic_window && (tcpwinsz > c->local_window_max)) {
  2014. /* grow the window somewhat aggressively to maintain pressure */
  2015. addition = 1.5 * (tcpwinsz - c->local_window_max);
  2016. c->local_window_max += addition;
  2017. debug("Channel: Window growth to %d by %d bytes", c->local_window_max, addition);
  2018. }
  2019. if (!c->have_remote_id)
  2020. fatal(":%s: channel %d: no remote id",
  2021. __func__, c->self);
  2022. if ((r = sshpkt_start(ssh,
  2023. SSH2_MSG_CHANNEL_WINDOW_ADJUST)) != 0 ||
  2024. (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
  2025. (r = sshpkt_put_u32(ssh, c->local_consumed + addition)) != 0 ||
  2026. (r = sshpkt_send(ssh)) != 0) {
  2027. fatal("%s: channel %i: %s", __func__,
  2028. c->self, ssh_err(r));
  2029. }
  2030. debug2("channel %d: window %d sent adjust %d",
  2031. c->self, c->local_window,
  2032. c->local_consumed + addition);
  2033. c->local_window += c->local_consumed + addition;
  2034. c->local_consumed = 0;
  2035. }
  2036. return 1;
  2037. }
  2038. static void
  2039. channel_post_open(struct ssh *ssh, Channel *c,
  2040. fd_set *readset, fd_set *writeset)
  2041. {
  2042. channel_handle_rfd(ssh, c, readset, writeset);
  2043. channel_handle_wfd(ssh, c, readset, writeset);
  2044. channel_handle_efd(ssh, c, readset, writeset);
  2045. channel_check_window(ssh, c);
  2046. }
  2047. static u_int
  2048. read_mux(struct ssh *ssh, Channel *c, u_int need)
  2049. {
  2050. char buf[CHAN_RBUF];
  2051. ssize_t len;
  2052. u_int rlen;
  2053. int r;
  2054. if (sshbuf_len(c->input) < need) {
  2055. rlen = need - sshbuf_len(c->input);
  2056. len = read(c->rfd, buf, MINIMUM(rlen, CHAN_RBUF));
  2057. if (len == -1 && (errno == EINTR || errno == EAGAIN))
  2058. return sshbuf_len(c->input);
  2059. if (len <= 0) {
  2060. debug2("channel %d: ctl read<=0 rfd %d len %zd",
  2061. c->self, c->rfd, len);
  2062. chan_read_failed(ssh, c);
  2063. return 0;
  2064. } else if ((r = sshbuf_put(c->input, buf, len)) != 0) {
  2065. fatal("%s: channel %d: append: %s",
  2066. __func__, c->self, ssh_err(r));
  2067. }
  2068. }
  2069. return sshbuf_len(c->input);
  2070. }
  2071. static void
  2072. channel_post_mux_client_read(struct ssh *ssh, Channel *c,
  2073. fd_set *readset, fd_set *writeset)
  2074. {
  2075. u_int need;
  2076. if (c->rfd == -1 || !FD_ISSET(c->rfd, readset))
  2077. return;
  2078. if (c->istate != CHAN_INPUT_OPEN && c->istate != CHAN_INPUT_WAIT_DRAIN)
  2079. return;
  2080. if (c->mux_pause)
  2081. return;
  2082. /*
  2083. * Don't not read past the precise end of packets to
  2084. * avoid disrupting fd passing.
  2085. */
  2086. if (read_mux(ssh, c, 4) < 4) /* read header */
  2087. return;
  2088. /* XXX sshbuf_peek_u32 */
  2089. need = PEEK_U32(sshbuf_ptr(c->input));
  2090. #define CHANNEL_MUX_MAX_PACKET (256 * 1024)
  2091. if (need > CHANNEL_MUX_MAX_PACKET) {
  2092. debug2("channel %d: packet too big %u > %u",
  2093. c->self, CHANNEL_MUX_MAX_PACKET, need);
  2094. chan_rcvd_oclose(ssh, c);
  2095. return;
  2096. }
  2097. if (read_mux(ssh, c, need + 4) < need + 4) /* read body */
  2098. return;
  2099. if (c->mux_rcb(ssh, c) != 0) {
  2100. debug("channel %d: mux_rcb failed", c->self);
  2101. chan_mark_dead(ssh, c);
  2102. return;
  2103. }
  2104. }
  2105. static void
  2106. channel_post_mux_client_write(struct ssh *ssh, Channel *c,
  2107. fd_set *readset, fd_set *writeset)
  2108. {
  2109. ssize_t len;
  2110. int r;
  2111. if (c->wfd == -1 || !FD_ISSET(c->wfd, writeset) ||
  2112. sshbuf_len(c->output) == 0)
  2113. return;
  2114. len = write(c->wfd, sshbuf_ptr(c->output), sshbuf_len(c->output));
  2115. if (len == -1 && (errno == EINTR || errno == EAGAIN))
  2116. return;
  2117. if (len <= 0) {
  2118. chan_mark_dead(ssh, c);
  2119. return;
  2120. }
  2121. if ((r = sshbuf_consume(c->output, len)) != 0)
  2122. fatal("%s: channel %d: consume: %s", __func__,
  2123. c->self, ssh_err(r));
  2124. }
  2125. static void
  2126. channel_post_mux_client(struct ssh *ssh, Channel *c,
  2127. fd_set *readset, fd_set *writeset)
  2128. {
  2129. channel_post_mux_client_read(ssh, c, readset, writeset);
  2130. channel_post_mux_client_write(ssh, c, readset, writeset);
  2131. }
  2132. static void
  2133. channel_post_mux_listener(struct ssh *ssh, Channel *c,
  2134. fd_set *readset, fd_set *writeset)
  2135. {
  2136. Channel *nc;
  2137. struct sockaddr_storage addr;
  2138. socklen_t addrlen;
  2139. int newsock;
  2140. uid_t euid;
  2141. gid_t egid;
  2142. if (!FD_ISSET(c->sock, readset))
  2143. return;
  2144. debug("multiplexing control connection");
  2145. /*
  2146. * Accept connection on control socket
  2147. */
  2148. memset(&addr, 0, sizeof(addr));
  2149. addrlen = sizeof(addr);
  2150. if ((newsock = accept(c->sock, (struct sockaddr*)&addr,
  2151. &addrlen)) == -1) {
  2152. error("%s accept: %s", __func__, strerror(errno));
  2153. if (errno == EMFILE || errno == ENFILE)
  2154. c->notbefore = monotime() + 1;
  2155. return;
  2156. }
  2157. if (getpeereid(newsock, &euid, &egid) == -1) {
  2158. error("%s getpeereid failed: %s", __func__,
  2159. strerror(errno));
  2160. close(newsock);
  2161. return;
  2162. }
  2163. if ((euid != 0) && (getuid() != euid)) {
  2164. error("multiplex uid mismatch: peer euid %u != uid %u",
  2165. (u_int)euid, (u_int)getuid());
  2166. close(newsock);
  2167. return;
  2168. }
  2169. nc = channel_new(ssh, "multiplex client", SSH_CHANNEL_MUX_CLIENT,
  2170. newsock, newsock, -1, c->local_window_max,
  2171. c->local_maxpacket, 0, "mux-control", 1);
  2172. nc->mux_rcb = c->mux_rcb;
  2173. debug3("%s: new mux channel %d fd %d", __func__, nc->self, nc->sock);
  2174. /* establish state */
  2175. nc->mux_rcb(ssh, nc);
  2176. /* mux state transitions must not elicit protocol messages */
  2177. nc->flags |= CHAN_LOCAL;
  2178. }
  2179. static void
  2180. channel_handler_init(struct ssh_channels *sc)
  2181. {
  2182. chan_fn **pre, **post;
  2183. if ((pre = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*pre))) == NULL ||
  2184. (post = calloc(SSH_CHANNEL_MAX_TYPE, sizeof(*post))) == NULL)
  2185. fatal("%s: allocation failed", __func__);
  2186. pre[SSH_CHANNEL_OPEN] = &channel_pre_open;
  2187. pre[SSH_CHANNEL_X11_OPEN] = &channel_pre_x11_open;
  2188. pre[SSH_CHANNEL_PORT_LISTENER] = &channel_pre_listener;
  2189. pre[SSH_CHANNEL_RPORT_LISTENER] = &channel_pre_listener;
  2190. pre[SSH_CHANNEL_UNIX_LISTENER] = &channel_pre_listener;
  2191. pre[SSH_CHANNEL_RUNIX_LISTENER] = &channel_pre_listener;
  2192. pre[SSH_CHANNEL_X11_LISTENER] = &channel_pre_listener;
  2193. pre[SSH_CHANNEL_AUTH_SOCKET] = &channel_pre_listener;
  2194. pre[SSH_CHANNEL_CONNECTING] = &channel_pre_connecting;
  2195. pre[SSH_CHANNEL_DYNAMIC] = &channel_pre_dynamic;
  2196. pre[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_pre_connecting;
  2197. pre[SSH_CHANNEL_MUX_LISTENER] = &channel_pre_listener;
  2198. pre[SSH_CHANNEL_MUX_CLIENT] = &channel_pre_mux_client;
  2199. post[SSH_CHANNEL_OPEN] = &channel_post_open;
  2200. post[SSH_CHANNEL_PORT_LISTENER] = &channel_post_port_listener;
  2201. post[SSH_CHANNEL_RPORT_LISTENER] = &channel_post_port_listener;
  2202. post[SSH_CHANNEL_UNIX_LISTENER] = &channel_post_port_listener;
  2203. post[SSH_CHANNEL_RUNIX_LISTENER] = &channel_post_port_listener;
  2204. post[SSH_CHANNEL_X11_LISTENER] = &channel_post_x11_listener;
  2205. post[SSH_CHANNEL_AUTH_SOCKET] = &channel_post_auth_listener;
  2206. post[SSH_CHANNEL_CONNECTING] = &channel_post_connecting;
  2207. post[SSH_CHANNEL_DYNAMIC] = &channel_post_open;
  2208. post[SSH_CHANNEL_RDYNAMIC_FINISH] = &channel_post_connecting;
  2209. post[SSH_CHANNEL_MUX_LISTENER] = &channel_post_mux_listener;
  2210. post[SSH_CHANNEL_MUX_CLIENT] = &channel_post_mux_client;
  2211. sc->channel_pre = pre;
  2212. sc->channel_post = post;
  2213. }
  2214. /* gc dead channels */
  2215. static void
  2216. channel_garbage_collect(struct ssh *ssh, Channel *c)
  2217. {
  2218. if (c == NULL)
  2219. return;
  2220. if (c->detach_user != NULL) {
  2221. if (!chan_is_dead(ssh, c, c->detach_close))
  2222. return;
  2223. debug2("channel %d: gc: notify user", c->self);
  2224. c->detach_user(ssh, c->self, NULL);
  2225. /* if we still have a callback */
  2226. if (c->detach_user != NULL)
  2227. return;
  2228. debug2("channel %d: gc: user detached", c->self);
  2229. }
  2230. if (!chan_is_dead(ssh, c, 1))
  2231. return;
  2232. debug2("channel %d: garbage collecting", c->self);
  2233. channel_free(ssh, c);
  2234. }
  2235. enum channel_table { CHAN_PRE, CHAN_POST };
  2236. static void
  2237. channel_handler(struct ssh *ssh, int table,
  2238. fd_set *readset, fd_set *writeset, time_t *unpause_secs)
  2239. {
  2240. struct ssh_channels *sc = ssh->chanctxt;
  2241. chan_fn **ftab = table == CHAN_PRE ? sc->channel_pre : sc->channel_post;
  2242. u_int i, oalloc;
  2243. Channel *c;
  2244. time_t now;
  2245. now = monotime();
  2246. if (unpause_secs != NULL)
  2247. *unpause_secs = 0;
  2248. for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
  2249. c = sc->channels[i];
  2250. if (c == NULL)
  2251. continue;
  2252. if (c->delayed) {
  2253. if (table == CHAN_PRE)
  2254. c->delayed = 0;
  2255. else
  2256. continue;
  2257. }
  2258. if (ftab[c->type] != NULL) {
  2259. /*
  2260. * Run handlers that are not paused.
  2261. */
  2262. if (c->notbefore <= now)
  2263. (*ftab[c->type])(ssh, c, readset, writeset);
  2264. else if (unpause_secs != NULL) {
  2265. /*
  2266. * Collect the time that the earliest
  2267. * channel comes off pause.
  2268. */
  2269. debug3("%s: chan %d: skip for %d more seconds",
  2270. __func__, c->self,
  2271. (int)(c->notbefore - now));
  2272. if (*unpause_secs == 0 ||
  2273. (c->notbefore - now) < *unpause_secs)
  2274. *unpause_secs = c->notbefore - now;
  2275. }
  2276. }
  2277. channel_garbage_collect(ssh, c);
  2278. }
  2279. if (unpause_secs != NULL && *unpause_secs != 0)
  2280. debug3("%s: first channel unpauses in %d seconds",
  2281. __func__, (int)*unpause_secs);
  2282. }
  2283. /*
  2284. * Create sockets before allocating the select bitmasks.
  2285. * This is necessary for things that need to happen after reading
  2286. * the network-input but before channel_prepare_select().
  2287. */
  2288. static void
  2289. channel_before_prepare_select(struct ssh *ssh)
  2290. {
  2291. struct ssh_channels *sc = ssh->chanctxt;
  2292. Channel *c;
  2293. u_int i, oalloc;
  2294. for (i = 0, oalloc = sc->channels_alloc; i < oalloc; i++) {
  2295. c = sc->channels[i];
  2296. if (c == NULL)
  2297. continue;
  2298. if (c->type == SSH_CHANNEL_RDYNAMIC_OPEN)
  2299. channel_before_prepare_select_rdynamic(ssh, c);
  2300. }
  2301. }
  2302. /*
  2303. * Allocate/update select bitmasks and add any bits relevant to channels in
  2304. * select bitmasks.
  2305. */
  2306. void
  2307. channel_prepare_select(struct ssh *ssh, fd_set **readsetp, fd_set **writesetp,
  2308. int *maxfdp, u_int *nallocp, time_t *minwait_secs)
  2309. {
  2310. u_int n, sz, nfdset;
  2311. channel_before_prepare_select(ssh); /* might update channel_max_fd */
  2312. n = MAXIMUM(*maxfdp, ssh->chanctxt->channel_max_fd);
  2313. nfdset = howmany(n+1, NFDBITS);
  2314. /* Explicitly test here, because xrealloc isn't always called */
  2315. if (nfdset && SIZE_MAX / nfdset < sizeof(fd_mask))
  2316. fatal("channel_prepare_select: max_fd (%d) is too large", n);
  2317. sz = nfdset * sizeof(fd_mask);
  2318. /* perhaps check sz < nalloc/2 and shrink? */
  2319. if (*readsetp == NULL || sz > *nallocp) {
  2320. *readsetp = xreallocarray(*readsetp, nfdset, sizeof(fd_mask));
  2321. *writesetp = xreallocarray(*writesetp, nfdset, sizeof(fd_mask));
  2322. *nallocp = sz;
  2323. }
  2324. *maxfdp = n;
  2325. memset(*readsetp, 0, sz);
  2326. memset(*writesetp, 0, sz);
  2327. if (!ssh_packet_is_rekeying(ssh))
  2328. channel_handler(ssh, CHAN_PRE, *readsetp, *writesetp,
  2329. minwait_secs);
  2330. }
  2331. /*
  2332. * After select, perform any appropriate operations for channels which have
  2333. * events pending.
  2334. */
  2335. void
  2336. channel_after_select(struct ssh *ssh, fd_set *readset, fd_set *writeset)
  2337. {
  2338. channel_handler(ssh, CHAN_POST, readset, writeset, NULL);
  2339. }
  2340. /*
  2341. * Enqueue data for channels with open or draining c->input.
  2342. */
  2343. static void
  2344. channel_output_poll_input_open(struct ssh *ssh, Channel *c)
  2345. {
  2346. size_t len, plen;
  2347. const u_char *pkt;
  2348. int r;
  2349. if ((len = sshbuf_len(c->input)) == 0) {
  2350. if (c->istate == CHAN_INPUT_WAIT_DRAIN) {
  2351. /*
  2352. * input-buffer is empty and read-socket shutdown:
  2353. * tell peer, that we will not send more data:
  2354. * send IEOF.
  2355. * hack for extended data: delay EOF if EFD still
  2356. * in use.
  2357. */
  2358. if (CHANNEL_EFD_INPUT_ACTIVE(c))
  2359. debug2("channel %d: "
  2360. "ibuf_empty delayed efd %d/(%zu)",
  2361. c->self, c->efd, sshbuf_len(c->extended));
  2362. else
  2363. chan_ibuf_empty(ssh, c);
  2364. }
  2365. return;
  2366. }
  2367. if (!c->have_remote_id)
  2368. fatal(":%s: channel %d: no remote id", __func__, c->self);
  2369. if (c->datagram) {
  2370. /* Check datagram will fit; drop if not */
  2371. if ((r = sshbuf_get_string_direct(c->input, &pkt, &plen)) != 0)
  2372. fatal("%s: channel %d: get datagram: %s", __func__,
  2373. c->self, ssh_err(r));
  2374. /*
  2375. * XXX this does tail-drop on the datagram queue which is
  2376. * usually suboptimal compared to head-drop. Better to have
  2377. * backpressure at read time? (i.e. read + discard)
  2378. */
  2379. if (plen > c->remote_window || plen > c->remote_maxpacket) {
  2380. debug("channel %d: datagram too big", c->self);
  2381. return;
  2382. }
  2383. /* Enqueue it */
  2384. if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
  2385. (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
  2386. (r = sshpkt_put_string(ssh, pkt, plen)) != 0 ||
  2387. (r = sshpkt_send(ssh)) != 0) {
  2388. fatal("%s: channel %i: datagram: %s", __func__,
  2389. c->self, ssh_err(r));
  2390. }
  2391. c->remote_window -= plen;
  2392. }
  2393. /* Enqueue packet for buffered data. */
  2394. if (len > c->remote_window)
  2395. len = c->remote_window;
  2396. if (len > c->remote_maxpacket)
  2397. len = c->remote_maxpacket;
  2398. if (len == 0)
  2399. return;
  2400. if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_DATA)) != 0 ||
  2401. (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
  2402. (r = sshpkt_put_string(ssh, sshbuf_ptr(c->input), len)) != 0 ||
  2403. (r = sshpkt_send(ssh)) != 0) {
  2404. fatal("%s: channel %i: data: %s", __func__,
  2405. c->self, ssh_err(r));
  2406. }
  2407. if ((r = sshbuf_consume(c->input, len)) != 0)
  2408. fatal("%s: channel %i: consume: %s", __func__,
  2409. c->self, ssh_err(r));
  2410. c->remote_window -= len;
  2411. }
  2412. /*
  2413. * Enqueue data for channels with open c->extended in read mode.
  2414. */
  2415. static void
  2416. channel_output_poll_extended_read(struct ssh *ssh, Channel *c)
  2417. {
  2418. size_t len;
  2419. int r;
  2420. if ((len = sshbuf_len(c->extended)) == 0)
  2421. return;
  2422. debug2("channel %d: rwin %u elen %zu euse %d", c->self,
  2423. c->remote_window, sshbuf_len(c->extended), c->extended_usage);
  2424. if (len > c->remote_window)
  2425. len = c->remote_window;
  2426. if (len > c->remote_maxpacket)
  2427. len = c->remote_maxpacket;
  2428. if (len == 0)
  2429. return;
  2430. if (!c->have_remote_id)
  2431. fatal(":%s: channel %d: no remote id", __func__, c->self);
  2432. if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_EXTENDED_DATA)) != 0 ||
  2433. (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
  2434. (r = sshpkt_put_u32(ssh, SSH2_EXTENDED_DATA_STDERR)) != 0 ||
  2435. (r = sshpkt_put_string(ssh, sshbuf_ptr(c->extended), len)) != 0 ||
  2436. (r = sshpkt_send(ssh)) != 0) {
  2437. fatal("%s: channel %i: data: %s", __func__,
  2438. c->self, ssh_err(r));
  2439. }
  2440. if ((r = sshbuf_consume(c->extended, len)) != 0)
  2441. fatal("%s: channel %i: consume: %s", __func__,
  2442. c->self, ssh_err(r));
  2443. c->remote_window -= len;
  2444. debug2("channel %d: sent ext data %zu", c->self, len);
  2445. }
  2446. /* If there is data to send to the connection, enqueue some of it now. */
  2447. void
  2448. channel_output_poll(struct ssh *ssh)
  2449. {
  2450. struct ssh_channels *sc = ssh->chanctxt;
  2451. Channel *c;
  2452. u_int i;
  2453. for (i = 0; i < sc->channels_alloc; i++) {
  2454. c = sc->channels[i];
  2455. if (c == NULL)
  2456. continue;
  2457. /*
  2458. * We are only interested in channels that can have buffered
  2459. * incoming data.
  2460. */
  2461. if (c->type != SSH_CHANNEL_OPEN)
  2462. continue;
  2463. if ((c->flags & (CHAN_CLOSE_SENT|CHAN_CLOSE_RCVD))) {
  2464. /* XXX is this true? */
  2465. debug3("channel %d: will not send data after close",
  2466. c->self);
  2467. continue;
  2468. }
  2469. /* Get the amount of buffered data for this channel. */
  2470. if (c->istate == CHAN_INPUT_OPEN ||
  2471. c->istate == CHAN_INPUT_WAIT_DRAIN)
  2472. channel_output_poll_input_open(ssh, c);
  2473. /* Send extended data, i.e. stderr */
  2474. if (!(c->flags & CHAN_EOF_SENT) &&
  2475. c->extended_usage == CHAN_EXTENDED_READ)
  2476. channel_output_poll_extended_read(ssh, c);
  2477. }
  2478. }
  2479. /* -- mux proxy support */
  2480. /*
  2481. * When multiplexing channel messages for mux clients we have to deal
  2482. * with downstream messages from the mux client and upstream messages
  2483. * from the ssh server:
  2484. * 1) Handling downstream messages is straightforward and happens
  2485. * in channel_proxy_downstream():
  2486. * - We forward all messages (mostly) unmodified to the server.
  2487. * - However, in order to route messages from upstream to the correct
  2488. * downstream client, we have to replace the channel IDs used by the
  2489. * mux clients with a unique channel ID because the mux clients might
  2490. * use conflicting channel IDs.
  2491. * - so we inspect and change both SSH2_MSG_CHANNEL_OPEN and
  2492. * SSH2_MSG_CHANNEL_OPEN_CONFIRMATION messages, create a local
  2493. * SSH_CHANNEL_MUX_PROXY channel and replace the mux clients ID
  2494. * with the newly allocated channel ID.
  2495. * 2) Upstream messages are received by matching SSH_CHANNEL_MUX_PROXY
  2496. * channels and processed by channel_proxy_upstream(). The local channel ID
  2497. * is then translated back to the original mux client ID.
  2498. * 3) In both cases we need to keep track of matching SSH2_MSG_CHANNEL_CLOSE
  2499. * messages so we can clean up SSH_CHANNEL_MUX_PROXY channels.
  2500. * 4) The SSH_CHANNEL_MUX_PROXY channels also need to closed when the
  2501. * downstream mux client are removed.
  2502. * 5) Handling SSH2_MSG_CHANNEL_OPEN messages from the upstream server
  2503. * requires more work, because they are not addressed to a specific
  2504. * channel. E.g. client_request_forwarded_tcpip() needs to figure
  2505. * out whether the request is addressed to the local client or a
  2506. * specific downstream client based on the listen-address/port.
  2507. * 6) Agent and X11-Forwarding have a similar problem and are currently
  2508. * not supported as the matching session/channel cannot be identified
  2509. * easily.
  2510. */
  2511. /*
  2512. * receive packets from downstream mux clients:
  2513. * channel callback fired on read from mux client, creates
  2514. * SSH_CHANNEL_MUX_PROXY channels and translates channel IDs
  2515. * on channel creation.
  2516. */
  2517. int
  2518. channel_proxy_downstream(struct ssh *ssh, Channel *downstream)
  2519. {
  2520. Channel *c = NULL;
  2521. struct sshbuf *original = NULL, *modified = NULL;
  2522. const u_char *cp;
  2523. char *ctype = NULL, *listen_host = NULL;
  2524. u_char type;
  2525. size_t have;
  2526. int ret = -1, r;
  2527. u_int id, remote_id, listen_port;
  2528. /* sshbuf_dump(downstream->input, stderr); */
  2529. if ((r = sshbuf_get_string_direct(downstream->input, &cp, &have))
  2530. != 0) {
  2531. error("%s: malformed message: %s", __func__, ssh_err(r));
  2532. return -1;
  2533. }
  2534. if (have < 2) {
  2535. error("%s: short message", __func__);
  2536. return -1;
  2537. }
  2538. type = cp[1];
  2539. /* skip padlen + type */
  2540. cp += 2;
  2541. have -= 2;
  2542. if (ssh_packet_log_type(type))
  2543. debug3("%s: channel %u: down->up: type %u", __func__,
  2544. downstream->self, type);
  2545. switch (type) {
  2546. case SSH2_MSG_CHANNEL_OPEN:
  2547. if ((original = sshbuf_from(cp, have)) == NULL ||
  2548. (modified = sshbuf_new()) == NULL) {
  2549. error("%s: alloc", __func__);
  2550. goto out;
  2551. }
  2552. if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0 ||
  2553. (r = sshbuf_get_u32(original, &id)) != 0) {
  2554. error("%s: parse error %s", __func__, ssh_err(r));
  2555. goto out;
  2556. }
  2557. c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
  2558. -1, -1, -1, 0, 0, 0, ctype, 1);
  2559. c->mux_ctx = downstream; /* point to mux client */
  2560. c->mux_downstream_id = id; /* original downstream id */
  2561. if ((r = sshbuf_put_cstring(modified, ctype)) != 0 ||
  2562. (r = sshbuf_put_u32(modified, c->self)) != 0 ||
  2563. (r = sshbuf_putb(modified, original)) != 0) {
  2564. error("%s: compose error %s", __func__, ssh_err(r));
  2565. channel_free(ssh, c);
  2566. goto out;
  2567. }
  2568. break;
  2569. case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
  2570. /*
  2571. * Almost the same as SSH2_MSG_CHANNEL_OPEN, except then we
  2572. * need to parse 'remote_id' instead of 'ctype'.
  2573. */
  2574. if ((original = sshbuf_from(cp, have)) == NULL ||
  2575. (modified = sshbuf_new()) == NULL) {
  2576. error("%s: alloc", __func__);
  2577. goto out;
  2578. }
  2579. if ((r = sshbuf_get_u32(original, &remote_id)) != 0 ||
  2580. (r = sshbuf_get_u32(original, &id)) != 0) {
  2581. error("%s: parse error %s", __func__, ssh_err(r));
  2582. goto out;
  2583. }
  2584. c = channel_new(ssh, "mux proxy", SSH_CHANNEL_MUX_PROXY,
  2585. -1, -1, -1, 0, 0, 0, "mux-down-connect", 1);
  2586. c->mux_ctx = downstream; /* point to mux client */
  2587. c->mux_downstream_id = id;
  2588. c->remote_id = remote_id;
  2589. c->have_remote_id = 1;
  2590. if ((r = sshbuf_put_u32(modified, remote_id)) != 0 ||
  2591. (r = sshbuf_put_u32(modified, c->self)) != 0 ||
  2592. (r = sshbuf_putb(modified, original)) != 0) {
  2593. error("%s: compose error %s", __func__, ssh_err(r));
  2594. channel_free(ssh, c);
  2595. goto out;
  2596. }
  2597. break;
  2598. case SSH2_MSG_GLOBAL_REQUEST:
  2599. if ((original = sshbuf_from(cp, have)) == NULL) {
  2600. error("%s: alloc", __func__);
  2601. goto out;
  2602. }
  2603. if ((r = sshbuf_get_cstring(original, &ctype, NULL)) != 0) {
  2604. error("%s: parse error %s", __func__, ssh_err(r));
  2605. goto out;
  2606. }
  2607. if (strcmp(ctype, "tcpip-forward") != 0) {
  2608. error("%s: unsupported request %s", __func__, ctype);
  2609. goto out;
  2610. }
  2611. if ((r = sshbuf_get_u8(original, NULL)) != 0 ||
  2612. (r = sshbuf_get_cstring(original, &listen_host, NULL)) != 0 ||
  2613. (r = sshbuf_get_u32(original, &listen_port)) != 0) {
  2614. error("%s: parse error %s", __func__, ssh_err(r));
  2615. goto out;
  2616. }
  2617. if (listen_port > 65535) {
  2618. error("%s: tcpip-forward for %s: bad port %u",
  2619. __func__, listen_host, listen_port);
  2620. goto out;
  2621. }
  2622. /* Record that connection to this host/port is permitted. */
  2623. permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL, "<mux>", -1,
  2624. listen_host, NULL, (int)listen_port, downstream);
  2625. listen_host = NULL;
  2626. break;
  2627. case SSH2_MSG_CHANNEL_CLOSE:
  2628. if (have < 4)
  2629. break;
  2630. remote_id = PEEK_U32(cp);
  2631. if ((c = channel_by_remote_id(ssh, remote_id)) != NULL) {
  2632. if (c->flags & CHAN_CLOSE_RCVD)
  2633. channel_free(ssh, c);
  2634. else
  2635. c->flags |= CHAN_CLOSE_SENT;
  2636. }
  2637. break;
  2638. }
  2639. if (modified) {
  2640. if ((r = sshpkt_start(ssh, type)) != 0 ||
  2641. (r = sshpkt_putb(ssh, modified)) != 0 ||
  2642. (r = sshpkt_send(ssh)) != 0) {
  2643. error("%s: send %s", __func__, ssh_err(r));
  2644. goto out;
  2645. }
  2646. } else {
  2647. if ((r = sshpkt_start(ssh, type)) != 0 ||
  2648. (r = sshpkt_put(ssh, cp, have)) != 0 ||
  2649. (r = sshpkt_send(ssh)) != 0) {
  2650. error("%s: send %s", __func__, ssh_err(r));
  2651. goto out;
  2652. }
  2653. }
  2654. ret = 0;
  2655. out:
  2656. free(ctype);
  2657. free(listen_host);
  2658. sshbuf_free(original);
  2659. sshbuf_free(modified);
  2660. return ret;
  2661. }
  2662. /*
  2663. * receive packets from upstream server and de-multiplex packets
  2664. * to correct downstream:
  2665. * implemented as a helper for channel input handlers,
  2666. * replaces local (proxy) channel ID with downstream channel ID.
  2667. */
  2668. int
  2669. channel_proxy_upstream(Channel *c, int type, u_int32_t seq, struct ssh *ssh)
  2670. {
  2671. struct sshbuf *b = NULL;
  2672. Channel *downstream;
  2673. const u_char *cp = NULL;
  2674. size_t len;
  2675. int r;
  2676. /*
  2677. * When receiving packets from the peer we need to check whether we
  2678. * need to forward the packets to the mux client. In this case we
  2679. * restore the original channel id and keep track of CLOSE messages,
  2680. * so we can cleanup the channel.
  2681. */
  2682. if (c == NULL || c->type != SSH_CHANNEL_MUX_PROXY)
  2683. return 0;
  2684. if ((downstream = c->mux_ctx) == NULL)
  2685. return 0;
  2686. switch (type) {
  2687. case SSH2_MSG_CHANNEL_CLOSE:
  2688. case SSH2_MSG_CHANNEL_DATA:
  2689. case SSH2_MSG_CHANNEL_EOF:
  2690. case SSH2_MSG_CHANNEL_EXTENDED_DATA:
  2691. case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
  2692. case SSH2_MSG_CHANNEL_OPEN_FAILURE:
  2693. case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
  2694. case SSH2_MSG_CHANNEL_SUCCESS:
  2695. case SSH2_MSG_CHANNEL_FAILURE:
  2696. case SSH2_MSG_CHANNEL_REQUEST:
  2697. break;
  2698. default:
  2699. debug2("%s: channel %u: unsupported type %u", __func__,
  2700. c->self, type);
  2701. return 0;
  2702. }
  2703. if ((b = sshbuf_new()) == NULL) {
  2704. error("%s: alloc reply", __func__);
  2705. goto out;
  2706. }
  2707. /* get remaining payload (after id) */
  2708. cp = sshpkt_ptr(ssh, &len);
  2709. if (cp == NULL) {
  2710. error("%s: no packet", __func__);
  2711. goto out;
  2712. }
  2713. /* translate id and send to muxclient */
  2714. if ((r = sshbuf_put_u8(b, 0)) != 0 || /* padlen */
  2715. (r = sshbuf_put_u8(b, type)) != 0 ||
  2716. (r = sshbuf_put_u32(b, c->mux_downstream_id)) != 0 ||
  2717. (r = sshbuf_put(b, cp, len)) != 0 ||
  2718. (r = sshbuf_put_stringb(downstream->output, b)) != 0) {
  2719. error("%s: compose for muxclient %s", __func__, ssh_err(r));
  2720. goto out;
  2721. }
  2722. /* sshbuf_dump(b, stderr); */
  2723. if (ssh_packet_log_type(type))
  2724. debug3("%s: channel %u: up->down: type %u", __func__, c->self,
  2725. type);
  2726. out:
  2727. /* update state */
  2728. switch (type) {
  2729. case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
  2730. /* record remote_id for SSH2_MSG_CHANNEL_CLOSE */
  2731. if (cp && len > 4) {
  2732. c->remote_id = PEEK_U32(cp);
  2733. c->have_remote_id = 1;
  2734. }
  2735. break;
  2736. case SSH2_MSG_CHANNEL_CLOSE:
  2737. if (c->flags & CHAN_CLOSE_SENT)
  2738. channel_free(ssh, c);
  2739. else
  2740. c->flags |= CHAN_CLOSE_RCVD;
  2741. break;
  2742. }
  2743. sshbuf_free(b);
  2744. return 1;
  2745. }
  2746. /* -- protocol input */
  2747. /* Parse a channel ID from the current packet */
  2748. static int
  2749. channel_parse_id(struct ssh *ssh, const char *where, const char *what)
  2750. {
  2751. u_int32_t id;
  2752. int r;
  2753. if ((r = sshpkt_get_u32(ssh, &id)) != 0) {
  2754. error("%s: parse id: %s", where, ssh_err(r));
  2755. ssh_packet_disconnect(ssh, "Invalid %s message", what);
  2756. }
  2757. if (id > INT_MAX) {
  2758. error("%s: bad channel id %u: %s", where, id, ssh_err(r));
  2759. ssh_packet_disconnect(ssh, "Invalid %s channel id", what);
  2760. }
  2761. return (int)id;
  2762. }
  2763. /* Lookup a channel from an ID in the current packet */
  2764. static Channel *
  2765. channel_from_packet_id(struct ssh *ssh, const char *where, const char *what)
  2766. {
  2767. int id = channel_parse_id(ssh, where, what);
  2768. Channel *c;
  2769. if ((c = channel_lookup(ssh, id)) == NULL) {
  2770. ssh_packet_disconnect(ssh,
  2771. "%s packet referred to nonexistent channel %d", what, id);
  2772. }
  2773. return c;
  2774. }
  2775. int
  2776. channel_input_data(int type, u_int32_t seq, struct ssh *ssh)
  2777. {
  2778. const u_char *data;
  2779. size_t data_len, win_len;
  2780. Channel *c = channel_from_packet_id(ssh, __func__, "data");
  2781. int r;
  2782. if (channel_proxy_upstream(c, type, seq, ssh))
  2783. return 0;
  2784. /* Ignore any data for non-open channels (might happen on close) */
  2785. if (c->type != SSH_CHANNEL_OPEN &&
  2786. c->type != SSH_CHANNEL_RDYNAMIC_OPEN &&
  2787. c->type != SSH_CHANNEL_RDYNAMIC_FINISH &&
  2788. c->type != SSH_CHANNEL_X11_OPEN)
  2789. return 0;
  2790. /* Get the data. */
  2791. if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
  2792. (r = sshpkt_get_end(ssh)) != 0)
  2793. fatal("%s: channel %d: get data: %s", __func__,
  2794. c->self, ssh_err(r));
  2795. win_len = data_len;
  2796. if (c->datagram)
  2797. win_len += 4; /* string length header */
  2798. /*
  2799. * The sending side reduces its window as it sends data, so we
  2800. * must 'fake' consumption of the data in order to ensure that window
  2801. * updates are sent back. Otherwise the connection might deadlock.
  2802. */
  2803. if (c->ostate != CHAN_OUTPUT_OPEN) {
  2804. c->local_window -= win_len;
  2805. c->local_consumed += win_len;
  2806. return 0;
  2807. }
  2808. if (win_len > c->local_maxpacket) {
  2809. logit("channel %d: rcvd big packet %zu, maxpack %u",
  2810. c->self, win_len, c->local_maxpacket);
  2811. return 0;
  2812. }
  2813. if (win_len > c->local_window) {
  2814. logit("channel %d: rcvd too much data %zu, win %u",
  2815. c->self, win_len, c->local_window);
  2816. return 0;
  2817. }
  2818. c->local_window -= win_len;
  2819. if (c->datagram) {
  2820. if ((r = sshbuf_put_string(c->output, data, data_len)) != 0)
  2821. fatal("%s: channel %d: append datagram: %s",
  2822. __func__, c->self, ssh_err(r));
  2823. } else if ((r = sshbuf_put(c->output, data, data_len)) != 0)
  2824. fatal("%s: channel %d: append data: %s",
  2825. __func__, c->self, ssh_err(r));
  2826. return 0;
  2827. }
  2828. int
  2829. channel_input_extended_data(int type, u_int32_t seq, struct ssh *ssh)
  2830. {
  2831. const u_char *data;
  2832. size_t data_len;
  2833. u_int32_t tcode;
  2834. Channel *c = channel_from_packet_id(ssh, __func__, "extended data");
  2835. int r;
  2836. if (channel_proxy_upstream(c, type, seq, ssh))
  2837. return 0;
  2838. if (c->type != SSH_CHANNEL_OPEN) {
  2839. logit("channel %d: ext data for non open", c->self);
  2840. return 0;
  2841. }
  2842. if (c->flags & CHAN_EOF_RCVD) {
  2843. if (ssh->compat & SSH_BUG_EXTEOF)
  2844. debug("channel %d: accepting ext data after eof",
  2845. c->self);
  2846. else
  2847. ssh_packet_disconnect(ssh, "Received extended_data "
  2848. "after EOF on channel %d.", c->self);
  2849. }
  2850. if ((r = sshpkt_get_u32(ssh, &tcode)) != 0) {
  2851. error("%s: parse tcode: %s", __func__, ssh_err(r));
  2852. ssh_packet_disconnect(ssh, "Invalid extended_data message");
  2853. }
  2854. if (c->efd == -1 ||
  2855. c->extended_usage != CHAN_EXTENDED_WRITE ||
  2856. tcode != SSH2_EXTENDED_DATA_STDERR) {
  2857. logit("channel %d: bad ext data", c->self);
  2858. return 0;
  2859. }
  2860. if ((r = sshpkt_get_string_direct(ssh, &data, &data_len)) != 0 ||
  2861. (r = sshpkt_get_end(ssh)) != 0) {
  2862. error("%s: parse data: %s", __func__, ssh_err(r));
  2863. ssh_packet_disconnect(ssh, "Invalid extended_data message");
  2864. }
  2865. if (data_len > c->local_window) {
  2866. logit("channel %d: rcvd too much extended_data %zu, win %u",
  2867. c->self, data_len, c->local_window);
  2868. return 0;
  2869. }
  2870. debug2("channel %d: rcvd ext data %zu", c->self, data_len);
  2871. /* XXX sshpkt_getb? */
  2872. if ((r = sshbuf_put(c->extended, data, data_len)) != 0)
  2873. error("%s: append: %s", __func__, ssh_err(r));
  2874. c->local_window -= data_len;
  2875. return 0;
  2876. }
  2877. int
  2878. channel_input_ieof(int type, u_int32_t seq, struct ssh *ssh)
  2879. {
  2880. Channel *c = channel_from_packet_id(ssh, __func__, "ieof");
  2881. int r;
  2882. if ((r = sshpkt_get_end(ssh)) != 0) {
  2883. error("%s: parse data: %s", __func__, ssh_err(r));
  2884. ssh_packet_disconnect(ssh, "Invalid ieof message");
  2885. }
  2886. if (channel_proxy_upstream(c, type, seq, ssh))
  2887. return 0;
  2888. chan_rcvd_ieof(ssh, c);
  2889. /* XXX force input close */
  2890. if (c->force_drain && c->istate == CHAN_INPUT_OPEN) {
  2891. debug("channel %d: FORCE input drain", c->self);
  2892. c->istate = CHAN_INPUT_WAIT_DRAIN;
  2893. if (sshbuf_len(c->input) == 0)
  2894. chan_ibuf_empty(ssh, c);
  2895. }
  2896. return 0;
  2897. }
  2898. int
  2899. channel_input_oclose(int type, u_int32_t seq, struct ssh *ssh)
  2900. {
  2901. Channel *c = channel_from_packet_id(ssh, __func__, "oclose");
  2902. int r;
  2903. if (channel_proxy_upstream(c, type, seq, ssh))
  2904. return 0;
  2905. if ((r = sshpkt_get_end(ssh)) != 0) {
  2906. error("%s: parse data: %s", __func__, ssh_err(r));
  2907. ssh_packet_disconnect(ssh, "Invalid oclose message");
  2908. }
  2909. chan_rcvd_oclose(ssh, c);
  2910. return 0;
  2911. }
  2912. int
  2913. channel_input_open_confirmation(int type, u_int32_t seq, struct ssh *ssh)
  2914. {
  2915. Channel *c = channel_from_packet_id(ssh, __func__, "open confirmation");
  2916. u_int32_t remote_window, remote_maxpacket;
  2917. int r;
  2918. if (channel_proxy_upstream(c, type, seq, ssh))
  2919. return 0;
  2920. if (c->type != SSH_CHANNEL_OPENING)
  2921. ssh_packet_disconnect(ssh, "Received open confirmation for "
  2922. "non-opening channel %d.", c->self);
  2923. /*
  2924. * Record the remote channel number and mark that the channel
  2925. * is now open.
  2926. */
  2927. if ((r = sshpkt_get_u32(ssh, &c->remote_id)) != 0 ||
  2928. (r = sshpkt_get_u32(ssh, &remote_window)) != 0 ||
  2929. (r = sshpkt_get_u32(ssh, &remote_maxpacket)) != 0 ||
  2930. (r = sshpkt_get_end(ssh)) != 0) {
  2931. error("%s: window/maxpacket: %s", __func__, ssh_err(r));
  2932. ssh_packet_disconnect(ssh, "Invalid open confirmation message");
  2933. }
  2934. c->have_remote_id = 1;
  2935. c->remote_window = remote_window;
  2936. c->remote_maxpacket = remote_maxpacket;
  2937. c->type = SSH_CHANNEL_OPEN;
  2938. if (c->open_confirm) {
  2939. debug2("%s: channel %d: callback start", __func__, c->self);
  2940. c->open_confirm(ssh, c->self, 1, c->open_confirm_ctx);
  2941. debug2("%s: channel %d: callback done", __func__, c->self);
  2942. }
  2943. debug2("channel %d: open confirm rwindow %u rmax %u", c->self,
  2944. c->remote_window, c->remote_maxpacket);
  2945. return 0;
  2946. }
  2947. static char *
  2948. reason2txt(int reason)
  2949. {
  2950. switch (reason) {
  2951. case SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED:
  2952. return "administratively prohibited";
  2953. case SSH2_OPEN_CONNECT_FAILED:
  2954. return "connect failed";
  2955. case SSH2_OPEN_UNKNOWN_CHANNEL_TYPE:
  2956. return "unknown channel type";
  2957. case SSH2_OPEN_RESOURCE_SHORTAGE:
  2958. return "resource shortage";
  2959. }
  2960. return "unknown reason";
  2961. }
  2962. int
  2963. channel_input_open_failure(int type, u_int32_t seq, struct ssh *ssh)
  2964. {
  2965. Channel *c = channel_from_packet_id(ssh, __func__, "open failure");
  2966. u_int32_t reason;
  2967. char *msg = NULL;
  2968. int r;
  2969. if (channel_proxy_upstream(c, type, seq, ssh))
  2970. return 0;
  2971. if (c->type != SSH_CHANNEL_OPENING)
  2972. ssh_packet_disconnect(ssh, "Received open failure for "
  2973. "non-opening channel %d.", c->self);
  2974. if ((r = sshpkt_get_u32(ssh, &reason)) != 0) {
  2975. error("%s: reason: %s", __func__, ssh_err(r));
  2976. ssh_packet_disconnect(ssh, "Invalid open failure message");
  2977. }
  2978. /* skip language */
  2979. if ((r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 ||
  2980. (r = sshpkt_get_string_direct(ssh, NULL, NULL)) != 0 ||
  2981. (r = sshpkt_get_end(ssh)) != 0) {
  2982. error("%s: message/lang: %s", __func__, ssh_err(r));
  2983. ssh_packet_disconnect(ssh, "Invalid open failure message");
  2984. }
  2985. logit("channel %d: open failed: %s%s%s", c->self,
  2986. reason2txt(reason), msg ? ": ": "", msg ? msg : "");
  2987. free(msg);
  2988. if (c->open_confirm) {
  2989. debug2("%s: channel %d: callback start", __func__, c->self);
  2990. c->open_confirm(ssh, c->self, 0, c->open_confirm_ctx);
  2991. debug2("%s: channel %d: callback done", __func__, c->self);
  2992. }
  2993. /* Schedule the channel for cleanup/deletion. */
  2994. chan_mark_dead(ssh, c);
  2995. return 0;
  2996. }
  2997. int
  2998. channel_input_window_adjust(int type, u_int32_t seq, struct ssh *ssh)
  2999. {
  3000. int id = channel_parse_id(ssh, __func__, "window adjust");
  3001. Channel *c;
  3002. u_int32_t adjust;
  3003. u_int new_rwin;
  3004. int r;
  3005. if ((c = channel_lookup(ssh, id)) == NULL) {
  3006. logit("Received window adjust for non-open channel %d.", id);
  3007. return 0;
  3008. }
  3009. if (channel_proxy_upstream(c, type, seq, ssh))
  3010. return 0;
  3011. if ((r = sshpkt_get_u32(ssh, &adjust)) != 0 ||
  3012. (r = sshpkt_get_end(ssh)) != 0) {
  3013. error("%s: adjust: %s", __func__, ssh_err(r));
  3014. ssh_packet_disconnect(ssh, "Invalid window adjust message");
  3015. }
  3016. debug2("channel %d: rcvd adjust %u", c->self, adjust);
  3017. if ((new_rwin = c->remote_window + adjust) < c->remote_window) {
  3018. fatal("channel %d: adjust %u overflows remote window %u",
  3019. c->self, adjust, c->remote_window);
  3020. }
  3021. c->remote_window = new_rwin;
  3022. return 0;
  3023. }
  3024. int
  3025. channel_input_status_confirm(int type, u_int32_t seq, struct ssh *ssh)
  3026. {
  3027. int id = channel_parse_id(ssh, __func__, "status confirm");
  3028. Channel *c;
  3029. struct channel_confirm *cc;
  3030. /* Reset keepalive timeout */
  3031. ssh_packet_set_alive_timeouts(ssh, 0);
  3032. debug2("%s: type %d id %d", __func__, type, id);
  3033. if ((c = channel_lookup(ssh, id)) == NULL) {
  3034. logit("%s: %d: unknown", __func__, id);
  3035. return 0;
  3036. }
  3037. if (channel_proxy_upstream(c, type, seq, ssh))
  3038. return 0;
  3039. if (sshpkt_get_end(ssh) != 0)
  3040. ssh_packet_disconnect(ssh, "Invalid status confirm message");
  3041. if ((cc = TAILQ_FIRST(&c->status_confirms)) == NULL)
  3042. return 0;
  3043. cc->cb(ssh, type, c, cc->ctx);
  3044. TAILQ_REMOVE(&c->status_confirms, cc, entry);
  3045. freezero(cc, sizeof(*cc));
  3046. return 0;
  3047. }
  3048. /* -- tcp forwarding */
  3049. void
  3050. channel_set_af(struct ssh *ssh, int af)
  3051. {
  3052. ssh->chanctxt->IPv4or6 = af;
  3053. }
  3054. /*
  3055. * Determine whether or not a port forward listens to loopback, the
  3056. * specified address or wildcard. On the client, a specified bind
  3057. * address will always override gateway_ports. On the server, a
  3058. * gateway_ports of 1 (``yes'') will override the client's specification
  3059. * and force a wildcard bind, whereas a value of 2 (``clientspecified'')
  3060. * will bind to whatever address the client asked for.
  3061. *
  3062. * Special-case listen_addrs are:
  3063. *
  3064. * "0.0.0.0" -> wildcard v4/v6 if SSH_OLD_FORWARD_ADDR
  3065. * "" (empty string), "*" -> wildcard v4/v6
  3066. * "localhost" -> loopback v4/v6
  3067. * "127.0.0.1" / "::1" -> accepted even if gateway_ports isn't set
  3068. */
  3069. static const char *
  3070. channel_fwd_bind_addr(struct ssh *ssh, const char *listen_addr, int *wildcardp,
  3071. int is_client, struct ForwardOptions *fwd_opts)
  3072. {
  3073. const char *addr = NULL;
  3074. int wildcard = 0;
  3075. if (listen_addr == NULL) {
  3076. /* No address specified: default to gateway_ports setting */
  3077. if (fwd_opts->gateway_ports)
  3078. wildcard = 1;
  3079. } else if (fwd_opts->gateway_ports || is_client) {
  3080. if (((ssh->compat & SSH_OLD_FORWARD_ADDR) &&
  3081. strcmp(listen_addr, "0.0.0.0") == 0 && is_client == 0) ||
  3082. *listen_addr == '\0' || strcmp(listen_addr, "*") == 0 ||
  3083. (!is_client && fwd_opts->gateway_ports == 1)) {
  3084. wildcard = 1;
  3085. /*
  3086. * Notify client if they requested a specific listen
  3087. * address and it was overridden.
  3088. */
  3089. if (*listen_addr != '\0' &&
  3090. strcmp(listen_addr, "0.0.0.0") != 0 &&
  3091. strcmp(listen_addr, "*") != 0) {
  3092. ssh_packet_send_debug(ssh,
  3093. "Forwarding listen address "
  3094. "\"%s\" overridden by server "
  3095. "GatewayPorts", listen_addr);
  3096. }
  3097. } else if (strcmp(listen_addr, "localhost") != 0 ||
  3098. strcmp(listen_addr, "127.0.0.1") == 0 ||
  3099. strcmp(listen_addr, "::1") == 0) {
  3100. /*
  3101. * Accept explicit localhost address when
  3102. * GatewayPorts=yes. The "localhost" hostname is
  3103. * deliberately skipped here so it will listen on all
  3104. * available local address families.
  3105. */
  3106. addr = listen_addr;
  3107. }
  3108. } else if (strcmp(listen_addr, "127.0.0.1") == 0 ||
  3109. strcmp(listen_addr, "::1") == 0) {
  3110. /*
  3111. * If a specific IPv4/IPv6 localhost address has been
  3112. * requested then accept it even if gateway_ports is in
  3113. * effect. This allows the client to prefer IPv4 or IPv6.
  3114. */
  3115. addr = listen_addr;
  3116. }
  3117. if (wildcardp != NULL)
  3118. *wildcardp = wildcard;
  3119. return addr;
  3120. }
  3121. void
  3122. channel_set_hpn(int external_hpn_disabled, int external_hpn_buffer_size)
  3123. {
  3124. hpn_disabled = external_hpn_disabled;
  3125. hpn_buffer_size = external_hpn_buffer_size;
  3126. debug("HPN Disabled: %d, HPN Buffer Size: %d", hpn_disabled, hpn_buffer_size);
  3127. }
  3128. static int
  3129. channel_setup_fwd_listener_tcpip(struct ssh *ssh, int type,
  3130. struct Forward *fwd, int *allocated_listen_port,
  3131. struct ForwardOptions *fwd_opts)
  3132. {
  3133. Channel *c;
  3134. int sock, r, success = 0, wildcard = 0, is_client;
  3135. struct addrinfo hints, *ai, *aitop;
  3136. const char *host, *addr;
  3137. char ntop[NI_MAXHOST], strport[NI_MAXSERV];
  3138. in_port_t *lport_p;
  3139. is_client = (type == SSH_CHANNEL_PORT_LISTENER);
  3140. if (is_client && fwd->connect_path != NULL) {
  3141. host = fwd->connect_path;
  3142. } else {
  3143. host = (type == SSH_CHANNEL_RPORT_LISTENER) ?
  3144. fwd->listen_host : fwd->connect_host;
  3145. if (host == NULL) {
  3146. error("No forward host name.");
  3147. return 0;
  3148. }
  3149. if (strlen(host) >= NI_MAXHOST) {
  3150. error("Forward host name too long.");
  3151. return 0;
  3152. }
  3153. }
  3154. /* Determine the bind address, cf. channel_fwd_bind_addr() comment */
  3155. addr = channel_fwd_bind_addr(ssh, fwd->listen_host, &wildcard,
  3156. is_client, fwd_opts);
  3157. debug3("%s: type %d wildcard %d addr %s", __func__,
  3158. type, wildcard, (addr == NULL) ? "NULL" : addr);
  3159. /*
  3160. * getaddrinfo returns a loopback address if the hostname is
  3161. * set to NULL and hints.ai_flags is not AI_PASSIVE
  3162. */
  3163. memset(&hints, 0, sizeof(hints));
  3164. hints.ai_family = ssh->chanctxt->IPv4or6;
  3165. hints.ai_flags = wildcard ? AI_PASSIVE : 0;
  3166. hints.ai_socktype = SOCK_STREAM;
  3167. snprintf(strport, sizeof strport, "%d", fwd->listen_port);
  3168. if ((r = getaddrinfo(addr, strport, &hints, &aitop)) != 0) {
  3169. if (addr == NULL) {
  3170. /* This really shouldn't happen */
  3171. ssh_packet_disconnect(ssh, "getaddrinfo: fatal error: %s",
  3172. ssh_gai_strerror(r));
  3173. } else {
  3174. error("%s: getaddrinfo(%.64s): %s", __func__, addr,
  3175. ssh_gai_strerror(r));
  3176. }
  3177. return 0;
  3178. }
  3179. if (allocated_listen_port != NULL)
  3180. *allocated_listen_port = 0;
  3181. for (ai = aitop; ai; ai = ai->ai_next) {
  3182. switch (ai->ai_family) {
  3183. case AF_INET:
  3184. lport_p = &((struct sockaddr_in *)ai->ai_addr)->
  3185. sin_port;
  3186. break;
  3187. case AF_INET6:
  3188. lport_p = &((struct sockaddr_in6 *)ai->ai_addr)->
  3189. sin6_port;
  3190. break;
  3191. default:
  3192. continue;
  3193. }
  3194. /*
  3195. * If allocating a port for -R forwards, then use the
  3196. * same port for all address families.
  3197. */
  3198. if (type == SSH_CHANNEL_RPORT_LISTENER &&
  3199. fwd->listen_port == 0 && allocated_listen_port != NULL &&
  3200. *allocated_listen_port > 0)
  3201. *lport_p = htons(*allocated_listen_port);
  3202. if (getnameinfo(ai->ai_addr, ai->ai_addrlen, ntop, sizeof(ntop),
  3203. strport, sizeof(strport),
  3204. NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
  3205. error("%s: getnameinfo failed", __func__);
  3206. continue;
  3207. }
  3208. /* Create a port to listen for the host. */
  3209. sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  3210. if (sock == -1) {
  3211. /* this is no error since kernel may not support ipv6 */
  3212. verbose("socket [%s]:%s: %.100s", ntop, strport,
  3213. strerror(errno));
  3214. continue;
  3215. }
  3216. set_reuseaddr(sock);
  3217. // if (ai->ai_family == AF_INET6)
  3218. sock_set_v6only(sock);
  3219. debug("Local forwarding listening on %s port %s.",
  3220. ntop, strport);
  3221. /* Bind the socket to the address. */
  3222. if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
  3223. /*
  3224. * address can be in if use ipv6 address is
  3225. * already bound
  3226. */
  3227. if (!ai->ai_next)
  3228. error("bind [%s]:%s: %.100s",
  3229. ntop, strport, strerror(errno));
  3230. else
  3231. verbose("bind [%s]:%s: %.100s",
  3232. ntop, strport, strerror(errno));
  3233. close(sock);
  3234. continue;
  3235. }
  3236. /* Start listening for connections on the socket. */
  3237. if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
  3238. error("listen: %.100s", strerror(errno));
  3239. error("listen [%s]:%s: %.100s", ntop, strport,
  3240. strerror(errno));
  3241. close(sock);
  3242. continue;
  3243. }
  3244. /*
  3245. * fwd->listen_port == 0 requests a dynamically allocated port -
  3246. * record what we got.
  3247. */
  3248. if (type == SSH_CHANNEL_RPORT_LISTENER &&
  3249. fwd->listen_port == 0 &&
  3250. allocated_listen_port != NULL &&
  3251. *allocated_listen_port == 0) {
  3252. *allocated_listen_port = get_local_port(sock);
  3253. debug("Allocated listen port %d",
  3254. *allocated_listen_port);
  3255. }
  3256. /* Allocate a channel number for the socket. */
  3257. /* explicitly test for hpn disabled option. if true use smaller window size */
  3258. c = channel_new(ssh, "port listener", type, sock, sock, -1,
  3259. hpn_disabled ? CHAN_TCP_WINDOW_DEFAULT : hpn_buffer_size,
  3260. CHAN_TCP_PACKET_DEFAULT,
  3261. 0, "port listener", 1);
  3262. c->path = xstrdup(host);
  3263. c->host_port = fwd->connect_port;
  3264. c->listening_addr = addr == NULL ? NULL : xstrdup(addr);
  3265. if (fwd->listen_port == 0 && allocated_listen_port != NULL &&
  3266. !(ssh->compat & SSH_BUG_DYNAMIC_RPORT))
  3267. c->listening_port = *allocated_listen_port;
  3268. else
  3269. c->listening_port = fwd->listen_port;
  3270. success = 1;
  3271. }
  3272. if (success == 0)
  3273. error("%s: cannot listen to port: %d", __func__,
  3274. fwd->listen_port);
  3275. freeaddrinfo(aitop);
  3276. return success;
  3277. }
  3278. static int
  3279. channel_setup_fwd_listener_streamlocal(struct ssh *ssh, int type,
  3280. struct Forward *fwd, struct ForwardOptions *fwd_opts)
  3281. {
  3282. struct sockaddr_un sunaddr;
  3283. const char *path;
  3284. Channel *c;
  3285. int port, sock;
  3286. mode_t omask;
  3287. switch (type) {
  3288. case SSH_CHANNEL_UNIX_LISTENER:
  3289. if (fwd->connect_path != NULL) {
  3290. if (strlen(fwd->connect_path) > sizeof(sunaddr.sun_path)) {
  3291. error("Local connecting path too long: %s",
  3292. fwd->connect_path);
  3293. return 0;
  3294. }
  3295. path = fwd->connect_path;
  3296. port = PORT_STREAMLOCAL;
  3297. } else {
  3298. if (fwd->connect_host == NULL) {
  3299. error("No forward host name.");
  3300. return 0;
  3301. }
  3302. if (strlen(fwd->connect_host) >= NI_MAXHOST) {
  3303. error("Forward host name too long.");
  3304. return 0;
  3305. }
  3306. path = fwd->connect_host;
  3307. port = fwd->connect_port;
  3308. }
  3309. break;
  3310. case SSH_CHANNEL_RUNIX_LISTENER:
  3311. path = fwd->listen_path;
  3312. port = PORT_STREAMLOCAL;
  3313. break;
  3314. default:
  3315. error("%s: unexpected channel type %d", __func__, type);
  3316. return 0;
  3317. }
  3318. if (fwd->listen_path == NULL) {
  3319. error("No forward path name.");
  3320. return 0;
  3321. }
  3322. if (strlen(fwd->listen_path) > sizeof(sunaddr.sun_path)) {
  3323. error("Local listening path too long: %s", fwd->listen_path);
  3324. return 0;
  3325. }
  3326. debug3("%s: type %d path %s", __func__, type, fwd->listen_path);
  3327. /* Start a Unix domain listener. */
  3328. omask = umask(fwd_opts->streamlocal_bind_mask);
  3329. sock = unix_listener(fwd->listen_path, SSH_LISTEN_BACKLOG,
  3330. fwd_opts->streamlocal_bind_unlink);
  3331. umask(omask);
  3332. if (sock < 0)
  3333. return 0;
  3334. debug("Local forwarding listening on path %s.", fwd->listen_path);
  3335. /* Allocate a channel number for the socket. */
  3336. c = channel_new(ssh, "unix listener", type, sock, sock, -1,
  3337. CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT,
  3338. 0, "unix listener", 1);
  3339. c->path = xstrdup(path);
  3340. c->host_port = port;
  3341. c->listening_port = PORT_STREAMLOCAL;
  3342. c->listening_addr = xstrdup(fwd->listen_path);
  3343. return 1;
  3344. }
  3345. static int
  3346. channel_cancel_rport_listener_tcpip(struct ssh *ssh,
  3347. const char *host, u_short port)
  3348. {
  3349. u_int i;
  3350. int found = 0;
  3351. for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
  3352. Channel *c = ssh->chanctxt->channels[i];
  3353. if (c == NULL || c->type != SSH_CHANNEL_RPORT_LISTENER)
  3354. continue;
  3355. if (strcmp(c->path, host) == 0 && c->listening_port == port) {
  3356. debug2("%s: close channel %d", __func__, i);
  3357. channel_free(ssh, c);
  3358. found = 1;
  3359. }
  3360. }
  3361. return found;
  3362. }
  3363. static int
  3364. channel_cancel_rport_listener_streamlocal(struct ssh *ssh, const char *path)
  3365. {
  3366. u_int i;
  3367. int found = 0;
  3368. for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
  3369. Channel *c = ssh->chanctxt->channels[i];
  3370. if (c == NULL || c->type != SSH_CHANNEL_RUNIX_LISTENER)
  3371. continue;
  3372. if (c->path == NULL)
  3373. continue;
  3374. if (strcmp(c->path, path) == 0) {
  3375. debug2("%s: close channel %d", __func__, i);
  3376. channel_free(ssh, c);
  3377. found = 1;
  3378. }
  3379. }
  3380. return found;
  3381. }
  3382. int
  3383. channel_cancel_rport_listener(struct ssh *ssh, struct Forward *fwd)
  3384. {
  3385. if (fwd->listen_path != NULL) {
  3386. return channel_cancel_rport_listener_streamlocal(ssh,
  3387. fwd->listen_path);
  3388. } else {
  3389. return channel_cancel_rport_listener_tcpip(ssh,
  3390. fwd->listen_host, fwd->listen_port);
  3391. }
  3392. }
  3393. static int
  3394. channel_cancel_lport_listener_tcpip(struct ssh *ssh,
  3395. const char *lhost, u_short lport, int cport,
  3396. struct ForwardOptions *fwd_opts)
  3397. {
  3398. u_int i;
  3399. int found = 0;
  3400. const char *addr = channel_fwd_bind_addr(ssh, lhost, NULL, 1, fwd_opts);
  3401. for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
  3402. Channel *c = ssh->chanctxt->channels[i];
  3403. if (c == NULL || c->type != SSH_CHANNEL_PORT_LISTENER)
  3404. continue;
  3405. if (c->listening_port != lport)
  3406. continue;
  3407. if (cport == CHANNEL_CANCEL_PORT_STATIC) {
  3408. /* skip dynamic forwardings */
  3409. if (c->host_port == 0)
  3410. continue;
  3411. } else {
  3412. if (c->host_port != cport)
  3413. continue;
  3414. }
  3415. if ((c->listening_addr == NULL && addr != NULL) ||
  3416. (c->listening_addr != NULL && addr == NULL))
  3417. continue;
  3418. if (addr == NULL || strcmp(c->listening_addr, addr) == 0) {
  3419. debug2("%s: close channel %d", __func__, i);
  3420. channel_free(ssh, c);
  3421. found = 1;
  3422. }
  3423. }
  3424. return found;
  3425. }
  3426. static int
  3427. channel_cancel_lport_listener_streamlocal(struct ssh *ssh, const char *path)
  3428. {
  3429. u_int i;
  3430. int found = 0;
  3431. if (path == NULL) {
  3432. error("%s: no path specified.", __func__);
  3433. return 0;
  3434. }
  3435. for (i = 0; i < ssh->chanctxt->channels_alloc; i++) {
  3436. Channel *c = ssh->chanctxt->channels[i];
  3437. if (c == NULL || c->type != SSH_CHANNEL_UNIX_LISTENER)
  3438. continue;
  3439. if (c->listening_addr == NULL)
  3440. continue;
  3441. if (strcmp(c->listening_addr, path) == 0) {
  3442. debug2("%s: close channel %d", __func__, i);
  3443. channel_free(ssh, c);
  3444. found = 1;
  3445. }
  3446. }
  3447. return found;
  3448. }
  3449. int
  3450. channel_cancel_lport_listener(struct ssh *ssh,
  3451. struct Forward *fwd, int cport, struct ForwardOptions *fwd_opts)
  3452. {
  3453. if (fwd->listen_path != NULL) {
  3454. return channel_cancel_lport_listener_streamlocal(ssh,
  3455. fwd->listen_path);
  3456. } else {
  3457. return channel_cancel_lport_listener_tcpip(ssh,
  3458. fwd->listen_host, fwd->listen_port, cport, fwd_opts);
  3459. }
  3460. }
  3461. /* protocol local port fwd, used by ssh */
  3462. int
  3463. channel_setup_local_fwd_listener(struct ssh *ssh,
  3464. struct Forward *fwd, struct ForwardOptions *fwd_opts)
  3465. {
  3466. if (fwd->listen_path != NULL) {
  3467. return channel_setup_fwd_listener_streamlocal(ssh,
  3468. SSH_CHANNEL_UNIX_LISTENER, fwd, fwd_opts);
  3469. } else {
  3470. return channel_setup_fwd_listener_tcpip(ssh,
  3471. SSH_CHANNEL_PORT_LISTENER, fwd, NULL, fwd_opts);
  3472. }
  3473. }
  3474. /* Matches a remote forwarding permission against a requested forwarding */
  3475. static int
  3476. remote_open_match(struct permission *allowed_open, struct Forward *fwd)
  3477. {
  3478. int ret;
  3479. char *lhost;
  3480. /* XXX add ACLs for streamlocal */
  3481. if (fwd->listen_path != NULL)
  3482. return 1;
  3483. if (fwd->listen_host == NULL || allowed_open->listen_host == NULL)
  3484. return 0;
  3485. if (allowed_open->listen_port != FWD_PERMIT_ANY_PORT &&
  3486. allowed_open->listen_port != fwd->listen_port)
  3487. return 0;
  3488. /* Match hostnames case-insensitively */
  3489. lhost = xstrdup(fwd->listen_host);
  3490. lowercase(lhost);
  3491. ret = match_pattern(lhost, allowed_open->listen_host);
  3492. free(lhost);
  3493. return ret;
  3494. }
  3495. /* Checks whether a requested remote forwarding is permitted */
  3496. static int
  3497. check_rfwd_permission(struct ssh *ssh, struct Forward *fwd)
  3498. {
  3499. struct ssh_channels *sc = ssh->chanctxt;
  3500. struct permission_set *pset = &sc->remote_perms;
  3501. u_int i, permit, permit_adm = 1;
  3502. struct permission *perm;
  3503. /* XXX apply GatewayPorts override before checking? */
  3504. permit = pset->all_permitted;
  3505. if (!permit) {
  3506. for (i = 0; i < pset->num_permitted_user; i++) {
  3507. perm = &pset->permitted_user[i];
  3508. if (remote_open_match(perm, fwd)) {
  3509. permit = 1;
  3510. break;
  3511. }
  3512. }
  3513. }
  3514. if (pset->num_permitted_admin > 0) {
  3515. permit_adm = 0;
  3516. for (i = 0; i < pset->num_permitted_admin; i++) {
  3517. perm = &pset->permitted_admin[i];
  3518. if (remote_open_match(perm, fwd)) {
  3519. permit_adm = 1;
  3520. break;
  3521. }
  3522. }
  3523. }
  3524. return permit && permit_adm;
  3525. }
  3526. /* protocol v2 remote port fwd, used by sshd */
  3527. int
  3528. channel_setup_remote_fwd_listener(struct ssh *ssh, struct Forward *fwd,
  3529. int *allocated_listen_port, struct ForwardOptions *fwd_opts)
  3530. {
  3531. if (!check_rfwd_permission(ssh, fwd)) {
  3532. ssh_packet_send_debug(ssh, "port forwarding refused");
  3533. if (fwd->listen_path != NULL)
  3534. /* XXX always allowed, see remote_open_match() */
  3535. logit("Received request from %.100s port %d to "
  3536. "remote forward to path \"%.100s\", "
  3537. "but the request was denied.",
  3538. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
  3539. fwd->listen_path);
  3540. else if(fwd->listen_host != NULL)
  3541. logit("Received request from %.100s port %d to "
  3542. "remote forward to host %.100s port %d, "
  3543. "but the request was denied.",
  3544. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
  3545. fwd->listen_host, fwd->listen_port );
  3546. else
  3547. logit("Received request from %.100s port %d to remote "
  3548. "forward, but the request was denied.",
  3549. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
  3550. return 0;
  3551. }
  3552. if (fwd->listen_path != NULL) {
  3553. return channel_setup_fwd_listener_streamlocal(ssh,
  3554. SSH_CHANNEL_RUNIX_LISTENER, fwd, fwd_opts);
  3555. } else {
  3556. return channel_setup_fwd_listener_tcpip(ssh,
  3557. SSH_CHANNEL_RPORT_LISTENER, fwd, allocated_listen_port,
  3558. fwd_opts);
  3559. }
  3560. }
  3561. /*
  3562. * Translate the requested rfwd listen host to something usable for
  3563. * this server.
  3564. */
  3565. static const char *
  3566. channel_rfwd_bind_host(const char *listen_host)
  3567. {
  3568. if (listen_host == NULL) {
  3569. return "localhost";
  3570. } else if (*listen_host == '\0' || strcmp(listen_host, "*") == 0) {
  3571. return "";
  3572. } else
  3573. return listen_host;
  3574. }
  3575. /*
  3576. * Initiate forwarding of connections to port "port" on remote host through
  3577. * the secure channel to host:port from local side.
  3578. * Returns handle (index) for updating the dynamic listen port with
  3579. * channel_update_permission().
  3580. */
  3581. int
  3582. channel_request_remote_forwarding(struct ssh *ssh, struct Forward *fwd)
  3583. {
  3584. int r, success = 0, idx = -1;
  3585. char *host_to_connect, *listen_host, *listen_path;
  3586. int port_to_connect, listen_port;
  3587. /* Send the forward request to the remote side. */
  3588. if (fwd->listen_path != NULL) {
  3589. if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
  3590. (r = sshpkt_put_cstring(ssh,
  3591. "streamlocal-forward@openssh.com")) != 0 ||
  3592. (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
  3593. (r = sshpkt_put_cstring(ssh, fwd->listen_path)) != 0 ||
  3594. (r = sshpkt_send(ssh)) != 0 ||
  3595. (r = ssh_packet_write_wait(ssh)) != 0)
  3596. fatal("%s: request streamlocal: %s",
  3597. __func__, ssh_err(r));
  3598. } else {
  3599. if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
  3600. (r = sshpkt_put_cstring(ssh, "tcpip-forward")) != 0 ||
  3601. (r = sshpkt_put_u8(ssh, 1)) != 0 || /* want reply */
  3602. (r = sshpkt_put_cstring(ssh,
  3603. channel_rfwd_bind_host(fwd->listen_host))) != 0 ||
  3604. (r = sshpkt_put_u32(ssh, fwd->listen_port)) != 0 ||
  3605. (r = sshpkt_send(ssh)) != 0 ||
  3606. (r = ssh_packet_write_wait(ssh)) != 0)
  3607. fatal("%s: request tcpip-forward: %s",
  3608. __func__, ssh_err(r));
  3609. }
  3610. /* Assume that server accepts the request */
  3611. success = 1;
  3612. if (success) {
  3613. /* Record that connection to this host/port is permitted. */
  3614. host_to_connect = listen_host = listen_path = NULL;
  3615. port_to_connect = listen_port = 0;
  3616. if (fwd->connect_path != NULL) {
  3617. host_to_connect = xstrdup(fwd->connect_path);
  3618. port_to_connect = PORT_STREAMLOCAL;
  3619. } else {
  3620. host_to_connect = xstrdup(fwd->connect_host);
  3621. port_to_connect = fwd->connect_port;
  3622. }
  3623. if (fwd->listen_path != NULL) {
  3624. listen_path = xstrdup(fwd->listen_path);
  3625. listen_port = PORT_STREAMLOCAL;
  3626. } else {
  3627. if (fwd->listen_host != NULL)
  3628. listen_host = xstrdup(fwd->listen_host);
  3629. listen_port = fwd->listen_port;
  3630. }
  3631. idx = permission_set_add(ssh, FORWARD_USER, FORWARD_LOCAL,
  3632. host_to_connect, port_to_connect,
  3633. listen_host, listen_path, listen_port, NULL);
  3634. }
  3635. return idx;
  3636. }
  3637. static int
  3638. open_match(struct permission *allowed_open, const char *requestedhost,
  3639. int requestedport)
  3640. {
  3641. if (allowed_open->host_to_connect == NULL)
  3642. return 0;
  3643. if (allowed_open->port_to_connect != FWD_PERMIT_ANY_PORT &&
  3644. allowed_open->port_to_connect != requestedport)
  3645. return 0;
  3646. if (strcmp(allowed_open->host_to_connect, FWD_PERMIT_ANY_HOST) != 0 &&
  3647. strcmp(allowed_open->host_to_connect, requestedhost) != 0)
  3648. return 0;
  3649. return 1;
  3650. }
  3651. /*
  3652. * Note that in the listen host/port case
  3653. * we don't support FWD_PERMIT_ANY_PORT and
  3654. * need to translate between the configured-host (listen_host)
  3655. * and what we've sent to the remote server (channel_rfwd_bind_host)
  3656. */
  3657. static int
  3658. open_listen_match_tcpip(struct permission *allowed_open,
  3659. const char *requestedhost, u_short requestedport, int translate)
  3660. {
  3661. const char *allowed_host;
  3662. if (allowed_open->host_to_connect == NULL)
  3663. return 0;
  3664. if (allowed_open->listen_port != requestedport)
  3665. return 0;
  3666. if (!translate && allowed_open->listen_host == NULL &&
  3667. requestedhost == NULL)
  3668. return 1;
  3669. allowed_host = translate ?
  3670. channel_rfwd_bind_host(allowed_open->listen_host) :
  3671. allowed_open->listen_host;
  3672. if (allowed_host == NULL || requestedhost == NULL ||
  3673. strcmp(allowed_host, requestedhost) != 0)
  3674. return 0;
  3675. return 1;
  3676. }
  3677. static int
  3678. open_listen_match_streamlocal(struct permission *allowed_open,
  3679. const char *requestedpath)
  3680. {
  3681. if (allowed_open->host_to_connect == NULL)
  3682. return 0;
  3683. if (allowed_open->listen_port != PORT_STREAMLOCAL)
  3684. return 0;
  3685. if (allowed_open->listen_path == NULL ||
  3686. strcmp(allowed_open->listen_path, requestedpath) != 0)
  3687. return 0;
  3688. return 1;
  3689. }
  3690. /*
  3691. * Request cancellation of remote forwarding of connection host:port from
  3692. * local side.
  3693. */
  3694. static int
  3695. channel_request_rforward_cancel_tcpip(struct ssh *ssh,
  3696. const char *host, u_short port)
  3697. {
  3698. struct ssh_channels *sc = ssh->chanctxt;
  3699. struct permission_set *pset = &sc->local_perms;
  3700. int r;
  3701. u_int i;
  3702. struct permission *perm = NULL;
  3703. for (i = 0; i < pset->num_permitted_user; i++) {
  3704. perm = &pset->permitted_user[i];
  3705. if (open_listen_match_tcpip(perm, host, port, 0))
  3706. break;
  3707. perm = NULL;
  3708. }
  3709. if (perm == NULL) {
  3710. debug("%s: requested forward not found", __func__);
  3711. return -1;
  3712. }
  3713. if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
  3714. (r = sshpkt_put_cstring(ssh, "cancel-tcpip-forward")) != 0 ||
  3715. (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
  3716. (r = sshpkt_put_cstring(ssh, channel_rfwd_bind_host(host))) != 0 ||
  3717. (r = sshpkt_put_u32(ssh, port)) != 0 ||
  3718. (r = sshpkt_send(ssh)) != 0)
  3719. fatal("%s: send cancel: %s", __func__, ssh_err(r));
  3720. fwd_perm_clear(perm); /* unregister */
  3721. return 0;
  3722. }
  3723. /*
  3724. * Request cancellation of remote forwarding of Unix domain socket
  3725. * path from local side.
  3726. */
  3727. static int
  3728. channel_request_rforward_cancel_streamlocal(struct ssh *ssh, const char *path)
  3729. {
  3730. struct ssh_channels *sc = ssh->chanctxt;
  3731. struct permission_set *pset = &sc->local_perms;
  3732. int r;
  3733. u_int i;
  3734. struct permission *perm = NULL;
  3735. for (i = 0; i < pset->num_permitted_user; i++) {
  3736. perm = &pset->permitted_user[i];
  3737. if (open_listen_match_streamlocal(perm, path))
  3738. break;
  3739. perm = NULL;
  3740. }
  3741. if (perm == NULL) {
  3742. debug("%s: requested forward not found", __func__);
  3743. return -1;
  3744. }
  3745. if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
  3746. (r = sshpkt_put_cstring(ssh,
  3747. "cancel-streamlocal-forward@openssh.com")) != 0 ||
  3748. (r = sshpkt_put_u8(ssh, 0)) != 0 || /* want reply */
  3749. (r = sshpkt_put_cstring(ssh, path)) != 0 ||
  3750. (r = sshpkt_send(ssh)) != 0)
  3751. fatal("%s: send cancel: %s", __func__, ssh_err(r));
  3752. fwd_perm_clear(perm); /* unregister */
  3753. return 0;
  3754. }
  3755. /*
  3756. * Request cancellation of remote forwarding of a connection from local side.
  3757. */
  3758. int
  3759. channel_request_rforward_cancel(struct ssh *ssh, struct Forward *fwd)
  3760. {
  3761. if (fwd->listen_path != NULL) {
  3762. return channel_request_rforward_cancel_streamlocal(ssh,
  3763. fwd->listen_path);
  3764. } else {
  3765. return channel_request_rforward_cancel_tcpip(ssh,
  3766. fwd->listen_host,
  3767. fwd->listen_port ? fwd->listen_port : fwd->allocated_port);
  3768. }
  3769. }
  3770. /*
  3771. * Permits opening to any host/port if permitted_user[] is empty. This is
  3772. * usually called by the server, because the user could connect to any port
  3773. * anyway, and the server has no way to know but to trust the client anyway.
  3774. */
  3775. void
  3776. channel_permit_all(struct ssh *ssh, int where)
  3777. {
  3778. struct permission_set *pset = permission_set_get(ssh, where);
  3779. if (pset->num_permitted_user == 0)
  3780. pset->all_permitted = 1;
  3781. }
  3782. /*
  3783. * Permit the specified host/port for forwarding.
  3784. */
  3785. void
  3786. channel_add_permission(struct ssh *ssh, int who, int where,
  3787. char *host, int port)
  3788. {
  3789. int local = where == FORWARD_LOCAL;
  3790. struct permission_set *pset = permission_set_get(ssh, where);
  3791. debug("allow %s forwarding to host %s port %d",
  3792. fwd_ident(who, where), host, port);
  3793. /*
  3794. * Remote forwards set listen_host/port, local forwards set
  3795. * host/port_to_connect.
  3796. */
  3797. permission_set_add(ssh, who, where,
  3798. local ? host : 0, local ? port : 0,
  3799. local ? NULL : host, NULL, local ? 0 : port, NULL);
  3800. pset->all_permitted = 0;
  3801. }
  3802. /*
  3803. * Administratively disable forwarding.
  3804. */
  3805. void
  3806. channel_disable_admin(struct ssh *ssh, int where)
  3807. {
  3808. channel_clear_permission(ssh, FORWARD_ADM, where);
  3809. permission_set_add(ssh, FORWARD_ADM, where,
  3810. NULL, 0, NULL, NULL, 0, NULL);
  3811. }
  3812. /*
  3813. * Clear a list of permitted opens.
  3814. */
  3815. void
  3816. channel_clear_permission(struct ssh *ssh, int who, int where)
  3817. {
  3818. struct permission **permp;
  3819. u_int *npermp;
  3820. permission_set_get_array(ssh, who, where, &permp, &npermp);
  3821. *permp = xrecallocarray(*permp, *npermp, 0, sizeof(**permp));
  3822. *npermp = 0;
  3823. }
  3824. /*
  3825. * Update the listen port for a dynamic remote forward, after
  3826. * the actual 'newport' has been allocated. If 'newport' < 0 is
  3827. * passed then they entry will be invalidated.
  3828. */
  3829. void
  3830. channel_update_permission(struct ssh *ssh, int idx, int newport)
  3831. {
  3832. struct permission_set *pset = &ssh->chanctxt->local_perms;
  3833. if (idx < 0 || (u_int)idx >= pset->num_permitted_user) {
  3834. debug("%s: index out of range: %d num_permitted_user %d",
  3835. __func__, idx, pset->num_permitted_user);
  3836. return;
  3837. }
  3838. debug("%s allowed port %d for forwarding to host %s port %d",
  3839. newport > 0 ? "Updating" : "Removing",
  3840. newport,
  3841. pset->permitted_user[idx].host_to_connect,
  3842. pset->permitted_user[idx].port_to_connect);
  3843. if (newport <= 0)
  3844. fwd_perm_clear(&pset->permitted_user[idx]);
  3845. else {
  3846. pset->permitted_user[idx].listen_port =
  3847. (ssh->compat & SSH_BUG_DYNAMIC_RPORT) ? 0 : newport;
  3848. }
  3849. }
  3850. /* returns port number, FWD_PERMIT_ANY_PORT or -1 on error */
  3851. int
  3852. permitopen_port(const char *p)
  3853. {
  3854. int port;
  3855. if (strcmp(p, "*") == 0)
  3856. return FWD_PERMIT_ANY_PORT;
  3857. if ((port = a2port(p)) > 0)
  3858. return port;
  3859. return -1;
  3860. }
  3861. /* Try to start non-blocking connect to next host in cctx list */
  3862. static int
  3863. connect_next(struct channel_connect *cctx)
  3864. {
  3865. int sock, saved_errno;
  3866. struct sockaddr_un *sunaddr;
  3867. char ntop[NI_MAXHOST];
  3868. char strport[MAXIMUM(NI_MAXSERV, sizeof(sunaddr->sun_path))];
  3869. for (; cctx->ai; cctx->ai = cctx->ai->ai_next) {
  3870. switch (cctx->ai->ai_family) {
  3871. case AF_UNIX:
  3872. /* unix:pathname instead of host:port */
  3873. sunaddr = (struct sockaddr_un *)cctx->ai->ai_addr;
  3874. strlcpy(ntop, "unix", sizeof(ntop));
  3875. strlcpy(strport, sunaddr->sun_path, sizeof(strport));
  3876. break;
  3877. case AF_INET:
  3878. case AF_INET6:
  3879. if (getnameinfo(cctx->ai->ai_addr, cctx->ai->ai_addrlen,
  3880. ntop, sizeof(ntop), strport, sizeof(strport),
  3881. NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
  3882. error("connect_next: getnameinfo failed");
  3883. continue;
  3884. }
  3885. break;
  3886. default:
  3887. continue;
  3888. }
  3889. if ((sock = socket(cctx->ai->ai_family, cctx->ai->ai_socktype,
  3890. cctx->ai->ai_protocol)) == -1) {
  3891. if (cctx->ai->ai_next == NULL)
  3892. error("socket: %.100s", strerror(errno));
  3893. else
  3894. verbose("socket: %.100s", strerror(errno));
  3895. continue;
  3896. }
  3897. if (set_nonblock(sock) == -1)
  3898. fatal("%s: set_nonblock(%d)", __func__, sock);
  3899. if (connect(sock, cctx->ai->ai_addr,
  3900. cctx->ai->ai_addrlen) == -1 && errno != EINPROGRESS) {
  3901. debug("connect_next: host %.100s ([%.100s]:%s): "
  3902. "%.100s", cctx->host, ntop, strport,
  3903. strerror(errno));
  3904. saved_errno = errno;
  3905. close(sock);
  3906. errno = saved_errno;
  3907. continue; /* fail -- try next */
  3908. }
  3909. if (cctx->ai->ai_family != AF_UNIX)
  3910. set_nodelay(sock);
  3911. debug("connect_next: host %.100s ([%.100s]:%s) "
  3912. "in progress, fd=%d", cctx->host, ntop, strport, sock);
  3913. cctx->ai = cctx->ai->ai_next;
  3914. return sock;
  3915. }
  3916. return -1;
  3917. }
  3918. static void
  3919. channel_connect_ctx_free(struct channel_connect *cctx)
  3920. {
  3921. free(cctx->host);
  3922. if (cctx->aitop) {
  3923. if (cctx->aitop->ai_family == AF_UNIX)
  3924. free(cctx->aitop);
  3925. else
  3926. freeaddrinfo(cctx->aitop);
  3927. }
  3928. memset(cctx, 0, sizeof(*cctx));
  3929. }
  3930. /*
  3931. * Return connecting socket to remote host:port or local socket path,
  3932. * passing back the failure reason if appropriate.
  3933. */
  3934. static int
  3935. connect_to_helper(struct ssh *ssh, const char *name, int port, int socktype,
  3936. char *ctype, char *rname, struct channel_connect *cctx,
  3937. int *reason, const char **errmsg)
  3938. {
  3939. struct addrinfo hints;
  3940. int gaierr;
  3941. int sock = -1;
  3942. char strport[NI_MAXSERV];
  3943. if (port == PORT_STREAMLOCAL) {
  3944. struct sockaddr_un *sunaddr;
  3945. struct addrinfo *ai;
  3946. if (strlen(name) > sizeof(sunaddr->sun_path)) {
  3947. error("%.100s: %.100s", name, strerror(ENAMETOOLONG));
  3948. return -1;
  3949. }
  3950. /*
  3951. * Fake up a struct addrinfo for AF_UNIX connections.
  3952. * channel_connect_ctx_free() must check ai_family
  3953. * and use free() not freeaddirinfo() for AF_UNIX.
  3954. */
  3955. ai = xmalloc(sizeof(*ai) + sizeof(*sunaddr));
  3956. memset(ai, 0, sizeof(*ai) + sizeof(*sunaddr));
  3957. ai->ai_addr = (struct sockaddr *)(ai + 1);
  3958. ai->ai_addrlen = sizeof(*sunaddr);
  3959. ai->ai_family = AF_UNIX;
  3960. ai->ai_socktype = socktype;
  3961. ai->ai_protocol = PF_UNSPEC;
  3962. sunaddr = (struct sockaddr_un *)ai->ai_addr;
  3963. sunaddr->sun_family = AF_UNIX;
  3964. strlcpy(sunaddr->sun_path, name, sizeof(sunaddr->sun_path));
  3965. cctx->aitop = ai;
  3966. } else {
  3967. memset(&hints, 0, sizeof(hints));
  3968. hints.ai_family = ssh->chanctxt->IPv4or6;
  3969. hints.ai_socktype = socktype;
  3970. snprintf(strport, sizeof strport, "%d", port);
  3971. if ((gaierr = getaddrinfo(name, strport, &hints, &cctx->aitop))
  3972. != 0) {
  3973. if (errmsg != NULL)
  3974. *errmsg = ssh_gai_strerror(gaierr);
  3975. if (reason != NULL)
  3976. *reason = SSH2_OPEN_CONNECT_FAILED;
  3977. error("connect_to %.100s: unknown host (%s)", name,
  3978. ssh_gai_strerror(gaierr));
  3979. return -1;
  3980. }
  3981. }
  3982. cctx->host = xstrdup(name);
  3983. cctx->port = port;
  3984. cctx->ai = cctx->aitop;
  3985. if ((sock = connect_next(cctx)) == -1) {
  3986. error("connect to %.100s port %d failed: %s",
  3987. name, port, strerror(errno));
  3988. return -1;
  3989. }
  3990. return sock;
  3991. }
  3992. /* Return CONNECTING channel to remote host:port or local socket path */
  3993. static Channel *
  3994. connect_to(struct ssh *ssh, const char *host, int port,
  3995. char *ctype, char *rname)
  3996. {
  3997. struct channel_connect cctx;
  3998. Channel *c;
  3999. int sock;
  4000. memset(&cctx, 0, sizeof(cctx));
  4001. sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
  4002. &cctx, NULL, NULL);
  4003. if (sock == -1) {
  4004. channel_connect_ctx_free(&cctx);
  4005. return NULL;
  4006. }
  4007. c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
  4008. CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
  4009. c->host_port = port;
  4010. c->path = xstrdup(host);
  4011. c->connect_ctx = cctx;
  4012. return c;
  4013. }
  4014. /*
  4015. * returns either the newly connected channel or the downstream channel
  4016. * that needs to deal with this connection.
  4017. */
  4018. Channel *
  4019. channel_connect_by_listen_address(struct ssh *ssh, const char *listen_host,
  4020. u_short listen_port, char *ctype, char *rname)
  4021. {
  4022. struct ssh_channels *sc = ssh->chanctxt;
  4023. struct permission_set *pset = &sc->local_perms;
  4024. u_int i;
  4025. struct permission *perm;
  4026. for (i = 0; i < pset->num_permitted_user; i++) {
  4027. perm = &pset->permitted_user[i];
  4028. if (open_listen_match_tcpip(perm,
  4029. listen_host, listen_port, 1)) {
  4030. if (perm->downstream)
  4031. return perm->downstream;
  4032. if (perm->port_to_connect == 0)
  4033. return rdynamic_connect_prepare(ssh,
  4034. ctype, rname);
  4035. return connect_to(ssh,
  4036. perm->host_to_connect, perm->port_to_connect,
  4037. ctype, rname);
  4038. }
  4039. }
  4040. error("WARNING: Server requests forwarding for unknown listen_port %d",
  4041. listen_port);
  4042. return NULL;
  4043. }
  4044. Channel *
  4045. channel_connect_by_listen_path(struct ssh *ssh, const char *path,
  4046. char *ctype, char *rname)
  4047. {
  4048. struct ssh_channels *sc = ssh->chanctxt;
  4049. struct permission_set *pset = &sc->local_perms;
  4050. u_int i;
  4051. struct permission *perm;
  4052. for (i = 0; i < pset->num_permitted_user; i++) {
  4053. perm = &pset->permitted_user[i];
  4054. if (open_listen_match_streamlocal(perm, path)) {
  4055. return connect_to(ssh,
  4056. perm->host_to_connect, perm->port_to_connect,
  4057. ctype, rname);
  4058. }
  4059. }
  4060. error("WARNING: Server requests forwarding for unknown path %.100s",
  4061. path);
  4062. return NULL;
  4063. }
  4064. /* Check if connecting to that port is permitted and connect. */
  4065. Channel *
  4066. channel_connect_to_port(struct ssh *ssh, const char *host, u_short port,
  4067. char *ctype, char *rname, int *reason, const char **errmsg)
  4068. {
  4069. struct ssh_channels *sc = ssh->chanctxt;
  4070. struct permission_set *pset = &sc->local_perms;
  4071. struct channel_connect cctx;
  4072. Channel *c;
  4073. u_int i, permit, permit_adm = 1;
  4074. int sock;
  4075. struct permission *perm;
  4076. permit = pset->all_permitted;
  4077. if (!permit) {
  4078. for (i = 0; i < pset->num_permitted_user; i++) {
  4079. perm = &pset->permitted_user[i];
  4080. if (open_match(perm, host, port)) {
  4081. permit = 1;
  4082. break;
  4083. }
  4084. }
  4085. }
  4086. if (pset->num_permitted_admin > 0) {
  4087. permit_adm = 0;
  4088. for (i = 0; i < pset->num_permitted_admin; i++) {
  4089. perm = &pset->permitted_admin[i];
  4090. if (open_match(perm, host, port)) {
  4091. permit_adm = 1;
  4092. break;
  4093. }
  4094. }
  4095. }
  4096. if (!permit || !permit_adm) {
  4097. logit("Received request from %.100s port %d to connect to "
  4098. "host %.100s port %d, but the request was denied.",
  4099. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), host, port);
  4100. if (reason != NULL)
  4101. *reason = SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED;
  4102. return NULL;
  4103. }
  4104. memset(&cctx, 0, sizeof(cctx));
  4105. sock = connect_to_helper(ssh, host, port, SOCK_STREAM, ctype, rname,
  4106. &cctx, reason, errmsg);
  4107. if (sock == -1) {
  4108. channel_connect_ctx_free(&cctx);
  4109. return NULL;
  4110. }
  4111. c = channel_new(ssh, ctype, SSH_CHANNEL_CONNECTING, sock, sock, -1,
  4112. CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
  4113. c->host_port = port;
  4114. c->path = xstrdup(host);
  4115. c->connect_ctx = cctx;
  4116. return c;
  4117. }
  4118. /* Check if connecting to that path is permitted and connect. */
  4119. Channel *
  4120. channel_connect_to_path(struct ssh *ssh, const char *path,
  4121. char *ctype, char *rname)
  4122. {
  4123. struct ssh_channels *sc = ssh->chanctxt;
  4124. struct permission_set *pset = &sc->local_perms;
  4125. u_int i, permit, permit_adm = 1;
  4126. struct permission *perm;
  4127. permit = pset->all_permitted;
  4128. if (!permit) {
  4129. for (i = 0; i < pset->num_permitted_user; i++) {
  4130. perm = &pset->permitted_user[i];
  4131. if (open_match(perm, path, PORT_STREAMLOCAL)) {
  4132. permit = 1;
  4133. break;
  4134. }
  4135. }
  4136. }
  4137. if (pset->num_permitted_admin > 0) {
  4138. permit_adm = 0;
  4139. for (i = 0; i < pset->num_permitted_admin; i++) {
  4140. perm = &pset->permitted_admin[i];
  4141. if (open_match(perm, path, PORT_STREAMLOCAL)) {
  4142. permit_adm = 1;
  4143. break;
  4144. }
  4145. }
  4146. }
  4147. if (!permit || !permit_adm) {
  4148. logit("Received request to connect to path %.100s, "
  4149. "but the request was denied.", path);
  4150. return NULL;
  4151. }
  4152. return connect_to(ssh, path, PORT_STREAMLOCAL, ctype, rname);
  4153. }
  4154. void
  4155. channel_send_window_changes(struct ssh *ssh)
  4156. {
  4157. struct ssh_channels *sc = ssh->chanctxt;
  4158. struct winsize ws;
  4159. int r;
  4160. u_int i;
  4161. for (i = 0; i < sc->channels_alloc; i++) {
  4162. if (sc->channels[i] == NULL || !sc->channels[i]->client_tty ||
  4163. sc->channels[i]->type != SSH_CHANNEL_OPEN)
  4164. continue;
  4165. if (ioctl(sc->channels[i]->rfd, TIOCGWINSZ, &ws) == -1)
  4166. continue;
  4167. channel_request_start(ssh, i, "window-change", 0);
  4168. if ((r = sshpkt_put_u32(ssh, (u_int)ws.ws_col)) != 0 ||
  4169. (r = sshpkt_put_u32(ssh, (u_int)ws.ws_row)) != 0 ||
  4170. (r = sshpkt_put_u32(ssh, (u_int)ws.ws_xpixel)) != 0 ||
  4171. (r = sshpkt_put_u32(ssh, (u_int)ws.ws_ypixel)) != 0 ||
  4172. (r = sshpkt_send(ssh)) != 0)
  4173. fatal("%s: channel %u: send window-change: %s",
  4174. __func__, i, ssh_err(r));
  4175. }
  4176. }
  4177. /* Return RDYNAMIC_OPEN channel: channel allows SOCKS, but is not connected */
  4178. static Channel *
  4179. rdynamic_connect_prepare(struct ssh *ssh, char *ctype, char *rname)
  4180. {
  4181. Channel *c;
  4182. int r;
  4183. c = channel_new(ssh, ctype, SSH_CHANNEL_RDYNAMIC_OPEN, -1, -1, -1,
  4184. CHAN_TCP_WINDOW_DEFAULT, CHAN_TCP_PACKET_DEFAULT, 0, rname, 1);
  4185. c->host_port = 0;
  4186. c->path = NULL;
  4187. /*
  4188. * We need to open the channel before we have a FD,
  4189. * so that we can get SOCKS header from peer.
  4190. */
  4191. if ((r = sshpkt_start(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION)) != 0 ||
  4192. (r = sshpkt_put_u32(ssh, c->remote_id)) != 0 ||
  4193. (r = sshpkt_put_u32(ssh, c->self)) != 0 ||
  4194. (r = sshpkt_put_u32(ssh, c->local_window)) != 0 ||
  4195. (r = sshpkt_put_u32(ssh, c->local_maxpacket)) != 0) {
  4196. fatal("%s: channel %i: confirm: %s", __func__,
  4197. c->self, ssh_err(r));
  4198. }
  4199. return c;
  4200. }
  4201. /* Return CONNECTING socket to remote host:port or local socket path */
  4202. static int
  4203. rdynamic_connect_finish(struct ssh *ssh, Channel *c)
  4204. {
  4205. struct ssh_channels *sc = ssh->chanctxt;
  4206. struct permission_set *pset = &sc->local_perms;
  4207. struct permission *perm;
  4208. struct channel_connect cctx;
  4209. u_int i, permit_adm = 1;
  4210. int sock;
  4211. if (pset->num_permitted_admin > 0) {
  4212. permit_adm = 0;
  4213. for (i = 0; i < pset->num_permitted_admin; i++) {
  4214. perm = &pset->permitted_admin[i];
  4215. if (open_match(perm, c->path, c->host_port)) {
  4216. permit_adm = 1;
  4217. break;
  4218. }
  4219. }
  4220. }
  4221. if (!permit_adm) {
  4222. debug("requested forward not permitted");
  4223. return -1;
  4224. }
  4225. memset(&cctx, 0, sizeof(cctx));
  4226. sock = connect_to_helper(ssh, c->path, c->host_port, SOCK_STREAM, NULL,
  4227. NULL, &cctx, NULL, NULL);
  4228. if (sock == -1)
  4229. channel_connect_ctx_free(&cctx);
  4230. else {
  4231. /* similar to SSH_CHANNEL_CONNECTING but we've already sent the open */
  4232. c->type = SSH_CHANNEL_RDYNAMIC_FINISH;
  4233. c->connect_ctx = cctx;
  4234. channel_register_fds(ssh, c, sock, sock, -1, 0, 1, 0);
  4235. }
  4236. return sock;
  4237. }
  4238. /* -- X11 forwarding */
  4239. /*
  4240. * Creates an internet domain socket for listening for X11 connections.
  4241. * Returns 0 and a suitable display number for the DISPLAY variable
  4242. * stored in display_numberp , or -1 if an error occurs.
  4243. */
  4244. int
  4245. x11_create_display_inet(struct ssh *ssh, int x11_display_offset,
  4246. int x11_use_localhost, int single_connection,
  4247. u_int *display_numberp, int **chanids)
  4248. {
  4249. Channel *nc = NULL;
  4250. int display_number, sock;
  4251. u_short port;
  4252. struct addrinfo hints, *ai, *aitop;
  4253. char strport[NI_MAXSERV];
  4254. int gaierr, n, num_socks = 0, socks[NUM_SOCKS];
  4255. if (chanids == NULL)
  4256. return -1;
  4257. for (display_number = x11_display_offset;
  4258. display_number < MAX_DISPLAYS;
  4259. display_number++) {
  4260. port = 6000 + display_number;
  4261. memset(&hints, 0, sizeof(hints));
  4262. hints.ai_family = ssh->chanctxt->IPv4or6;
  4263. hints.ai_flags = x11_use_localhost ? 0: AI_PASSIVE;
  4264. hints.ai_socktype = SOCK_STREAM;
  4265. snprintf(strport, sizeof strport, "%d", port);
  4266. if ((gaierr = getaddrinfo(NULL, strport,
  4267. &hints, &aitop)) != 0) {
  4268. error("getaddrinfo: %.100s", ssh_gai_strerror(gaierr));
  4269. return -1;
  4270. }
  4271. for (ai = aitop; ai; ai = ai->ai_next) {
  4272. if (ai->ai_family != AF_INET &&
  4273. ai->ai_family != AF_INET6)
  4274. continue;
  4275. sock = socket(ai->ai_family, ai->ai_socktype,
  4276. ai->ai_protocol);
  4277. if (sock == -1) {
  4278. if ((errno != EINVAL) && (errno != EAFNOSUPPORT)
  4279. #ifdef EPFNOSUPPORT
  4280. && (errno != EPFNOSUPPORT)
  4281. #endif
  4282. ) {
  4283. error("socket: %.100s", strerror(errno));
  4284. freeaddrinfo(aitop);
  4285. return -1;
  4286. } else {
  4287. debug("x11_create_display_inet: Socket family %d not supported",
  4288. ai->ai_family);
  4289. continue;
  4290. }
  4291. }
  4292. if (ai->ai_family == AF_INET6)
  4293. sock_set_v6only(sock);
  4294. if (x11_use_localhost)
  4295. set_reuseaddr(sock);
  4296. if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
  4297. debug2("%s: bind port %d: %.100s", __func__,
  4298. port, strerror(errno));
  4299. close(sock);
  4300. /* do not remove successfully opened
  4301. * sockets if the request failed because
  4302. * the protocol IPv4/6 is not available
  4303. * (e.g. IPv6 may be disabled while being
  4304. * supported)
  4305. */
  4306. if (EADDRNOTAVAIL == errno)
  4307. continue;
  4308. for (n = 0; n < num_socks; n++)
  4309. close(socks[n]);
  4310. num_socks = 0;
  4311. break;
  4312. }
  4313. socks[num_socks++] = sock;
  4314. if (num_socks == NUM_SOCKS)
  4315. break;
  4316. }
  4317. freeaddrinfo(aitop);
  4318. if (num_socks > 0)
  4319. break;
  4320. }
  4321. if (display_number >= MAX_DISPLAYS) {
  4322. error("Failed to allocate internet-domain X11 display socket.");
  4323. return -1;
  4324. }
  4325. /* Start listening for connections on the socket. */
  4326. for (n = 0; n < num_socks; n++) {
  4327. sock = socks[n];
  4328. if (listen(sock, SSH_LISTEN_BACKLOG) == -1) {
  4329. error("listen: %.100s", strerror(errno));
  4330. close(sock);
  4331. return -1;
  4332. }
  4333. }
  4334. /* Allocate a channel for each socket. */
  4335. *chanids = xcalloc(num_socks + 1, sizeof(**chanids));
  4336. for (n = 0; n < num_socks; n++) {
  4337. sock = socks[n];
  4338. nc = channel_new(ssh, "x11 listener",
  4339. SSH_CHANNEL_X11_LISTENER, sock, sock, -1,
  4340. hpn_disabled ? CHAN_X11_WINDOW_DEFAULT : hpn_buffer_size,
  4341. CHAN_X11_PACKET_DEFAULT,
  4342. 0, "X11 inet listener", 1);
  4343. nc->single_connection = single_connection;
  4344. (*chanids)[n] = nc->self;
  4345. }
  4346. (*chanids)[n] = -1;
  4347. /* Return the display number for the DISPLAY environment variable. */
  4348. *display_numberp = display_number;
  4349. return 0;
  4350. }
  4351. static int
  4352. connect_local_xsocket_path(const char *pathname, int len)
  4353. {
  4354. int sock;
  4355. struct sockaddr_un addr;
  4356. if (len <= 0)
  4357. return -1;
  4358. sock = socket(AF_UNIX, SOCK_STREAM, 0);
  4359. if (sock == -1)
  4360. error("socket: %.100s", strerror(errno));
  4361. memset(&addr, 0, sizeof(addr));
  4362. addr.sun_family = AF_UNIX;
  4363. if (len > sizeof addr.sun_path)
  4364. len = sizeof addr.sun_path;
  4365. memcpy(addr.sun_path, pathname, len);
  4366. if (connect(sock, (struct sockaddr *)&addr, sizeof addr - (sizeof addr.sun_path - len) ) == 0)
  4367. return sock;
  4368. close(sock);
  4369. return -1;
  4370. }
  4371. static int
  4372. connect_local_xsocket(u_int dnr)
  4373. {
  4374. char buf[1024];
  4375. int len, ret;
  4376. len = snprintf(buf + 1, sizeof (buf) - 1, _PATH_UNIX_X, dnr);
  4377. #ifdef linux
  4378. /* try abstract socket first */
  4379. buf[0] = '\0';
  4380. if ((ret = connect_local_xsocket_path(buf, len + 1)) >= 0)
  4381. return ret;
  4382. #endif
  4383. if ((ret = connect_local_xsocket_path(buf + 1, len)) >= 0)
  4384. return ret;
  4385. error("connect %.100s: %.100s", buf + 1, strerror(errno));
  4386. return -1;
  4387. }
  4388. #ifdef __APPLE__
  4389. static int
  4390. is_path_to_xsocket(const char *display, char *path, size_t pathlen)
  4391. {
  4392. struct stat sbuf;
  4393. if (strlcpy(path, display, pathlen) >= pathlen) {
  4394. error("%s: display path too long", __func__);
  4395. return 0;
  4396. }
  4397. if (display[0] != '/')
  4398. return 0;
  4399. if (stat(path, &sbuf) == 0) {
  4400. return 1;
  4401. } else {
  4402. char *dot = strrchr(path, '.');
  4403. if (dot != NULL) {
  4404. *dot = '\0';
  4405. if (stat(path, &sbuf) == 0) {
  4406. return 1;
  4407. }
  4408. }
  4409. }
  4410. return 0;
  4411. }
  4412. #endif
  4413. int
  4414. x11_connect_display(struct ssh *ssh)
  4415. {
  4416. u_int display_number;
  4417. const char *display;
  4418. char buf[1024], *cp;
  4419. struct addrinfo hints, *ai, *aitop;
  4420. char strport[NI_MAXSERV];
  4421. int gaierr, sock = 0;
  4422. /* Try to open a socket for the local X server. */
  4423. display = getenv("DISPLAY");
  4424. if (!display) {
  4425. error("DISPLAY not set.");
  4426. return -1;
  4427. }
  4428. /*
  4429. * Now we decode the value of the DISPLAY variable and make a
  4430. * connection to the real X server.
  4431. */
  4432. #ifdef __APPLE__
  4433. /* Check if display is a path to a socket (as set by launchd). */
  4434. {
  4435. char path[PATH_MAX];
  4436. if (is_path_to_xsocket(display, path, sizeof(path))) {
  4437. debug("x11_connect_display: $DISPLAY is launchd");
  4438. /* Create a socket. */
  4439. sock = connect_local_xsocket_path(path);
  4440. if (sock < 0)
  4441. return -1;
  4442. /* OK, we now have a connection to the display. */
  4443. return sock;
  4444. }
  4445. }
  4446. #endif
  4447. /*
  4448. * Check if it is a unix domain socket. Unix domain displays are in
  4449. * one of the following formats: unix:d[.s], :d[.s], ::d[.s]
  4450. */
  4451. if (strncmp(display, "unix:", 5) == 0 ||
  4452. display[0] == ':') {
  4453. /* Connect to the unix domain socket. */
  4454. if (sscanf(strrchr(display, ':') + 1, "%u",
  4455. &display_number) != 1) {
  4456. error("Could not parse display number from DISPLAY: "
  4457. "%.100s", display);
  4458. return -1;
  4459. }
  4460. /* Create a socket. */
  4461. sock = connect_local_xsocket(display_number);
  4462. if (sock < 0)
  4463. return -1;
  4464. /* OK, we now have a connection to the display. */
  4465. return sock;
  4466. }
  4467. /*
  4468. * Connect to an inet socket. The DISPLAY value is supposedly
  4469. * hostname:d[.s], where hostname may also be numeric IP address.
  4470. */
  4471. strlcpy(buf, display, sizeof(buf));
  4472. cp = strchr(buf, ':');
  4473. if (!cp) {
  4474. error("Could not find ':' in DISPLAY: %.100s", display);
  4475. return -1;
  4476. }
  4477. *cp = 0;
  4478. /*
  4479. * buf now contains the host name. But first we parse the
  4480. * display number.
  4481. */
  4482. if (sscanf(cp + 1, "%u", &display_number) != 1) {
  4483. error("Could not parse display number from DISPLAY: %.100s",
  4484. display);
  4485. return -1;
  4486. }
  4487. /* Look up the host address */
  4488. memset(&hints, 0, sizeof(hints));
  4489. hints.ai_family = ssh->chanctxt->IPv4or6;
  4490. hints.ai_socktype = SOCK_STREAM;
  4491. snprintf(strport, sizeof strport, "%u", 6000 + display_number);
  4492. if ((gaierr = getaddrinfo(buf, strport, &hints, &aitop)) != 0) {
  4493. error("%.100s: unknown host. (%s)", buf,
  4494. ssh_gai_strerror(gaierr));
  4495. return -1;
  4496. }
  4497. for (ai = aitop; ai; ai = ai->ai_next) {
  4498. /* Create a socket. */
  4499. sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
  4500. if (sock == -1) {
  4501. debug2("socket: %.100s", strerror(errno));
  4502. continue;
  4503. }
  4504. /* Connect it to the display. */
  4505. if (connect(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
  4506. debug2("connect %.100s port %u: %.100s", buf,
  4507. 6000 + display_number, strerror(errno));
  4508. close(sock);
  4509. continue;
  4510. }
  4511. /* Success */
  4512. break;
  4513. }
  4514. freeaddrinfo(aitop);
  4515. if (!ai) {
  4516. error("connect %.100s port %u: %.100s", buf,
  4517. 6000 + display_number, strerror(errno));
  4518. return -1;
  4519. }
  4520. set_nodelay(sock);
  4521. return sock;
  4522. }
  4523. /*
  4524. * Requests forwarding of X11 connections, generates fake authentication
  4525. * data, and enables authentication spoofing.
  4526. * This should be called in the client only.
  4527. */
  4528. void
  4529. x11_request_forwarding_with_spoofing(struct ssh *ssh, int client_session_id,
  4530. const char *disp, const char *proto, const char *data, int want_reply)
  4531. {
  4532. struct ssh_channels *sc = ssh->chanctxt;
  4533. u_int data_len = (u_int) strlen(data) / 2;
  4534. u_int i, value;
  4535. const char *cp;
  4536. char *new_data;
  4537. int r, screen_number;
  4538. if (sc->x11_saved_display == NULL)
  4539. sc->x11_saved_display = xstrdup(disp);
  4540. else if (strcmp(disp, sc->x11_saved_display) != 0) {
  4541. error("x11_request_forwarding_with_spoofing: different "
  4542. "$DISPLAY already forwarded");
  4543. return;
  4544. }
  4545. cp = strchr(disp, ':');
  4546. if (cp)
  4547. cp = strchr(cp, '.');
  4548. if (cp)
  4549. screen_number = (u_int)strtonum(cp + 1, 0, 400, NULL);
  4550. else
  4551. screen_number = 0;
  4552. if (sc->x11_saved_proto == NULL) {
  4553. /* Save protocol name. */
  4554. sc->x11_saved_proto = xstrdup(proto);
  4555. /* Extract real authentication data. */
  4556. sc->x11_saved_data = xmalloc(data_len);
  4557. for (i = 0; i < data_len; i++) {
  4558. if (sscanf(data + 2 * i, "%2x", &value) != 1)
  4559. fatal("x11_request_forwarding: bad "
  4560. "authentication data: %.100s", data);
  4561. sc->x11_saved_data[i] = value;
  4562. }
  4563. sc->x11_saved_data_len = data_len;
  4564. /* Generate fake data of the same length. */
  4565. sc->x11_fake_data = xmalloc(data_len);
  4566. arc4random_buf(sc->x11_fake_data, data_len);
  4567. sc->x11_fake_data_len = data_len;
  4568. }
  4569. /* Convert the fake data into hex. */
  4570. new_data = tohex(sc->x11_fake_data, data_len);
  4571. /* Send the request packet. */
  4572. channel_request_start(ssh, client_session_id, "x11-req", want_reply);
  4573. if ((r = sshpkt_put_u8(ssh, 0)) != 0 || /* bool: single connection */
  4574. (r = sshpkt_put_cstring(ssh, proto)) != 0 ||
  4575. (r = sshpkt_put_cstring(ssh, new_data)) != 0 ||
  4576. (r = sshpkt_put_u32(ssh, screen_number)) != 0 ||
  4577. (r = sshpkt_send(ssh)) != 0 ||
  4578. (r = ssh_packet_write_wait(ssh)) != 0)
  4579. fatal("%s: send x11-req: %s", __func__, ssh_err(r));
  4580. free(new_data);
  4581. }