session.c 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856
  1. /* $OpenBSD: session.c,v 1.324 2020/07/07 02:47:21 deraadt Exp $ */
  2. /*
  3. * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
  4. * All rights reserved
  5. *
  6. * As far as I am concerned, the code I have written for this software
  7. * can be used freely for any purpose. Any derived versions of this
  8. * software must be clearly marked as such, and if the derived work is
  9. * incompatible with the protocol description in the RFC file, it must be
  10. * called by a name other than "ssh" or "Secure Shell".
  11. *
  12. * SSH2 support by Markus Friedl.
  13. * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
  14. *
  15. * Redistribution and use in source and binary forms, with or without
  16. * modification, are permitted provided that the following conditions
  17. * are met:
  18. * 1. Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. * 2. Redistributions in binary form must reproduce the above copyright
  21. * notice, this list of conditions and the following disclaimer in the
  22. * documentation and/or other materials provided with the distribution.
  23. *
  24. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  25. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  26. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  27. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  28. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  29. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  30. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  31. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  32. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  33. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  34. */
  35. #include "includes.h"
  36. #include <sys/types.h>
  37. #include <sys/param.h>
  38. #ifdef HAVE_SYS_STAT_H
  39. # include <sys/stat.h>
  40. #endif
  41. #include <sys/socket.h>
  42. #include <sys/un.h>
  43. #include <sys/wait.h>
  44. #include <arpa/inet.h>
  45. #include <ctype.h>
  46. #include <errno.h>
  47. #include <fcntl.h>
  48. #include <grp.h>
  49. #include <netdb.h>
  50. #ifdef HAVE_PATHS_H
  51. #include <paths.h>
  52. #endif
  53. #include <pwd.h>
  54. #include <signal.h>
  55. #include <stdio.h>
  56. #include <stdlib.h>
  57. #include <string.h>
  58. #include <stdarg.h>
  59. #include <unistd.h>
  60. #include <limits.h>
  61. #include "openbsd-compat/sys-queue.h"
  62. #include "xmalloc.h"
  63. #include "ssh.h"
  64. #include "ssh2.h"
  65. #include "sshpty.h"
  66. #include "packet.h"
  67. #include "sshbuf.h"
  68. #include "ssherr.h"
  69. #include "match.h"
  70. #include "uidswap.h"
  71. #include "compat.h"
  72. #include "channels.h"
  73. #include "sshkey.h"
  74. #include "cipher.h"
  75. #ifdef GSSAPI
  76. #include "ssh-gss.h"
  77. #endif
  78. #include "hostfile.h"
  79. #include "auth.h"
  80. #include "auth-options.h"
  81. #include "authfd.h"
  82. #include "pathnames.h"
  83. #include "log.h"
  84. #include "misc.h"
  85. #include "servconf.h"
  86. #include "sshlogin.h"
  87. #include "serverloop.h"
  88. #include "canohost.h"
  89. #include "session.h"
  90. #include "kex.h"
  91. #include "monitor_wrap.h"
  92. #include "sftp.h"
  93. #include "atomicio.h"
  94. #if defined(KRB5) && defined(USE_AFS)
  95. #include <kafs.h>
  96. #endif
  97. #ifdef WITH_SELINUX
  98. #include <selinux/selinux.h>
  99. #endif
  100. #define IS_INTERNAL_SFTP(c) \
  101. (!strncmp(c, INTERNAL_SFTP_NAME, sizeof(INTERNAL_SFTP_NAME) - 1) && \
  102. (c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\0' || \
  103. c[sizeof(INTERNAL_SFTP_NAME) - 1] == ' ' || \
  104. c[sizeof(INTERNAL_SFTP_NAME) - 1] == '\t'))
  105. /* func */
  106. Session *session_new(void);
  107. void session_set_fds(struct ssh *, Session *, int, int, int, int, int);
  108. void session_pty_cleanup(Session *);
  109. void session_proctitle(Session *);
  110. int session_setup_x11fwd(struct ssh *, Session *);
  111. int do_exec_pty(struct ssh *, Session *, const char *);
  112. int do_exec_no_pty(struct ssh *, Session *, const char *);
  113. int do_exec(struct ssh *, Session *, const char *);
  114. void do_login(struct ssh *, Session *, const char *);
  115. void do_child(struct ssh *, Session *, const char *);
  116. void do_motd(void);
  117. int check_quietlogin(Session *, const char *);
  118. static void do_authenticated2(struct ssh *, Authctxt *);
  119. static int session_pty_req(struct ssh *, Session *);
  120. /* import */
  121. extern ServerOptions options;
  122. extern char *__progname;
  123. extern int debug_flag;
  124. extern u_int utmp_len;
  125. extern int startup_pipe;
  126. extern void destroy_sensitive_data(struct ssh *, int);
  127. extern struct sshbuf *loginmsg;
  128. extern struct sshauthopt *auth_opts;
  129. extern char *tun_fwd_ifnames; /* serverloop.c */
  130. /* original command from peer. */
  131. const char *original_command = NULL;
  132. /* data */
  133. static int sessions_first_unused = -1;
  134. static int sessions_nalloc = 0;
  135. static Session *sessions = NULL;
  136. #define SUBSYSTEM_NONE 0
  137. #define SUBSYSTEM_EXT 1
  138. #define SUBSYSTEM_INT_SFTP 2
  139. #define SUBSYSTEM_INT_SFTP_ERROR 3
  140. #ifdef HAVE_LOGIN_CAP
  141. login_cap_t *lc;
  142. #endif
  143. static int is_child = 0;
  144. static int in_chroot = 0;
  145. static int have_dev_log = 1;
  146. /* File containing userauth info, if ExposeAuthInfo set */
  147. static char *auth_info_file = NULL;
  148. /* Name and directory of socket for authentication agent forwarding. */
  149. static char *auth_sock_name = NULL;
  150. static char *auth_sock_dir = NULL;
  151. /* removes the agent forwarding socket */
  152. static void
  153. auth_sock_cleanup_proc(struct passwd *pw)
  154. {
  155. if (auth_sock_name != NULL) {
  156. temporarily_use_uid(pw);
  157. unlink(auth_sock_name);
  158. rmdir(auth_sock_dir);
  159. auth_sock_name = NULL;
  160. restore_uid();
  161. }
  162. }
  163. static int
  164. auth_input_request_forwarding(struct ssh *ssh, struct passwd * pw)
  165. {
  166. Channel *nc;
  167. int sock = -1;
  168. if (auth_sock_name != NULL) {
  169. error("authentication forwarding requested twice.");
  170. return 0;
  171. }
  172. /* Temporarily drop privileged uid for mkdir/bind. */
  173. temporarily_use_uid(pw);
  174. /* Allocate a buffer for the socket name, and format the name. */
  175. auth_sock_dir = xstrdup("/tmp/ssh-XXXXXXXXXX");
  176. /* Create private directory for socket */
  177. if (mkdtemp(auth_sock_dir) == NULL) {
  178. ssh_packet_send_debug(ssh, "Agent forwarding disabled: "
  179. "mkdtemp() failed: %.100s", strerror(errno));
  180. restore_uid();
  181. free(auth_sock_dir);
  182. auth_sock_dir = NULL;
  183. goto authsock_err;
  184. }
  185. xasprintf(&auth_sock_name, "%s/agent.%ld",
  186. auth_sock_dir, (long) getpid());
  187. /* Start a Unix listener on auth_sock_name. */
  188. sock = unix_listener(auth_sock_name, SSH_LISTEN_BACKLOG, 0);
  189. /* Restore the privileged uid. */
  190. restore_uid();
  191. /* Check for socket/bind/listen failure. */
  192. if (sock < 0)
  193. goto authsock_err;
  194. /* Allocate a channel for the authentication agent socket. */
  195. /* this shouldn't matter if its hpn or not - cjr */
  196. nc = channel_new(ssh, "auth socket",
  197. SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
  198. CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
  199. 0, "auth socket", 1);
  200. nc->path = xstrdup(auth_sock_name);
  201. return 1;
  202. authsock_err:
  203. free(auth_sock_name);
  204. if (auth_sock_dir != NULL) {
  205. temporarily_use_uid(pw);
  206. rmdir(auth_sock_dir);
  207. restore_uid();
  208. free(auth_sock_dir);
  209. }
  210. if (sock != -1)
  211. close(sock);
  212. auth_sock_name = NULL;
  213. auth_sock_dir = NULL;
  214. return 0;
  215. }
  216. static void
  217. display_loginmsg(void)
  218. {
  219. int r;
  220. if (sshbuf_len(loginmsg) == 0)
  221. return;
  222. if ((r = sshbuf_put_u8(loginmsg, 0)) != 0)
  223. fatal("%s: buffer error: %s", __func__, ssh_err(r));
  224. printf("%s", (char *)sshbuf_ptr(loginmsg));
  225. sshbuf_reset(loginmsg);
  226. }
  227. static void
  228. prepare_auth_info_file(struct passwd *pw, struct sshbuf *info)
  229. {
  230. int fd = -1, success = 0;
  231. if (!options.expose_userauth_info || info == NULL)
  232. return;
  233. temporarily_use_uid(pw);
  234. auth_info_file = xstrdup("/tmp/sshauth.XXXXXXXXXXXXXXX");
  235. if ((fd = mkstemp(auth_info_file)) == -1) {
  236. error("%s: mkstemp: %s", __func__, strerror(errno));
  237. goto out;
  238. }
  239. if (atomicio(vwrite, fd, sshbuf_mutable_ptr(info),
  240. sshbuf_len(info)) != sshbuf_len(info)) {
  241. error("%s: write: %s", __func__, strerror(errno));
  242. goto out;
  243. }
  244. if (close(fd) != 0) {
  245. error("%s: close: %s", __func__, strerror(errno));
  246. goto out;
  247. }
  248. success = 1;
  249. out:
  250. if (!success) {
  251. if (fd != -1)
  252. close(fd);
  253. free(auth_info_file);
  254. auth_info_file = NULL;
  255. }
  256. restore_uid();
  257. }
  258. static void
  259. set_fwdpermit_from_authopts(struct ssh *ssh, const struct sshauthopt *opts)
  260. {
  261. char *tmp, *cp, *host;
  262. int port;
  263. size_t i;
  264. if ((options.allow_tcp_forwarding & FORWARD_LOCAL) != 0) {
  265. channel_clear_permission(ssh, FORWARD_USER, FORWARD_LOCAL);
  266. for (i = 0; i < auth_opts->npermitopen; i++) {
  267. tmp = cp = xstrdup(auth_opts->permitopen[i]);
  268. /* This shouldn't fail as it has already been checked */
  269. if ((host = hpdelim(&cp)) == NULL)
  270. fatal("%s: internal error: hpdelim", __func__);
  271. host = cleanhostname(host);
  272. if (cp == NULL || (port = permitopen_port(cp)) < 0)
  273. fatal("%s: internal error: permitopen port",
  274. __func__);
  275. channel_add_permission(ssh,
  276. FORWARD_USER, FORWARD_LOCAL, host, port);
  277. free(tmp);
  278. }
  279. }
  280. if ((options.allow_tcp_forwarding & FORWARD_REMOTE) != 0) {
  281. channel_clear_permission(ssh, FORWARD_USER, FORWARD_REMOTE);
  282. for (i = 0; i < auth_opts->npermitlisten; i++) {
  283. tmp = cp = xstrdup(auth_opts->permitlisten[i]);
  284. /* This shouldn't fail as it has already been checked */
  285. if ((host = hpdelim(&cp)) == NULL)
  286. fatal("%s: internal error: hpdelim", __func__);
  287. host = cleanhostname(host);
  288. if (cp == NULL || (port = permitopen_port(cp)) < 0)
  289. fatal("%s: internal error: permitlisten port",
  290. __func__);
  291. channel_add_permission(ssh,
  292. FORWARD_USER, FORWARD_REMOTE, host, port);
  293. free(tmp);
  294. }
  295. }
  296. }
  297. void
  298. do_authenticated(struct ssh *ssh, Authctxt *authctxt)
  299. {
  300. setproctitle("%s", authctxt->pw->pw_name);
  301. auth_log_authopts("active", auth_opts, 0);
  302. /* setup the channel layer */
  303. /* XXX - streamlocal? */
  304. set_fwdpermit_from_authopts(ssh, auth_opts);
  305. if (!auth_opts->permit_port_forwarding_flag ||
  306. options.disable_forwarding) {
  307. channel_disable_admin(ssh, FORWARD_LOCAL);
  308. channel_disable_admin(ssh, FORWARD_REMOTE);
  309. } else {
  310. if ((options.allow_tcp_forwarding & FORWARD_LOCAL) == 0)
  311. channel_disable_admin(ssh, FORWARD_LOCAL);
  312. else
  313. channel_permit_all(ssh, FORWARD_LOCAL);
  314. if ((options.allow_tcp_forwarding & FORWARD_REMOTE) == 0)
  315. channel_disable_admin(ssh, FORWARD_REMOTE);
  316. else
  317. channel_permit_all(ssh, FORWARD_REMOTE);
  318. }
  319. auth_debug_send(ssh);
  320. prepare_auth_info_file(authctxt->pw, authctxt->session_info);
  321. do_authenticated2(ssh, authctxt);
  322. do_cleanup(ssh, authctxt);
  323. }
  324. /* Check untrusted xauth strings for metacharacters */
  325. static int
  326. xauth_valid_string(const char *s)
  327. {
  328. size_t i;
  329. for (i = 0; s[i] != '\0'; i++) {
  330. if (!isalnum((u_char)s[i]) &&
  331. s[i] != '.' && s[i] != ':' && s[i] != '/' &&
  332. s[i] != '-' && s[i] != '_')
  333. return 0;
  334. }
  335. return 1;
  336. }
  337. #define USE_PIPES 1
  338. /*
  339. * This is called to fork and execute a command when we have no tty. This
  340. * will call do_child from the child, and server_loop from the parent after
  341. * setting up file descriptors and such.
  342. */
  343. int
  344. do_exec_no_pty(struct ssh *ssh, Session *s, const char *command)
  345. {
  346. pid_t pid;
  347. #ifdef USE_PIPES
  348. int pin[2], pout[2], perr[2];
  349. if (s == NULL)
  350. fatal("do_exec_no_pty: no session");
  351. /* Allocate pipes for communicating with the program. */
  352. if (pipe(pin) == -1) {
  353. error("%s: pipe in: %.100s", __func__, strerror(errno));
  354. return -1;
  355. }
  356. if (pipe(pout) == -1) {
  357. error("%s: pipe out: %.100s", __func__, strerror(errno));
  358. close(pin[0]);
  359. close(pin[1]);
  360. return -1;
  361. }
  362. if (pipe(perr) == -1) {
  363. error("%s: pipe err: %.100s", __func__,
  364. strerror(errno));
  365. close(pin[0]);
  366. close(pin[1]);
  367. close(pout[0]);
  368. close(pout[1]);
  369. return -1;
  370. }
  371. #else
  372. int inout[2], err[2];
  373. if (s == NULL)
  374. fatal("do_exec_no_pty: no session");
  375. /* Uses socket pairs to communicate with the program. */
  376. if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) == -1) {
  377. error("%s: socketpair #1: %.100s", __func__, strerror(errno));
  378. return -1;
  379. }
  380. if (socketpair(AF_UNIX, SOCK_STREAM, 0, err) == -1) {
  381. error("%s: socketpair #2: %.100s", __func__,
  382. strerror(errno));
  383. close(inout[0]);
  384. close(inout[1]);
  385. return -1;
  386. }
  387. #endif
  388. session_proctitle(s);
  389. /* Fork the child. */
  390. switch ((pid = fork())) {
  391. case -1:
  392. error("%s: fork: %.100s", __func__, strerror(errno));
  393. #ifdef USE_PIPES
  394. close(pin[0]);
  395. close(pin[1]);
  396. close(pout[0]);
  397. close(pout[1]);
  398. close(perr[0]);
  399. close(perr[1]);
  400. #else
  401. close(inout[0]);
  402. close(inout[1]);
  403. close(err[0]);
  404. close(err[1]);
  405. #endif
  406. return -1;
  407. case 0:
  408. is_child = 1;
  409. /*
  410. * Create a new session and process group since the 4.4BSD
  411. * setlogin() affects the entire process group.
  412. */
  413. if (setsid() == -1)
  414. error("setsid failed: %.100s", strerror(errno));
  415. #ifdef USE_PIPES
  416. /*
  417. * Redirect stdin. We close the parent side of the socket
  418. * pair, and make the child side the standard input.
  419. */
  420. close(pin[1]);
  421. if (dup2(pin[0], 0) == -1)
  422. perror("dup2 stdin");
  423. close(pin[0]);
  424. /* Redirect stdout. */
  425. close(pout[0]);
  426. if (dup2(pout[1], 1) == -1)
  427. perror("dup2 stdout");
  428. close(pout[1]);
  429. /* Redirect stderr. */
  430. close(perr[0]);
  431. if (dup2(perr[1], 2) == -1)
  432. perror("dup2 stderr");
  433. close(perr[1]);
  434. #else
  435. /*
  436. * Redirect stdin, stdout, and stderr. Stdin and stdout will
  437. * use the same socket, as some programs (particularly rdist)
  438. * seem to depend on it.
  439. */
  440. close(inout[1]);
  441. close(err[1]);
  442. if (dup2(inout[0], 0) == -1) /* stdin */
  443. perror("dup2 stdin");
  444. if (dup2(inout[0], 1) == -1) /* stdout (same as stdin) */
  445. perror("dup2 stdout");
  446. close(inout[0]);
  447. if (dup2(err[0], 2) == -1) /* stderr */
  448. perror("dup2 stderr");
  449. close(err[0]);
  450. #endif
  451. /* Do processing for the child (exec command etc). */
  452. do_child(ssh, s, command);
  453. /* NOTREACHED */
  454. default:
  455. break;
  456. }
  457. #ifdef HAVE_CYGWIN
  458. cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
  459. #endif
  460. s->pid = pid;
  461. /* Set interactive/non-interactive mode. */
  462. ssh_packet_set_interactive(ssh, s->display != NULL,
  463. options.ip_qos_interactive, options.ip_qos_bulk);
  464. /*
  465. * Clear loginmsg, since it's the child's responsibility to display
  466. * it to the user, otherwise multiple sessions may accumulate
  467. * multiple copies of the login messages.
  468. */
  469. sshbuf_reset(loginmsg);
  470. #ifdef USE_PIPES
  471. /* We are the parent. Close the child sides of the pipes. */
  472. close(pin[0]);
  473. close(pout[1]);
  474. close(perr[1]);
  475. session_set_fds(ssh, s, pin[1], pout[0], perr[0],
  476. s->is_subsystem, 0);
  477. #else
  478. /* We are the parent. Close the child sides of the socket pairs. */
  479. close(inout[0]);
  480. close(err[0]);
  481. /*
  482. * Enter the interactive session. Note: server_loop must be able to
  483. * handle the case that fdin and fdout are the same.
  484. */
  485. session_set_fds(ssh, s, inout[1], inout[1], err[1],
  486. s->is_subsystem, 0);
  487. #endif
  488. return 0;
  489. }
  490. /*
  491. * This is called to fork and execute a command when we have a tty. This
  492. * will call do_child from the child, and server_loop from the parent after
  493. * setting up file descriptors, controlling tty, updating wtmp, utmp,
  494. * lastlog, and other such operations.
  495. */
  496. int
  497. do_exec_pty(struct ssh *ssh, Session *s, const char *command)
  498. {
  499. int fdout, ptyfd, ttyfd, ptymaster;
  500. pid_t pid;
  501. if (s == NULL)
  502. fatal("do_exec_pty: no session");
  503. ptyfd = s->ptyfd;
  504. ttyfd = s->ttyfd;
  505. /*
  506. * Create another descriptor of the pty master side for use as the
  507. * standard input. We could use the original descriptor, but this
  508. * simplifies code in server_loop. The descriptor is bidirectional.
  509. * Do this before forking (and cleanup in the child) so as to
  510. * detect and gracefully fail out-of-fd conditions.
  511. */
  512. if ((fdout = dup(ptyfd)) == -1) {
  513. error("%s: dup #1: %s", __func__, strerror(errno));
  514. close(ttyfd);
  515. close(ptyfd);
  516. return -1;
  517. }
  518. /* we keep a reference to the pty master */
  519. if ((ptymaster = dup(ptyfd)) == -1) {
  520. error("%s: dup #2: %s", __func__, strerror(errno));
  521. close(ttyfd);
  522. close(ptyfd);
  523. close(fdout);
  524. return -1;
  525. }
  526. /* Fork the child. */
  527. switch ((pid = fork())) {
  528. case -1:
  529. error("%s: fork: %.100s", __func__, strerror(errno));
  530. close(fdout);
  531. close(ptymaster);
  532. close(ttyfd);
  533. close(ptyfd);
  534. return -1;
  535. case 0:
  536. is_child = 1;
  537. close(fdout);
  538. close(ptymaster);
  539. /* Close the master side of the pseudo tty. */
  540. close(ptyfd);
  541. /* Make the pseudo tty our controlling tty. */
  542. pty_make_controlling_tty(&ttyfd, s->tty);
  543. /* Redirect stdin/stdout/stderr from the pseudo tty. */
  544. if (dup2(ttyfd, 0) == -1)
  545. error("dup2 stdin: %s", strerror(errno));
  546. if (dup2(ttyfd, 1) == -1)
  547. error("dup2 stdout: %s", strerror(errno));
  548. if (dup2(ttyfd, 2) == -1)
  549. error("dup2 stderr: %s", strerror(errno));
  550. /* Close the extra descriptor for the pseudo tty. */
  551. close(ttyfd);
  552. /* record login, etc. similar to login(1) */
  553. #ifndef HAVE_OSF_SIA
  554. do_login(ssh, s, command);
  555. #endif
  556. /*
  557. * Do common processing for the child, such as execing
  558. * the command.
  559. */
  560. do_child(ssh, s, command);
  561. /* NOTREACHED */
  562. default:
  563. break;
  564. }
  565. #ifdef HAVE_CYGWIN
  566. cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
  567. #endif
  568. s->pid = pid;
  569. /* Parent. Close the slave side of the pseudo tty. */
  570. close(ttyfd);
  571. #if !defined(HAVE_OSF_SIA) && defined(SSH_AUDIT_EVENTS)
  572. /* do_login in the child did not affect state in this process,
  573. compensate. From an architectural standpoint, this is extremely
  574. ugly. */
  575. if (command != NULL)
  576. audit_count_session_open();
  577. #endif
  578. /* Enter interactive session. */
  579. s->ptymaster = ptymaster;
  580. ssh_packet_set_interactive(ssh, 1,
  581. options.ip_qos_interactive, options.ip_qos_bulk);
  582. session_set_fds(ssh, s, ptyfd, fdout, -1, 1, 1);
  583. return 0;
  584. }
  585. /*
  586. * This is called to fork and execute a command. If another command is
  587. * to be forced, execute that instead.
  588. */
  589. int
  590. do_exec(struct ssh *ssh, Session *s, const char *command)
  591. {
  592. int ret;
  593. const char *forced = NULL, *tty = NULL;
  594. char session_type[1024];
  595. struct stat dev_log_stat;
  596. if (options.adm_forced_command) {
  597. original_command = command;
  598. command = options.adm_forced_command;
  599. forced = "(config)";
  600. } else if (auth_opts->force_command != NULL) {
  601. original_command = command;
  602. command = auth_opts->force_command;
  603. forced = "(key-option)";
  604. }
  605. #ifdef GSSAPI
  606. #ifdef KRB5 /* k5users_allowed_cmds only available w/ GSSAPI+KRB5 */
  607. else if (k5users_allowed_cmds) {
  608. const char *match = command;
  609. int allowed = 0, i = 0;
  610. if (!match)
  611. match = s->pw->pw_shell;
  612. while (k5users_allowed_cmds[i]) {
  613. if (strcmp(match, k5users_allowed_cmds[i++]) == 0) {
  614. debug("Allowed command '%.900s'", match);
  615. allowed = 1;
  616. break;
  617. }
  618. }
  619. if (!allowed) {
  620. debug("command '%.900s' not allowed", match);
  621. return 1;
  622. }
  623. }
  624. #endif
  625. #endif
  626. s->forced = 0;
  627. if (forced != NULL) {
  628. s->forced = 1;
  629. if (IS_INTERNAL_SFTP(command)) {
  630. s->is_subsystem = s->is_subsystem ?
  631. SUBSYSTEM_INT_SFTP : SUBSYSTEM_INT_SFTP_ERROR;
  632. } else if (s->is_subsystem)
  633. s->is_subsystem = SUBSYSTEM_EXT;
  634. snprintf(session_type, sizeof(session_type),
  635. "forced-command %s '%.900s'", forced, command);
  636. } else if (s->is_subsystem) {
  637. snprintf(session_type, sizeof(session_type),
  638. "subsystem '%.900s'", s->subsys);
  639. } else if (command == NULL) {
  640. snprintf(session_type, sizeof(session_type), "shell");
  641. } else {
  642. /* NB. we don't log unforced commands to preserve privacy */
  643. snprintf(session_type, sizeof(session_type), "command");
  644. }
  645. if (s->ttyfd != -1) {
  646. tty = s->tty;
  647. if (strncmp(tty, "/dev/", 5) == 0)
  648. tty += 5;
  649. }
  650. if (lstat("/dev/log", &dev_log_stat) != 0) {
  651. have_dev_log = 0;
  652. }
  653. verbose("Starting session: %s%s%s for %s from %.200s port %d id %d",
  654. session_type,
  655. tty == NULL ? "" : " on ",
  656. tty == NULL ? "" : tty,
  657. s->pw->pw_name,
  658. ssh_remote_ipaddr(ssh),
  659. ssh_remote_port(ssh),
  660. s->self);
  661. #ifdef SSH_AUDIT_EVENTS
  662. if (s->command != NULL || s->command_handle != -1)
  663. fatal("do_exec: command already set");
  664. if (command != NULL)
  665. s->command = xstrdup(command);
  666. else if (s->ttyfd == -1) {
  667. char *shell = s->pw->pw_shell;
  668. if (shell[0] == '\0') /* empty shell means /bin/sh */
  669. shell =_PATH_BSHELL;
  670. s->command = xstrdup(shell);
  671. }
  672. if (s->command != NULL && s->ptyfd == -1)
  673. s->command_handle = PRIVSEP(audit_run_command(ssh, s->command));
  674. #endif
  675. if (s->ttyfd != -1)
  676. ret = do_exec_pty(ssh, s, command);
  677. else
  678. ret = do_exec_no_pty(ssh, s, command);
  679. original_command = NULL;
  680. /*
  681. * Clear loginmsg: it's the child's responsibility to display
  682. * it to the user, otherwise multiple sessions may accumulate
  683. * multiple copies of the login messages.
  684. */
  685. sshbuf_reset(loginmsg);
  686. return ret;
  687. }
  688. /* administrative, login(1)-like work */
  689. void
  690. do_login(struct ssh *ssh, Session *s, const char *command)
  691. {
  692. socklen_t fromlen;
  693. struct sockaddr_storage from;
  694. struct passwd * pw = s->pw;
  695. pid_t pid = getpid();
  696. /*
  697. * Get IP address of client. If the connection is not a socket, let
  698. * the address be 0.0.0.0.
  699. */
  700. memset(&from, 0, sizeof(from));
  701. fromlen = sizeof(from);
  702. if (ssh_packet_connection_is_on_socket(ssh)) {
  703. if (getpeername(ssh_packet_get_connection_in(ssh),
  704. (struct sockaddr *)&from, &fromlen) == -1) {
  705. debug("getpeername: %.100s", strerror(errno));
  706. cleanup_exit(255);
  707. }
  708. }
  709. /* Record that there was a login on that tty from the remote host. */
  710. if (!use_privsep)
  711. record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
  712. session_get_remote_name_or_ip(ssh, utmp_len,
  713. options.use_dns),
  714. (struct sockaddr *)&from, fromlen);
  715. #ifdef USE_PAM
  716. /*
  717. * If password change is needed, do it now.
  718. * This needs to occur before the ~/.hushlogin check.
  719. */
  720. if (options.use_pam && !use_privsep && s->authctxt->force_pwchange) {
  721. display_loginmsg();
  722. do_pam_chauthtok();
  723. s->authctxt->force_pwchange = 0;
  724. /* XXX - signal [net] parent to enable forwardings */
  725. }
  726. #endif
  727. if (check_quietlogin(s, command))
  728. return;
  729. display_loginmsg();
  730. do_motd();
  731. }
  732. /*
  733. * Display the message of the day.
  734. */
  735. void
  736. do_motd(void)
  737. {
  738. FILE *f;
  739. char buf[256];
  740. if (options.print_motd) {
  741. #ifdef HAVE_LOGIN_CAP
  742. f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
  743. "/etc/motd"), "r");
  744. #else
  745. f = fopen("/etc/motd", "r");
  746. #endif
  747. if (f) {
  748. while (fgets(buf, sizeof(buf), f))
  749. fputs(buf, stdout);
  750. fclose(f);
  751. }
  752. }
  753. }
  754. /*
  755. * Check for quiet login, either .hushlogin or command given.
  756. */
  757. int
  758. check_quietlogin(Session *s, const char *command)
  759. {
  760. char buf[256];
  761. struct passwd *pw = s->pw;
  762. struct stat st;
  763. /* Return 1 if .hushlogin exists or a command given. */
  764. if (command != NULL)
  765. return 1;
  766. snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
  767. #ifdef HAVE_LOGIN_CAP
  768. if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
  769. return 1;
  770. #else
  771. if (stat(buf, &st) >= 0)
  772. return 1;
  773. #endif
  774. return 0;
  775. }
  776. /*
  777. * Reads environment variables from the given file and adds/overrides them
  778. * into the environment. If the file does not exist, this does nothing.
  779. * Otherwise, it must consist of empty lines, comments (line starts with '#')
  780. * and assignments of the form name=value. No other forms are allowed.
  781. * If allowlist is not NULL, then it is interpreted as a pattern list and
  782. * only variable names that match it will be accepted.
  783. */
  784. static void
  785. read_environment_file(char ***env, u_int *envsize,
  786. const char *filename, const char *allowlist)
  787. {
  788. FILE *f;
  789. char *line = NULL, *cp, *value;
  790. size_t linesize = 0;
  791. u_int lineno = 0;
  792. f = fopen(filename, "r");
  793. if (!f)
  794. return;
  795. while (getline(&line, &linesize, f) != -1) {
  796. if (++lineno > 1000)
  797. fatal("Too many lines in environment file %s", filename);
  798. for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
  799. ;
  800. if (!*cp || *cp == '#' || *cp == '\n')
  801. continue;
  802. cp[strcspn(cp, "\n")] = '\0';
  803. value = strchr(cp, '=');
  804. if (value == NULL) {
  805. fprintf(stderr, "Bad line %u in %.100s\n", lineno,
  806. filename);
  807. continue;
  808. }
  809. /*
  810. * Replace the equals sign by nul, and advance value to
  811. * the value string.
  812. */
  813. *value = '\0';
  814. value++;
  815. if (allowlist != NULL &&
  816. match_pattern_list(cp, allowlist, 0) != 1)
  817. continue;
  818. child_set_env(env, envsize, cp, value);
  819. }
  820. free(line);
  821. fclose(f);
  822. }
  823. #ifdef HAVE_ETC_DEFAULT_LOGIN
  824. /*
  825. * Return named variable from specified environment, or NULL if not present.
  826. */
  827. static char *
  828. child_get_env(char **env, const char *name)
  829. {
  830. int i;
  831. size_t len;
  832. len = strlen(name);
  833. for (i=0; env[i] != NULL; i++)
  834. if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
  835. return(env[i] + len + 1);
  836. return NULL;
  837. }
  838. /*
  839. * Read /etc/default/login.
  840. * We pick up the PATH (or SUPATH for root) and UMASK.
  841. */
  842. static void
  843. read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
  844. {
  845. char **tmpenv = NULL, *var;
  846. u_int i, tmpenvsize = 0;
  847. u_long mask;
  848. /*
  849. * We don't want to copy the whole file to the child's environment,
  850. * so we use a temporary environment and copy the variables we're
  851. * interested in.
  852. */
  853. read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login",
  854. options.permit_user_env_allowlist);
  855. if (tmpenv == NULL)
  856. return;
  857. if (uid == 0)
  858. var = child_get_env(tmpenv, "SUPATH");
  859. else
  860. var = child_get_env(tmpenv, "PATH");
  861. if (var != NULL)
  862. child_set_env(env, envsize, "PATH", var);
  863. if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
  864. if (sscanf(var, "%5lo", &mask) == 1)
  865. umask((mode_t)mask);
  866. for (i = 0; tmpenv[i] != NULL; i++)
  867. free(tmpenv[i]);
  868. free(tmpenv);
  869. }
  870. #endif /* HAVE_ETC_DEFAULT_LOGIN */
  871. #if defined(USE_PAM) || defined(HAVE_CYGWIN)
  872. static void
  873. copy_environment_denylist(char **source, char ***env, u_int *envsize,
  874. const char *denylist)
  875. {
  876. char *var_name, *var_val;
  877. int i;
  878. if (source == NULL)
  879. return;
  880. for(i = 0; source[i] != NULL; i++) {
  881. var_name = xstrdup(source[i]);
  882. if ((var_val = strstr(var_name, "=")) == NULL) {
  883. free(var_name);
  884. continue;
  885. }
  886. *var_val++ = '\0';
  887. if (denylist == NULL ||
  888. match_pattern_list(var_name, denylist, 0) != 1) {
  889. debug3("Copy environment: %s=%s", var_name, var_val);
  890. child_set_env(env, envsize, var_name, var_val);
  891. }
  892. free(var_name);
  893. }
  894. }
  895. #endif /* defined(USE_PAM) || defined(HAVE_CYGWIN) */
  896. #ifdef HAVE_CYGWIN
  897. static void
  898. copy_environment(char **source, char ***env, u_int *envsize)
  899. {
  900. copy_environment_denylist(source, env, envsize, NULL);
  901. }
  902. #endif
  903. static char **
  904. do_setup_env(struct ssh *ssh, Session *s, const char *shell)
  905. {
  906. char buf[256];
  907. size_t n;
  908. u_int i, envsize;
  909. char *ocp, *cp, *value, **env, *laddr;
  910. struct passwd *pw = s->pw;
  911. #if !defined (HAVE_LOGIN_CAP) && !defined (HAVE_CYGWIN)
  912. char *path = NULL;
  913. #endif
  914. /* Initialize the environment. */
  915. envsize = 100;
  916. env = xcalloc(envsize, sizeof(char *));
  917. env[0] = NULL;
  918. #ifdef HAVE_CYGWIN
  919. /*
  920. * The Windows environment contains some setting which are
  921. * important for a running system. They must not be dropped.
  922. */
  923. {
  924. char **p;
  925. p = fetch_windows_environment();
  926. copy_environment(p, &env, &envsize);
  927. free_windows_environment(p);
  928. }
  929. #endif
  930. #ifdef GSSAPI
  931. /* Allow any GSSAPI methods that we've used to alter
  932. * the child's environment as they see fit
  933. */
  934. ssh_gssapi_do_child(&env, &envsize);
  935. #endif
  936. /* Set basic environment. */
  937. for (i = 0; i < s->num_env; i++)
  938. child_set_env(&env, &envsize, s->env[i].name, s->env[i].val);
  939. child_set_env(&env, &envsize, "USER", pw->pw_name);
  940. child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
  941. #ifdef _AIX
  942. child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
  943. #endif
  944. child_set_env(&env, &envsize, "HOME", pw->pw_dir);
  945. #ifdef HAVE_LOGIN_CAP
  946. if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
  947. child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
  948. else
  949. child_set_env(&env, &envsize, "PATH", getenv("PATH"));
  950. #else /* HAVE_LOGIN_CAP */
  951. # ifndef HAVE_CYGWIN
  952. /*
  953. * There's no standard path on Windows. The path contains
  954. * important components pointing to the system directories,
  955. * needed for loading shared libraries. So the path better
  956. * remains intact here.
  957. */
  958. # ifdef HAVE_ETC_DEFAULT_LOGIN
  959. read_etc_default_login(&env, &envsize, pw->pw_uid);
  960. path = child_get_env(env, "PATH");
  961. # endif /* HAVE_ETC_DEFAULT_LOGIN */
  962. if (path == NULL || *path == '\0') {
  963. child_set_env(&env, &envsize, "PATH",
  964. s->pw->pw_uid == 0 ? SUPERUSER_PATH : _PATH_STDPATH);
  965. }
  966. # endif /* HAVE_CYGWIN */
  967. #endif /* HAVE_LOGIN_CAP */
  968. if (!options.use_pam) {
  969. snprintf(buf, sizeof buf, "%.200s/%.50s",
  970. _PATH_MAILDIR, pw->pw_name);
  971. child_set_env(&env, &envsize, "MAIL", buf);
  972. }
  973. /* Normal systems set SHELL by default. */
  974. child_set_env(&env, &envsize, "SHELL", shell);
  975. if (getenv("TZ"))
  976. child_set_env(&env, &envsize, "TZ", getenv("TZ"));
  977. if (s->term)
  978. child_set_env(&env, &envsize, "TERM", s->term);
  979. if (s->display)
  980. child_set_env(&env, &envsize, "DISPLAY", s->display);
  981. /*
  982. * Since we clear KRB5CCNAME at startup, if it's set now then it
  983. * must have been set by a native authentication method (eg AIX or
  984. * SIA), so copy it to the child.
  985. */
  986. {
  987. char *cp;
  988. if ((cp = getenv("KRB5CCNAME")) != NULL)
  989. child_set_env(&env, &envsize, "KRB5CCNAME", cp);
  990. }
  991. #ifdef _AIX
  992. {
  993. char *cp;
  994. if ((cp = getenv("AUTHSTATE")) != NULL)
  995. child_set_env(&env, &envsize, "AUTHSTATE", cp);
  996. read_environment_file(&env, &envsize, "/etc/environment",
  997. options.permit_user_env_allowlist);
  998. }
  999. #endif
  1000. #ifdef KRB5
  1001. if (s->authctxt->krb5_ccname)
  1002. child_set_env(&env, &envsize, "KRB5CCNAME",
  1003. s->authctxt->krb5_ccname);
  1004. #endif
  1005. if (auth_sock_name != NULL)
  1006. child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
  1007. auth_sock_name);
  1008. /* Set custom environment options from pubkey authentication. */
  1009. if (options.permit_user_env) {
  1010. for (n = 0 ; n < auth_opts->nenv; n++) {
  1011. ocp = xstrdup(auth_opts->env[n]);
  1012. cp = strchr(ocp, '=');
  1013. if (cp != NULL) {
  1014. *cp = '\0';
  1015. /* Apply PermitUserEnvironment allowlist */
  1016. if (options.permit_user_env_allowlist == NULL ||
  1017. match_pattern_list(ocp,
  1018. options.permit_user_env_allowlist, 0) == 1)
  1019. child_set_env(&env, &envsize,
  1020. ocp, cp + 1);
  1021. }
  1022. free(ocp);
  1023. }
  1024. }
  1025. /* read $HOME/.ssh/environment. */
  1026. if (options.permit_user_env) {
  1027. snprintf(buf, sizeof buf, "%.200s/%s/environment",
  1028. pw->pw_dir, _PATH_SSH_USER_DIR);
  1029. read_environment_file(&env, &envsize, buf,
  1030. options.permit_user_env_allowlist);
  1031. }
  1032. #ifdef USE_PAM
  1033. /*
  1034. * Pull in any environment variables that may have
  1035. * been set by PAM.
  1036. */
  1037. if (options.use_pam) {
  1038. char **p;
  1039. /*
  1040. * Don't allow PAM-internal env vars to leak
  1041. * back into the session environment.
  1042. */
  1043. #define PAM_ENV_DENYLIST "SSH_AUTH_INFO*,SSH_CONNECTION*"
  1044. p = fetch_pam_child_environment();
  1045. copy_environment_denylist(p, &env, &envsize,
  1046. PAM_ENV_DENYLIST);
  1047. free_pam_environment(p);
  1048. p = fetch_pam_environment();
  1049. copy_environment_denylist(p, &env, &envsize,
  1050. PAM_ENV_DENYLIST);
  1051. free_pam_environment(p);
  1052. }
  1053. #endif /* USE_PAM */
  1054. /* Environment specified by admin */
  1055. for (i = 0; i < options.num_setenv; i++) {
  1056. cp = xstrdup(options.setenv[i]);
  1057. if ((value = strchr(cp, '=')) == NULL) {
  1058. /* shouldn't happen; vars are checked in servconf.c */
  1059. fatal("Invalid config SetEnv: %s", options.setenv[i]);
  1060. }
  1061. *value++ = '\0';
  1062. child_set_env(&env, &envsize, cp, value);
  1063. }
  1064. /* SSH_CLIENT deprecated */
  1065. snprintf(buf, sizeof buf, "%.50s %d %d",
  1066. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
  1067. ssh_local_port(ssh));
  1068. child_set_env(&env, &envsize, "SSH_CLIENT", buf);
  1069. laddr = get_local_ipaddr(ssh_packet_get_connection_in(ssh));
  1070. snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
  1071. ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
  1072. laddr, ssh_local_port(ssh));
  1073. free(laddr);
  1074. child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
  1075. if (tun_fwd_ifnames != NULL)
  1076. child_set_env(&env, &envsize, "SSH_TUNNEL", tun_fwd_ifnames);
  1077. if (auth_info_file != NULL)
  1078. child_set_env(&env, &envsize, "SSH_USER_AUTH", auth_info_file);
  1079. if (s->ttyfd != -1)
  1080. child_set_env(&env, &envsize, "SSH_TTY", s->tty);
  1081. if (original_command)
  1082. child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
  1083. original_command);
  1084. if (debug_flag) {
  1085. /* dump the environment */
  1086. fprintf(stderr, "Environment:\n");
  1087. for (i = 0; env[i]; i++)
  1088. fprintf(stderr, " %.200s\n", env[i]);
  1089. }
  1090. return env;
  1091. }
  1092. /*
  1093. * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
  1094. * first in this order).
  1095. */
  1096. static void
  1097. do_rc_files(struct ssh *ssh, Session *s, const char *shell)
  1098. {
  1099. FILE *f = NULL;
  1100. char *cmd = NULL, *user_rc = NULL;
  1101. int do_xauth;
  1102. struct stat st;
  1103. do_xauth =
  1104. s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
  1105. xasprintf(&user_rc, "%s/%s", s->pw->pw_dir, _PATH_SSH_USER_RC);
  1106. /* ignore _PATH_SSH_USER_RC for subsystems and admin forced commands */
  1107. if (!s->is_subsystem && options.adm_forced_command == NULL &&
  1108. auth_opts->permit_user_rc && options.permit_user_rc &&
  1109. stat(user_rc, &st) >= 0) {
  1110. if (xasprintf(&cmd, "%s -c '%s %s'", shell, _PATH_BSHELL,
  1111. user_rc) == -1)
  1112. fatal("%s: xasprintf: %s", __func__, strerror(errno));
  1113. if (debug_flag)
  1114. fprintf(stderr, "Running %s\n", cmd);
  1115. f = popen(cmd, "w");
  1116. if (f) {
  1117. if (do_xauth)
  1118. fprintf(f, "%s %s\n", s->auth_proto,
  1119. s->auth_data);
  1120. pclose(f);
  1121. } else
  1122. fprintf(stderr, "Could not run %s\n",
  1123. user_rc);
  1124. } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
  1125. if (debug_flag)
  1126. fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
  1127. _PATH_SSH_SYSTEM_RC);
  1128. f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
  1129. if (f) {
  1130. if (do_xauth)
  1131. fprintf(f, "%s %s\n", s->auth_proto,
  1132. s->auth_data);
  1133. pclose(f);
  1134. } else
  1135. fprintf(stderr, "Could not run %s\n",
  1136. _PATH_SSH_SYSTEM_RC);
  1137. } else if (do_xauth && options.xauth_location != NULL) {
  1138. /* Add authority data to .Xauthority if appropriate. */
  1139. if (debug_flag) {
  1140. fprintf(stderr,
  1141. "Running %.500s remove %.100s\n",
  1142. options.xauth_location, s->auth_display);
  1143. fprintf(stderr,
  1144. "%.500s add %.100s %.100s %.100s\n",
  1145. options.xauth_location, s->auth_display,
  1146. s->auth_proto, s->auth_data);
  1147. }
  1148. if (xasprintf(&cmd, "%s -q -", options.xauth_location) == -1)
  1149. fatal("%s: xasprintf: %s", __func__, strerror(errno));
  1150. f = popen(cmd, "w");
  1151. if (f) {
  1152. fprintf(f, "remove %s\n",
  1153. s->auth_display);
  1154. fprintf(f, "add %s %s %s\n",
  1155. s->auth_display, s->auth_proto,
  1156. s->auth_data);
  1157. pclose(f);
  1158. } else {
  1159. fprintf(stderr, "Could not run %s\n",
  1160. cmd);
  1161. }
  1162. }
  1163. free(cmd);
  1164. free(user_rc);
  1165. }
  1166. static void
  1167. do_nologin(struct passwd *pw)
  1168. {
  1169. FILE *f = NULL;
  1170. char buf[1024], *nl, *def_nl = _PATH_NOLOGIN;
  1171. struct stat sb;
  1172. #ifdef HAVE_LOGIN_CAP
  1173. if (login_getcapbool(lc, "ignorenologin", 0) || pw->pw_uid == 0)
  1174. return;
  1175. nl = login_getcapstr(lc, "nologin", def_nl, def_nl);
  1176. #else
  1177. if (pw->pw_uid == 0)
  1178. return;
  1179. nl = def_nl;
  1180. #endif
  1181. if (stat(nl, &sb) == -1)
  1182. return;
  1183. /* /etc/nologin exists. Print its contents if we can and exit. */
  1184. logit("User %.100s not allowed because %s exists", pw->pw_name, nl);
  1185. if ((f = fopen(nl, "r")) != NULL) {
  1186. while (fgets(buf, sizeof(buf), f))
  1187. fputs(buf, stderr);
  1188. fclose(f);
  1189. }
  1190. exit(254);
  1191. }
  1192. /*
  1193. * Chroot into a directory after checking it for safety: all path components
  1194. * must be root-owned directories with strict permissions.
  1195. */
  1196. static void
  1197. safely_chroot(const char *path, uid_t uid)
  1198. {
  1199. const char *cp;
  1200. char component[PATH_MAX];
  1201. struct stat st;
  1202. if (!path_absolute(path))
  1203. fatal("chroot path does not begin at root");
  1204. if (strlen(path) >= sizeof(component))
  1205. fatal("chroot path too long");
  1206. /*
  1207. * Descend the path, checking that each component is a
  1208. * root-owned directory with strict permissions.
  1209. */
  1210. for (cp = path; cp != NULL;) {
  1211. if ((cp = strchr(cp, '/')) == NULL)
  1212. strlcpy(component, path, sizeof(component));
  1213. else {
  1214. cp++;
  1215. memcpy(component, path, cp - path);
  1216. component[cp - path] = '\0';
  1217. }
  1218. debug3("%s: checking '%s'", __func__, component);
  1219. if (stat(component, &st) != 0)
  1220. fatal("%s: stat(\"%s\"): %s", __func__,
  1221. component, strerror(errno));
  1222. if (st.st_uid != 0 || (st.st_mode & 022) != 0)
  1223. fatal("bad ownership or modes for chroot "
  1224. "directory %s\"%s\"",
  1225. cp == NULL ? "" : "component ", component);
  1226. if (!S_ISDIR(st.st_mode))
  1227. fatal("chroot path %s\"%s\" is not a directory",
  1228. cp == NULL ? "" : "component ", component);
  1229. }
  1230. if (chdir(path) == -1)
  1231. fatal("Unable to chdir to chroot path \"%s\": "
  1232. "%s", path, strerror(errno));
  1233. if (chroot(path) == -1)
  1234. fatal("chroot(\"%s\"): %s", path, strerror(errno));
  1235. if (chdir("/") == -1)
  1236. fatal("%s: chdir(/) after chroot: %s",
  1237. __func__, strerror(errno));
  1238. verbose("Changed root directory to \"%s\"", path);
  1239. }
  1240. /* Set login name, uid, gid, and groups. */
  1241. void
  1242. do_setusercontext(struct passwd *pw)
  1243. {
  1244. char uidstr[32], *chroot_path, *tmp;
  1245. platform_setusercontext(pw);
  1246. if (platform_privileged_uidswap() && (!is_child || !use_privsep)) {
  1247. #ifdef HAVE_LOGIN_CAP
  1248. if (setusercontext(lc, pw, pw->pw_uid,
  1249. (LOGIN_SETALL & ~(LOGIN_SETPATH|LOGIN_SETUSER))) < 0) {
  1250. perror("unable to set user context");
  1251. exit(1);
  1252. }
  1253. #else
  1254. if (setlogin(pw->pw_name) < 0)
  1255. error("setlogin failed: %s", strerror(errno));
  1256. if (setgid(pw->pw_gid) < 0) {
  1257. perror("setgid");
  1258. exit(1);
  1259. }
  1260. /* Initialize the group list. */
  1261. if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
  1262. perror("initgroups");
  1263. exit(1);
  1264. }
  1265. endgrent();
  1266. #endif
  1267. platform_setusercontext_post_groups(pw);
  1268. if (!in_chroot && options.chroot_directory != NULL) { //&&
  1269. // strcasecmp(options.chroot_directory, "none") != 0) {
  1270. tmp = tilde_expand_filename(options.chroot_directory,
  1271. pw->pw_uid);
  1272. snprintf(uidstr, sizeof(uidstr), "%llu",
  1273. (unsigned long long)pw->pw_uid);
  1274. chroot_path = percent_expand(tmp, "h", pw->pw_dir,
  1275. "u", pw->pw_name, "U", uidstr, (char *)NULL);
  1276. #ifdef WITH_SELINUX
  1277. sshd_selinux_copy_context();
  1278. #endif
  1279. safely_chroot(chroot_path, pw->pw_uid);
  1280. free(tmp);
  1281. free(chroot_path);
  1282. /* Make sure we don't attempt to chroot again */
  1283. free(options.chroot_directory);
  1284. options.chroot_directory = NULL;
  1285. in_chroot = 1;
  1286. }
  1287. #ifdef HAVE_LOGIN_CAP
  1288. if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUSER) < 0) {
  1289. perror("unable to set user context (setuser)");
  1290. exit(1);
  1291. }
  1292. /*
  1293. * FreeBSD's setusercontext() will not apply the user's
  1294. * own umask setting unless running with the user's UID.
  1295. */
  1296. (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETUMASK);
  1297. #else
  1298. # ifdef USE_LIBIAF
  1299. /*
  1300. * In a chroot environment, the set_id() will always fail;
  1301. * typically because of the lack of necessary authentication
  1302. * services and runtime such as ./usr/lib/libiaf.so,
  1303. * ./usr/lib/libpam.so.1, and ./etc/passwd We skip it in the
  1304. * internal sftp chroot case. We'll lose auditing and ACLs but
  1305. * permanently_set_uid will take care of the rest.
  1306. */
  1307. if (!in_chroot && set_id(pw->pw_name) != 0)
  1308. fatal("set_id(%s) Failed", pw->pw_name);
  1309. # endif /* USE_LIBIAF */
  1310. /* Permanently switch to the desired uid. */
  1311. permanently_set_uid(pw);
  1312. #endif
  1313. #ifdef WITH_SELINUX
  1314. if (in_chroot == 0)
  1315. sshd_selinux_copy_context();
  1316. #endif
  1317. } else if (options.chroot_directory != NULL &&
  1318. strcasecmp(options.chroot_directory, "none") != 0) {
  1319. fatal("server lacks privileges to chroot to ChrootDirectory");
  1320. }
  1321. if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
  1322. fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
  1323. }
  1324. static void
  1325. do_pwchange(Session *s)
  1326. {
  1327. fflush(NULL);
  1328. fprintf(stderr, "WARNING: Your password has expired.\n");
  1329. if (s->ttyfd != -1) {
  1330. fprintf(stderr,
  1331. "You must change your password now and login again!\n");
  1332. #ifdef PASSWD_NEEDS_USERNAME
  1333. execl(_PATH_PASSWD_PROG, "passwd", s->pw->pw_name,
  1334. (char *)NULL);
  1335. #else
  1336. execl(_PATH_PASSWD_PROG, "passwd", (char *)NULL);
  1337. #endif
  1338. perror("passwd");
  1339. } else {
  1340. fprintf(stderr,
  1341. "Password change required but no TTY available.\n");
  1342. }
  1343. exit(1);
  1344. }
  1345. static void
  1346. child_close_fds(struct ssh *ssh)
  1347. {
  1348. extern int auth_sock;
  1349. if (auth_sock != -1) {
  1350. close(auth_sock);
  1351. auth_sock = -1;
  1352. }
  1353. if (ssh_packet_get_connection_in(ssh) ==
  1354. ssh_packet_get_connection_out(ssh))
  1355. close(ssh_packet_get_connection_in(ssh));
  1356. else {
  1357. close(ssh_packet_get_connection_in(ssh));
  1358. close(ssh_packet_get_connection_out(ssh));
  1359. }
  1360. /*
  1361. * Close all descriptors related to channels. They will still remain
  1362. * open in the parent.
  1363. */
  1364. /* XXX better use close-on-exec? -markus */
  1365. channel_close_all(ssh);
  1366. /*
  1367. * Close any extra file descriptors. Note that there may still be
  1368. * descriptors left by system functions. They will be closed later.
  1369. */
  1370. endpwent();
  1371. /* Stop directing logs to a high-numbered fd before we close it */
  1372. log_redirect_stderr_to(NULL);
  1373. }
  1374. /*
  1375. * Performs common processing for the child, such as setting up the
  1376. * environment, closing extra file descriptors, setting the user and group
  1377. * ids, and executing the command or shell.
  1378. */
  1379. #define ARGV_MAX 10
  1380. void
  1381. do_child(struct ssh *ssh, Session *s, const char *command)
  1382. {
  1383. extern char **environ;
  1384. char **env, *argv[ARGV_MAX], remote_id[512];
  1385. const char *shell, *shell0;
  1386. struct passwd *pw = s->pw;
  1387. int r = 0;
  1388. sshpkt_fmt_connection_id(ssh, remote_id, sizeof(remote_id));
  1389. /* remove hostkey from the child's memory */
  1390. destroy_sensitive_data(ssh, 1);
  1391. ssh_packet_clear_keys(ssh);
  1392. /* Don't audit this - both us and the parent would be talking to the
  1393. monitor over a single socket, with no synchronization. */
  1394. packet_destroy_all(ssh, 0, 1);
  1395. /* Force a password change */
  1396. if (s->authctxt->force_pwchange) {
  1397. do_setusercontext(pw);
  1398. child_close_fds(ssh);
  1399. do_pwchange(s);
  1400. exit(1);
  1401. }
  1402. /*
  1403. * Login(1) does this as well, and it needs uid 0 for the "-h"
  1404. * switch, so we let login(1) to this for us.
  1405. */
  1406. #ifdef HAVE_OSF_SIA
  1407. session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
  1408. if (!check_quietlogin(s, command))
  1409. do_motd();
  1410. #else /* HAVE_OSF_SIA */
  1411. /* When PAM is enabled we rely on it to do the nologin check */
  1412. if (!options.use_pam)
  1413. do_nologin(pw);
  1414. do_setusercontext(pw);
  1415. /*
  1416. * PAM session modules in do_setusercontext may have
  1417. * generated messages, so if this in an interactive
  1418. * login then display them too.
  1419. */
  1420. if (!check_quietlogin(s, command))
  1421. display_loginmsg();
  1422. #endif /* HAVE_OSF_SIA */
  1423. #ifdef USE_PAM
  1424. if (options.use_pam && !is_pam_session_open()) {
  1425. debug3("PAM session not opened, exiting");
  1426. display_loginmsg();
  1427. exit(254);
  1428. }
  1429. #endif
  1430. /*
  1431. * Get the shell from the password data. An empty shell field is
  1432. * legal, and means /bin/sh.
  1433. */
  1434. shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
  1435. /*
  1436. * Make sure $SHELL points to the shell from the password file,
  1437. * even if shell is overridden from login.conf
  1438. */
  1439. env = do_setup_env(ssh, s, shell);
  1440. #ifdef HAVE_LOGIN_CAP
  1441. shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
  1442. #endif
  1443. /*
  1444. * Close the connection descriptors; note that this is the child, and
  1445. * the server will still have the socket open, and it is important
  1446. * that we do not shutdown it. Note that the descriptors cannot be
  1447. * closed before building the environment, as we call
  1448. * ssh_remote_ipaddr there.
  1449. */
  1450. child_close_fds(ssh);
  1451. /*
  1452. * Must take new environment into use so that .ssh/rc,
  1453. * /etc/ssh/sshrc and xauth are run in the proper environment.
  1454. */
  1455. environ = env;
  1456. #if defined(KRB5) && defined(USE_AFS)
  1457. /*
  1458. * At this point, we check to see if AFS is active and if we have
  1459. * a valid Kerberos 5 TGT. If so, it seems like a good idea to see
  1460. * if we can (and need to) extend the ticket into an AFS token. If
  1461. * we don't do this, we run into potential problems if the user's
  1462. * home directory is in AFS and it's not world-readable.
  1463. */
  1464. if (options.kerberos_get_afs_token && k_hasafs() &&
  1465. (s->authctxt->krb5_ctx != NULL)) {
  1466. char cell[64];
  1467. debug("Getting AFS token");
  1468. k_setpag();
  1469. if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
  1470. krb5_afslog(s->authctxt->krb5_ctx,
  1471. s->authctxt->krb5_fwd_ccache, cell, NULL);
  1472. krb5_afslog_home(s->authctxt->krb5_ctx,
  1473. s->authctxt->krb5_fwd_ccache, NULL, NULL, pw->pw_dir);
  1474. }
  1475. #endif
  1476. /* Change current directory to the user's home directory. */
  1477. if (chdir(pw->pw_dir) == -1) {
  1478. /* Suppress missing homedir warning for chroot case */
  1479. #ifdef HAVE_LOGIN_CAP
  1480. r = login_getcapbool(lc, "requirehome", 0);
  1481. #endif
  1482. if (r || !in_chroot) {
  1483. fprintf(stderr, "Could not chdir to home "
  1484. "directory %s: %s\n", pw->pw_dir,
  1485. strerror(errno));
  1486. }
  1487. if (r)
  1488. exit(1);
  1489. }
  1490. do_rc_files(ssh, s, shell);
  1491. /* restore SIGPIPE for child */
  1492. ssh_signal(SIGPIPE, SIG_DFL);
  1493. if (s->is_subsystem == SUBSYSTEM_INT_SFTP_ERROR) {
  1494. error("Connection from %s: refusing non-sftp session",
  1495. remote_id);
  1496. printf("This service allows sftp connections only.\n");
  1497. fflush(NULL);
  1498. exit(1);
  1499. } else if (s->is_subsystem == SUBSYSTEM_INT_SFTP) {
  1500. extern int optind, optreset;
  1501. int i;
  1502. char *p, *args;
  1503. setproctitle("%s@%s", s->pw->pw_name, INTERNAL_SFTP_NAME);
  1504. args = xstrdup(command ? command : "sftp-server");
  1505. for (i = 0, (p = strtok(args, " ")); p; (p = strtok(NULL, " ")))
  1506. if (i < ARGV_MAX - 1)
  1507. argv[i++] = p;
  1508. argv[i] = NULL;
  1509. optind = optreset = 1;
  1510. __progname = argv[0];
  1511. exit(sftp_server_main(i, argv, s->pw, have_dev_log));
  1512. }
  1513. fflush(NULL);
  1514. /* Get the last component of the shell name. */
  1515. if ((shell0 = strrchr(shell, '/')) != NULL)
  1516. shell0++;
  1517. else
  1518. shell0 = shell;
  1519. /*
  1520. * If we have no command, execute the shell. In this case, the shell
  1521. * name to be passed in argv[0] is preceded by '-' to indicate that
  1522. * this is a login shell.
  1523. */
  1524. if (!command) {
  1525. char argv0[256];
  1526. /* Start the shell. Set initial character to '-'. */
  1527. argv0[0] = '-';
  1528. if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
  1529. >= sizeof(argv0) - 1) {
  1530. errno = EINVAL;
  1531. perror(shell);
  1532. exit(1);
  1533. }
  1534. /* Execute the shell. */
  1535. argv[0] = argv0;
  1536. argv[1] = NULL;
  1537. execve(shell, argv, env);
  1538. /* Executing the shell failed. */
  1539. perror(shell);
  1540. exit(1);
  1541. }
  1542. /*
  1543. * Execute the command using the user's shell. This uses the -c
  1544. * option to execute the command.
  1545. */
  1546. argv[0] = (char *) shell0;
  1547. argv[1] = "-c";
  1548. argv[2] = (char *) command;
  1549. argv[3] = NULL;
  1550. execve(shell, argv, env);
  1551. perror(shell);
  1552. exit(1);
  1553. }
  1554. void
  1555. session_unused(int id)
  1556. {
  1557. debug3("%s: session id %d unused", __func__, id);
  1558. if (id >= options.max_sessions ||
  1559. id >= sessions_nalloc) {
  1560. fatal("%s: insane session id %d (max %d nalloc %d)",
  1561. __func__, id, options.max_sessions, sessions_nalloc);
  1562. }
  1563. memset(&sessions[id], 0, sizeof(*sessions));
  1564. sessions[id].self = id;
  1565. sessions[id].used = 0;
  1566. sessions[id].chanid = -1;
  1567. sessions[id].ptyfd = -1;
  1568. sessions[id].ttyfd = -1;
  1569. sessions[id].ptymaster = -1;
  1570. sessions[id].x11_chanids = NULL;
  1571. #ifdef SSH_AUDIT_EVENTS
  1572. sessions[id].command_handle = -1;
  1573. #endif
  1574. sessions[id].next_unused = sessions_first_unused;
  1575. sessions_first_unused = id;
  1576. }
  1577. Session *
  1578. session_new(void)
  1579. {
  1580. Session *s, *tmp;
  1581. if (sessions_first_unused == -1) {
  1582. if (sessions_nalloc >= options.max_sessions)
  1583. return NULL;
  1584. debug2("%s: allocate (allocated %d max %d)",
  1585. __func__, sessions_nalloc, options.max_sessions);
  1586. tmp = xrecallocarray(sessions, sessions_nalloc,
  1587. sessions_nalloc + 1, sizeof(*sessions));
  1588. if (tmp == NULL) {
  1589. error("%s: cannot allocate %d sessions",
  1590. __func__, sessions_nalloc + 1);
  1591. return NULL;
  1592. }
  1593. sessions = tmp;
  1594. session_unused(sessions_nalloc++);
  1595. }
  1596. if (sessions_first_unused >= sessions_nalloc ||
  1597. sessions_first_unused < 0) {
  1598. fatal("%s: insane first_unused %d max %d nalloc %d",
  1599. __func__, sessions_first_unused, options.max_sessions,
  1600. sessions_nalloc);
  1601. }
  1602. s = &sessions[sessions_first_unused];
  1603. if (s->used) {
  1604. fatal("%s: session %d already used",
  1605. __func__, sessions_first_unused);
  1606. }
  1607. sessions_first_unused = s->next_unused;
  1608. s->used = 1;
  1609. s->next_unused = -1;
  1610. debug("session_new: session %d", s->self);
  1611. return s;
  1612. }
  1613. static void
  1614. session_dump(void)
  1615. {
  1616. int i;
  1617. for (i = 0; i < sessions_nalloc; i++) {
  1618. Session *s = &sessions[i];
  1619. debug("dump: used %d next_unused %d session %d %p "
  1620. "channel %d pid %ld",
  1621. s->used,
  1622. s->next_unused,
  1623. s->self,
  1624. s,
  1625. s->chanid,
  1626. (long)s->pid);
  1627. }
  1628. }
  1629. int
  1630. session_open(Authctxt *authctxt, int chanid)
  1631. {
  1632. Session *s = session_new();
  1633. debug("session_open: channel %d", chanid);
  1634. if (s == NULL) {
  1635. error("no more sessions");
  1636. return 0;
  1637. }
  1638. s->authctxt = authctxt;
  1639. s->pw = authctxt->pw;
  1640. if (s->pw == NULL || !authctxt->valid)
  1641. fatal("no user for session %d", s->self);
  1642. debug("session_open: session %d: link with channel %d", s->self, chanid);
  1643. s->chanid = chanid;
  1644. return 1;
  1645. }
  1646. Session *
  1647. session_by_id(int id)
  1648. {
  1649. if (id >= 0 && id < sessions_nalloc) {
  1650. Session *s = &sessions[id];
  1651. if (s->used)
  1652. return s;
  1653. }
  1654. debug("%s: unknown id %d", __func__, id);
  1655. session_dump();
  1656. return NULL;
  1657. }
  1658. Session *
  1659. session_by_tty(char *tty)
  1660. {
  1661. int i;
  1662. for (i = 0; i < sessions_nalloc; i++) {
  1663. Session *s = &sessions[i];
  1664. if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
  1665. debug("session_by_tty: session %d tty %s", i, tty);
  1666. return s;
  1667. }
  1668. }
  1669. debug("session_by_tty: unknown tty %.100s", tty);
  1670. session_dump();
  1671. return NULL;
  1672. }
  1673. static Session *
  1674. session_by_channel(int id)
  1675. {
  1676. int i;
  1677. for (i = 0; i < sessions_nalloc; i++) {
  1678. Session *s = &sessions[i];
  1679. if (s->used && s->chanid == id) {
  1680. debug("session_by_channel: session %d channel %d",
  1681. i, id);
  1682. return s;
  1683. }
  1684. }
  1685. debug("session_by_channel: unknown channel %d", id);
  1686. session_dump();
  1687. return NULL;
  1688. }
  1689. static Session *
  1690. session_by_x11_channel(int id)
  1691. {
  1692. int i, j;
  1693. for (i = 0; i < sessions_nalloc; i++) {
  1694. Session *s = &sessions[i];
  1695. if (s->x11_chanids == NULL || !s->used)
  1696. continue;
  1697. for (j = 0; s->x11_chanids[j] != -1; j++) {
  1698. if (s->x11_chanids[j] == id) {
  1699. debug("session_by_x11_channel: session %d "
  1700. "channel %d", s->self, id);
  1701. return s;
  1702. }
  1703. }
  1704. }
  1705. debug("session_by_x11_channel: unknown channel %d", id);
  1706. session_dump();
  1707. return NULL;
  1708. }
  1709. static Session *
  1710. session_by_pid(pid_t pid)
  1711. {
  1712. int i;
  1713. debug("session_by_pid: pid %ld", (long)pid);
  1714. for (i = 0; i < sessions_nalloc; i++) {
  1715. Session *s = &sessions[i];
  1716. if (s->used && s->pid == pid)
  1717. return s;
  1718. }
  1719. error("session_by_pid: unknown pid %ld", (long)pid);
  1720. session_dump();
  1721. return NULL;
  1722. }
  1723. static int
  1724. session_window_change_req(struct ssh *ssh, Session *s)
  1725. {
  1726. int r;
  1727. if ((r = sshpkt_get_u32(ssh, &s->col)) != 0 ||
  1728. (r = sshpkt_get_u32(ssh, &s->row)) != 0 ||
  1729. (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 ||
  1730. (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0 ||
  1731. (r = sshpkt_get_end(ssh)) != 0)
  1732. sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
  1733. pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
  1734. return 1;
  1735. }
  1736. static int
  1737. session_pty_req(struct ssh *ssh, Session *s)
  1738. {
  1739. int r;
  1740. if (!auth_opts->permit_pty_flag || !options.permit_tty) {
  1741. debug("Allocating a pty not permitted for this connection.");
  1742. return 0;
  1743. }
  1744. if (s->ttyfd != -1) {
  1745. ssh_packet_disconnect(ssh, "Protocol error: you already have a pty.");
  1746. return 0;
  1747. }
  1748. if ((r = sshpkt_get_cstring(ssh, &s->term, NULL)) != 0 ||
  1749. (r = sshpkt_get_u32(ssh, &s->col)) != 0 ||
  1750. (r = sshpkt_get_u32(ssh, &s->row)) != 0 ||
  1751. (r = sshpkt_get_u32(ssh, &s->xpixel)) != 0 ||
  1752. (r = sshpkt_get_u32(ssh, &s->ypixel)) != 0)
  1753. sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
  1754. if (strcmp(s->term, "") == 0) {
  1755. free(s->term);
  1756. s->term = NULL;
  1757. }
  1758. /* Allocate a pty and open it. */
  1759. debug("Allocating pty.");
  1760. if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
  1761. sizeof(s->tty)))) {
  1762. free(s->term);
  1763. s->term = NULL;
  1764. s->ptyfd = -1;
  1765. s->ttyfd = -1;
  1766. error("session_pty_req: session %d alloc failed", s->self);
  1767. return 0;
  1768. }
  1769. debug("session_pty_req: session %d alloc %s", s->self, s->tty);
  1770. ssh_tty_parse_modes(ssh, s->ttyfd);
  1771. if ((r = sshpkt_get_end(ssh)) != 0)
  1772. sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
  1773. if (!use_privsep)
  1774. pty_setowner(s->pw, s->tty);
  1775. /* Set window size from the packet. */
  1776. pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
  1777. session_proctitle(s);
  1778. return 1;
  1779. }
  1780. static int
  1781. session_subsystem_req(struct ssh *ssh, Session *s)
  1782. {
  1783. struct stat st;
  1784. int r, success = 0;
  1785. char *prog, *cmd;
  1786. u_int i;
  1787. if ((r = sshpkt_get_cstring(ssh, &s->subsys, NULL)) != 0 ||
  1788. (r = sshpkt_get_end(ssh)) != 0)
  1789. sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
  1790. debug2("subsystem request for %.100s by user %s", s->subsys,
  1791. s->pw->pw_name);
  1792. for (i = 0; i < options.num_subsystems; i++) {
  1793. if (strcmp(s->subsys, options.subsystem_name[i]) == 0) {
  1794. prog = options.subsystem_command[i];
  1795. cmd = options.subsystem_args[i];
  1796. if (strcmp(INTERNAL_SFTP_NAME, prog) == 0) {
  1797. s->is_subsystem = SUBSYSTEM_INT_SFTP;
  1798. debug("subsystem: %s", prog);
  1799. } else {
  1800. if (stat(prog, &st) == -1)
  1801. debug("subsystem: cannot stat %s: %s",
  1802. prog, strerror(errno));
  1803. s->is_subsystem = SUBSYSTEM_EXT;
  1804. debug("subsystem: exec() %s", cmd);
  1805. }
  1806. success = do_exec(ssh, s, cmd) == 0;
  1807. break;
  1808. }
  1809. }
  1810. if (!success)
  1811. logit("subsystem request for %.100s by user %s failed, "
  1812. "subsystem not found", s->subsys, s->pw->pw_name);
  1813. return success;
  1814. }
  1815. static int
  1816. session_x11_req(struct ssh *ssh, Session *s)
  1817. {
  1818. int r, success;
  1819. u_char single_connection = 0;
  1820. if (s->auth_proto != NULL || s->auth_data != NULL) {
  1821. error("session_x11_req: session %d: "
  1822. "x11 forwarding already active", s->self);
  1823. return 0;
  1824. }
  1825. if ((r = sshpkt_get_u8(ssh, &single_connection)) != 0 ||
  1826. (r = sshpkt_get_cstring(ssh, &s->auth_proto, NULL)) != 0 ||
  1827. (r = sshpkt_get_cstring(ssh, &s->auth_data, NULL)) != 0 ||
  1828. (r = sshpkt_get_u32(ssh, &s->screen)) != 0 ||
  1829. (r = sshpkt_get_end(ssh)) != 0)
  1830. sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
  1831. s->single_connection = single_connection;
  1832. if (xauth_valid_string(s->auth_proto) &&
  1833. xauth_valid_string(s->auth_data))
  1834. success = session_setup_x11fwd(ssh, s);
  1835. else {
  1836. success = 0;
  1837. error("Invalid X11 forwarding data");
  1838. }
  1839. if (!success) {
  1840. free(s->auth_proto);
  1841. free(s->auth_data);
  1842. s->auth_proto = NULL;
  1843. s->auth_data = NULL;
  1844. }
  1845. return success;
  1846. }
  1847. static int
  1848. session_shell_req(struct ssh *ssh, Session *s)
  1849. {
  1850. int r;
  1851. if ((r = sshpkt_get_end(ssh)) != 0)
  1852. sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
  1853. return do_exec(ssh, s, NULL) == 0;
  1854. }
  1855. static int
  1856. session_exec_req(struct ssh *ssh, Session *s)
  1857. {
  1858. u_int success;
  1859. int r;
  1860. char *command = NULL;
  1861. if ((r = sshpkt_get_cstring(ssh, &command, NULL)) != 0 ||
  1862. (r = sshpkt_get_end(ssh)) != 0)
  1863. sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
  1864. success = do_exec(ssh, s, command) == 0;
  1865. free(command);
  1866. return success;
  1867. }
  1868. static int
  1869. session_break_req(struct ssh *ssh, Session *s)
  1870. {
  1871. int r;
  1872. if ((r = sshpkt_get_u32(ssh, NULL)) != 0 || /* ignore */
  1873. (r = sshpkt_get_end(ssh)) != 0)
  1874. sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
  1875. if (s->ptymaster == -1 || tcsendbreak(s->ptymaster, 0) == -1)
  1876. return 0;
  1877. return 1;
  1878. }
  1879. static int
  1880. session_env_req(struct ssh *ssh, Session *s)
  1881. {
  1882. char *name, *val;
  1883. u_int i;
  1884. int r;
  1885. if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 ||
  1886. (r = sshpkt_get_cstring(ssh, &val, NULL)) != 0 ||
  1887. (r = sshpkt_get_end(ssh)) != 0)
  1888. sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
  1889. /* Don't set too many environment variables */
  1890. if (s->num_env > 128) {
  1891. debug2("Ignoring env request %s: too many env vars", name);
  1892. goto fail;
  1893. }
  1894. for (i = 0; i < options.num_accept_env; i++) {
  1895. if (match_pattern(name, options.accept_env[i])) {
  1896. debug2("Setting env %d: %s=%s", s->num_env, name, val);
  1897. s->env = xrecallocarray(s->env, s->num_env,
  1898. s->num_env + 1, sizeof(*s->env));
  1899. s->env[s->num_env].name = name;
  1900. s->env[s->num_env].val = val;
  1901. s->num_env++;
  1902. return (1);
  1903. }
  1904. }
  1905. debug2("Ignoring env request %s: disallowed name", name);
  1906. fail:
  1907. free(name);
  1908. free(val);
  1909. return (0);
  1910. }
  1911. /*
  1912. * Conversion of signals from ssh channel request names.
  1913. * Subset of signals from RFC 4254 section 6.10C, with SIGINFO as
  1914. * local extension.
  1915. */
  1916. static int
  1917. name2sig(char *name)
  1918. {
  1919. #define SSH_SIG(x) if (strcmp(name, #x) == 0) return SIG ## x
  1920. SSH_SIG(HUP);
  1921. SSH_SIG(INT);
  1922. SSH_SIG(KILL);
  1923. SSH_SIG(QUIT);
  1924. SSH_SIG(TERM);
  1925. SSH_SIG(USR1);
  1926. SSH_SIG(USR2);
  1927. #undef SSH_SIG
  1928. #ifdef SIGINFO
  1929. if (strcmp(name, "INFO@openssh.com") == 0)
  1930. return SIGINFO;
  1931. #endif
  1932. return -1;
  1933. }
  1934. static int
  1935. session_signal_req(struct ssh *ssh, Session *s)
  1936. {
  1937. char *signame = NULL;
  1938. int r, sig, success = 0;
  1939. if ((r = sshpkt_get_cstring(ssh, &signame, NULL)) != 0 ||
  1940. (r = sshpkt_get_end(ssh)) != 0) {
  1941. error("%s: parse packet: %s", __func__, ssh_err(r));
  1942. goto out;
  1943. }
  1944. if ((sig = name2sig(signame)) == -1) {
  1945. error("%s: unsupported signal \"%s\"", __func__, signame);
  1946. goto out;
  1947. }
  1948. if (s->pid <= 0) {
  1949. error("%s: no pid for session %d", __func__, s->self);
  1950. goto out;
  1951. }
  1952. if (s->forced || s->is_subsystem) {
  1953. error("%s: refusing to send signal %s to %s session", __func__,
  1954. signame, s->forced ? "forced-command" : "subsystem");
  1955. goto out;
  1956. }
  1957. if (!use_privsep || mm_is_monitor()) {
  1958. error("%s: session signalling requires privilege separation",
  1959. __func__);
  1960. goto out;
  1961. }
  1962. debug("%s: signal %s, killpg(%ld, %d)", __func__, signame,
  1963. (long)s->pid, sig);
  1964. temporarily_use_uid(s->pw);
  1965. r = killpg(s->pid, sig);
  1966. restore_uid();
  1967. if (r != 0) {
  1968. error("%s: killpg(%ld, %d): %s", __func__, (long)s->pid,
  1969. sig, strerror(errno));
  1970. goto out;
  1971. }
  1972. /* success */
  1973. success = 1;
  1974. out:
  1975. free(signame);
  1976. return success;
  1977. }
  1978. static int
  1979. session_auth_agent_req(struct ssh *ssh, Session *s)
  1980. {
  1981. static int called = 0;
  1982. int r;
  1983. if ((r = sshpkt_get_end(ssh)) != 0)
  1984. sshpkt_fatal(ssh, r, "%s: parse packet", __func__);
  1985. if (!auth_opts->permit_agent_forwarding_flag ||
  1986. !options.allow_agent_forwarding) {
  1987. debug("%s: agent forwarding disabled", __func__);
  1988. return 0;
  1989. }
  1990. if (called) {
  1991. return 0;
  1992. } else {
  1993. called = 1;
  1994. return auth_input_request_forwarding(ssh, s->pw);
  1995. }
  1996. }
  1997. int
  1998. session_input_channel_req(struct ssh *ssh, Channel *c, const char *rtype)
  1999. {
  2000. int success = 0;
  2001. Session *s;
  2002. if ((s = session_by_channel(c->self)) == NULL) {
  2003. logit("%s: no session %d req %.100s", __func__, c->self, rtype);
  2004. return 0;
  2005. }
  2006. debug("%s: session %d req %s", __func__, s->self, rtype);
  2007. /*
  2008. * a session is in LARVAL state until a shell, a command
  2009. * or a subsystem is executed
  2010. */
  2011. if (c->type == SSH_CHANNEL_LARVAL) {
  2012. if (strcmp(rtype, "shell") == 0) {
  2013. success = session_shell_req(ssh, s);
  2014. } else if (strcmp(rtype, "exec") == 0) {
  2015. success = session_exec_req(ssh, s);
  2016. } else if (strcmp(rtype, "pty-req") == 0) {
  2017. success = session_pty_req(ssh, s);
  2018. } else if (strcmp(rtype, "x11-req") == 0) {
  2019. success = session_x11_req(ssh, s);
  2020. } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
  2021. success = session_auth_agent_req(ssh, s);
  2022. } else if (strcmp(rtype, "subsystem") == 0) {
  2023. success = session_subsystem_req(ssh, s);
  2024. } else if (strcmp(rtype, "env") == 0) {
  2025. success = session_env_req(ssh, s);
  2026. }
  2027. }
  2028. if (strcmp(rtype, "window-change") == 0) {
  2029. success = session_window_change_req(ssh, s);
  2030. } else if (strcmp(rtype, "break") == 0) {
  2031. success = session_break_req(ssh, s);
  2032. } else if (strcmp(rtype, "signal") == 0) {
  2033. success = session_signal_req(ssh, s);
  2034. }
  2035. return success;
  2036. }
  2037. void
  2038. session_set_fds(struct ssh *ssh, Session *s,
  2039. int fdin, int fdout, int fderr, int ignore_fderr, int is_tty)
  2040. {
  2041. /*
  2042. * now that have a child and a pipe to the child,
  2043. * we can activate our channel and register the fd's
  2044. */
  2045. if (s->chanid == -1)
  2046. fatal("no channel for session %d", s->self);
  2047. channel_set_fds(ssh, s->chanid,
  2048. fdout, fdin, fderr,
  2049. ignore_fderr ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
  2050. 1, is_tty,
  2051. options.hpn_disabled ? CHAN_SES_WINDOW_DEFAULT : options.hpn_buffer_size);
  2052. }
  2053. /*
  2054. * Function to perform pty cleanup. Also called if we get aborted abnormally
  2055. * (e.g., due to a dropped connection).
  2056. */
  2057. void
  2058. session_pty_cleanup2(Session *s)
  2059. {
  2060. if (s == NULL) {
  2061. error("%s: no session", __func__);
  2062. return;
  2063. }
  2064. if (s->ttyfd == -1)
  2065. return;
  2066. debug("%s: session %d release %s", __func__, s->self, s->tty);
  2067. /* Record that the user has logged out. */
  2068. if (s->pid != 0)
  2069. record_logout(s->pid, s->tty, s->pw->pw_name);
  2070. /* Release the pseudo-tty. */
  2071. if (getuid() == 0)
  2072. pty_release(s->tty);
  2073. /*
  2074. * Close the server side of the socket pairs. We must do this after
  2075. * the pty cleanup, so that another process doesn't get this pty
  2076. * while we're still cleaning up.
  2077. */
  2078. if (s->ptymaster != -1 && close(s->ptymaster) == -1)
  2079. error("close(s->ptymaster/%d): %s",
  2080. s->ptymaster, strerror(errno));
  2081. /* unlink pty from session */
  2082. s->ttyfd = -1;
  2083. }
  2084. void
  2085. session_pty_cleanup(Session *s)
  2086. {
  2087. PRIVSEP(session_pty_cleanup2(s));
  2088. }
  2089. static char *
  2090. sig2name(int sig)
  2091. {
  2092. #define SSH_SIG(x) if (sig == SIG ## x) return #x
  2093. SSH_SIG(ABRT);
  2094. SSH_SIG(ALRM);
  2095. SSH_SIG(FPE);
  2096. SSH_SIG(HUP);
  2097. SSH_SIG(ILL);
  2098. SSH_SIG(INT);
  2099. SSH_SIG(KILL);
  2100. SSH_SIG(PIPE);
  2101. SSH_SIG(QUIT);
  2102. SSH_SIG(SEGV);
  2103. SSH_SIG(TERM);
  2104. SSH_SIG(USR1);
  2105. SSH_SIG(USR2);
  2106. #undef SSH_SIG
  2107. return "SIG@openssh.com";
  2108. }
  2109. static void
  2110. session_close_x11(struct ssh *ssh, int id)
  2111. {
  2112. Channel *c;
  2113. if ((c = channel_by_id(ssh, id)) == NULL) {
  2114. debug("%s: x11 channel %d missing", __func__, id);
  2115. } else {
  2116. /* Detach X11 listener */
  2117. debug("%s: detach x11 channel %d", __func__, id);
  2118. channel_cancel_cleanup(ssh, id);
  2119. if (c->ostate != CHAN_OUTPUT_CLOSED)
  2120. chan_mark_dead(ssh, c);
  2121. }
  2122. }
  2123. static void
  2124. session_close_single_x11(struct ssh *ssh, int id, void *arg)
  2125. {
  2126. Session *s;
  2127. u_int i;
  2128. debug3("%s: channel %d", __func__, id);
  2129. channel_cancel_cleanup(ssh, id);
  2130. if ((s = session_by_x11_channel(id)) == NULL)
  2131. fatal("%s: no x11 channel %d", __func__, id);
  2132. for (i = 0; s->x11_chanids[i] != -1; i++) {
  2133. debug("%s: session %d: closing channel %d",
  2134. __func__, s->self, s->x11_chanids[i]);
  2135. /*
  2136. * The channel "id" is already closing, but make sure we
  2137. * close all of its siblings.
  2138. */
  2139. if (s->x11_chanids[i] != id)
  2140. session_close_x11(ssh, s->x11_chanids[i]);
  2141. }
  2142. free(s->x11_chanids);
  2143. s->x11_chanids = NULL;
  2144. free(s->display);
  2145. s->display = NULL;
  2146. free(s->auth_proto);
  2147. s->auth_proto = NULL;
  2148. free(s->auth_data);
  2149. s->auth_data = NULL;
  2150. free(s->auth_display);
  2151. s->auth_display = NULL;
  2152. }
  2153. static void
  2154. session_exit_message(struct ssh *ssh, Session *s, int status)
  2155. {
  2156. Channel *c;
  2157. int r;
  2158. if ((c = channel_lookup(ssh, s->chanid)) == NULL)
  2159. fatal("%s: session %d: no channel %d",
  2160. __func__, s->self, s->chanid);
  2161. debug("%s: session %d channel %d pid %ld",
  2162. __func__, s->self, s->chanid, (long)s->pid);
  2163. if (WIFEXITED(status)) {
  2164. channel_request_start(ssh, s->chanid, "exit-status", 0);
  2165. if ((r = sshpkt_put_u32(ssh, WEXITSTATUS(status))) != 0 ||
  2166. (r = sshpkt_send(ssh)) != 0)
  2167. sshpkt_fatal(ssh, r, "%s: exit reply", __func__);
  2168. } else if (WIFSIGNALED(status)) {
  2169. channel_request_start(ssh, s->chanid, "exit-signal", 0);
  2170. #ifndef WCOREDUMP
  2171. # define WCOREDUMP(x) (0)
  2172. #endif
  2173. if ((r = sshpkt_put_cstring(ssh, sig2name(WTERMSIG(status)))) != 0 ||
  2174. (r = sshpkt_put_u8(ssh, WCOREDUMP(status)? 1 : 0)) != 0 ||
  2175. (r = sshpkt_put_cstring(ssh, "")) != 0 ||
  2176. (r = sshpkt_put_cstring(ssh, "")) != 0 ||
  2177. (r = sshpkt_send(ssh)) != 0)
  2178. sshpkt_fatal(ssh, r, "%s: exit reply", __func__);
  2179. } else {
  2180. /* Some weird exit cause. Just exit. */
  2181. ssh_packet_disconnect(ssh, "wait returned status %04x.", status);
  2182. }
  2183. /* disconnect channel */
  2184. debug("%s: release channel %d", __func__, s->chanid);
  2185. /*
  2186. * Adjust cleanup callback attachment to send close messages when
  2187. * the channel gets EOF. The session will be then be closed
  2188. * by session_close_by_channel when the child sessions close their fds.
  2189. */
  2190. channel_register_cleanup(ssh, c->self, session_close_by_channel, 1);
  2191. /*
  2192. * emulate a write failure with 'chan_write_failed', nobody will be
  2193. * interested in data we write.
  2194. * Note that we must not call 'chan_read_failed', since there could
  2195. * be some more data waiting in the pipe.
  2196. */
  2197. if (c->ostate != CHAN_OUTPUT_CLOSED)
  2198. chan_write_failed(ssh, c);
  2199. }
  2200. #ifdef SSH_AUDIT_EVENTS
  2201. void
  2202. session_end_command2(struct ssh *ssh, Session *s)
  2203. {
  2204. if (s->command != NULL) {
  2205. if (s->command_handle != -1)
  2206. audit_end_command(ssh, s->command_handle, s->command);
  2207. free(s->command);
  2208. s->command = NULL;
  2209. s->command_handle = -1;
  2210. }
  2211. }
  2212. static void
  2213. session_end_command(struct ssh *ssh, Session *s)
  2214. {
  2215. if (s->command != NULL) {
  2216. if (s->command_handle != -1)
  2217. PRIVSEP(audit_end_command(ssh, s->command_handle, s->command));
  2218. free(s->command);
  2219. s->command = NULL;
  2220. s->command_handle = -1;
  2221. }
  2222. }
  2223. #endif
  2224. void
  2225. session_close(struct ssh *ssh, Session *s)
  2226. {
  2227. u_int i;
  2228. int do_xauth;
  2229. verbose("Close session: user %s from %.200s port %d id %d",
  2230. s->pw->pw_name,
  2231. ssh_remote_ipaddr(ssh),
  2232. ssh_remote_port(ssh),
  2233. s->self);
  2234. do_xauth = s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
  2235. if (do_xauth && options.xauth_location != NULL) {
  2236. pid_t pid;
  2237. FILE *f;
  2238. char cmd[1024];
  2239. struct passwd * pw = s->pw;
  2240. if (!(pid = fork())) {
  2241. permanently_set_uid(pw);
  2242. /* Remove authority data from .Xauthority if appropriate. */
  2243. debug("Running %.500s remove %.100s\n",
  2244. options.xauth_location, s->auth_display);
  2245. snprintf(cmd, sizeof cmd, "unset XAUTHORITY && HOME=\"%.200s\" %s -q -",
  2246. s->pw->pw_dir, options.xauth_location);
  2247. f = popen(cmd, "w");
  2248. if (f) {
  2249. fprintf(f, "remove %s\n", s->auth_display);
  2250. pclose(f);
  2251. } else
  2252. error("Could not run %s\n", cmd);
  2253. exit(0);
  2254. } else if (pid > 0) {
  2255. int status;
  2256. waitpid(pid, &status, 0);
  2257. }
  2258. }
  2259. if (s->ttyfd != -1)
  2260. session_pty_cleanup(s);
  2261. #ifdef SSH_AUDIT_EVENTS
  2262. if (s->command)
  2263. session_end_command(ssh, s);
  2264. #endif
  2265. free(s->term);
  2266. free(s->display);
  2267. free(s->x11_chanids);
  2268. free(s->auth_display);
  2269. free(s->auth_data);
  2270. free(s->auth_proto);
  2271. free(s->subsys);
  2272. if (s->env != NULL) {
  2273. for (i = 0; i < s->num_env; i++) {
  2274. free(s->env[i].name);
  2275. free(s->env[i].val);
  2276. }
  2277. free(s->env);
  2278. }
  2279. session_proctitle(s);
  2280. session_unused(s->self);
  2281. }
  2282. void
  2283. session_close_by_pid(struct ssh *ssh, pid_t pid, int status)
  2284. {
  2285. Session *s = session_by_pid(pid);
  2286. if (s == NULL) {
  2287. debug("%s: no session for pid %ld", __func__, (long)pid);
  2288. return;
  2289. }
  2290. if (s->chanid != -1)
  2291. session_exit_message(ssh, s, status);
  2292. if (s->ttyfd != -1)
  2293. session_pty_cleanup(s);
  2294. s->pid = 0;
  2295. }
  2296. /*
  2297. * this is called when a channel dies before
  2298. * the session 'child' itself dies
  2299. */
  2300. void
  2301. session_close_by_channel(struct ssh *ssh, int id, void *arg)
  2302. {
  2303. Session *s = session_by_channel(id);
  2304. u_int i;
  2305. if (s == NULL) {
  2306. debug("%s: no session for id %d", __func__, id);
  2307. return;
  2308. }
  2309. debug("%s: channel %d child %ld", __func__, id, (long)s->pid);
  2310. if (s->pid != 0) {
  2311. debug("%s: channel %d: has child, ttyfd %d",
  2312. __func__, id, s->ttyfd);
  2313. /*
  2314. * delay detach of session, but release pty, since
  2315. * the fd's to the child are already closed
  2316. */
  2317. if (s->ttyfd != -1)
  2318. session_pty_cleanup(s);
  2319. return;
  2320. }
  2321. /* detach by removing callback */
  2322. channel_cancel_cleanup(ssh, s->chanid);
  2323. /* Close any X11 listeners associated with this session */
  2324. if (s->x11_chanids != NULL) {
  2325. for (i = 0; s->x11_chanids[i] != -1; i++) {
  2326. session_close_x11(ssh, s->x11_chanids[i]);
  2327. s->x11_chanids[i] = -1;
  2328. }
  2329. }
  2330. s->chanid = -1;
  2331. session_close(ssh, s);
  2332. }
  2333. void
  2334. session_destroy_all(struct ssh *ssh, void (*closefunc)(struct ssh *ssh, Session *))
  2335. {
  2336. int i;
  2337. for (i = 0; i < sessions_nalloc; i++) {
  2338. Session *s = &sessions[i];
  2339. if (s->used) {
  2340. if (closefunc != NULL)
  2341. closefunc(ssh, s);
  2342. else
  2343. session_close(ssh, s);
  2344. }
  2345. }
  2346. }
  2347. static char *
  2348. session_tty_list(void)
  2349. {
  2350. static char buf[1024];
  2351. int i;
  2352. char *cp;
  2353. buf[0] = '\0';
  2354. for (i = 0; i < sessions_nalloc; i++) {
  2355. Session *s = &sessions[i];
  2356. if (s->used && s->ttyfd != -1) {
  2357. if (strncmp(s->tty, "/dev/", 5) != 0) {
  2358. cp = strrchr(s->tty, '/');
  2359. cp = (cp == NULL) ? s->tty : cp + 1;
  2360. } else
  2361. cp = s->tty + 5;
  2362. if (buf[0] != '\0')
  2363. strlcat(buf, ",", sizeof buf);
  2364. strlcat(buf, cp, sizeof buf);
  2365. }
  2366. }
  2367. if (buf[0] == '\0')
  2368. strlcpy(buf, "notty", sizeof buf);
  2369. return buf;
  2370. }
  2371. void
  2372. session_proctitle(Session *s)
  2373. {
  2374. if (s->pw == NULL)
  2375. error("no user for session %d", s->self);
  2376. else
  2377. setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
  2378. }
  2379. int
  2380. session_setup_x11fwd(struct ssh *ssh, Session *s)
  2381. {
  2382. struct stat st;
  2383. char display[512], auth_display[512];
  2384. char hostname[NI_MAXHOST];
  2385. u_int i;
  2386. if (!auth_opts->permit_x11_forwarding_flag) {
  2387. ssh_packet_send_debug(ssh, "X11 forwarding disabled by key options.");
  2388. return 0;
  2389. }
  2390. if (!options.x11_forwarding) {
  2391. debug("X11 forwarding disabled in server configuration file.");
  2392. return 0;
  2393. }
  2394. if (options.xauth_location == NULL ||
  2395. (stat(options.xauth_location, &st) == -1)) {
  2396. ssh_packet_send_debug(ssh, "No xauth program; cannot forward X11.");
  2397. return 0;
  2398. }
  2399. if (s->display != NULL) {
  2400. debug("X11 display already set.");
  2401. return 0;
  2402. }
  2403. if (x11_create_display_inet(ssh, options.x11_display_offset,
  2404. options.x11_use_localhost, s->single_connection,
  2405. &s->display_number, &s->x11_chanids) == -1) {
  2406. debug("x11_create_display_inet failed.");
  2407. return 0;
  2408. }
  2409. for (i = 0; s->x11_chanids[i] != -1; i++) {
  2410. channel_register_cleanup(ssh, s->x11_chanids[i],
  2411. session_close_single_x11, 0);
  2412. }
  2413. /* Set up a suitable value for the DISPLAY variable. */
  2414. if (gethostname(hostname, sizeof(hostname)) == -1)
  2415. fatal("gethostname: %.100s", strerror(errno));
  2416. /*
  2417. * auth_display must be used as the displayname when the
  2418. * authorization entry is added with xauth(1). This will be
  2419. * different than the DISPLAY string for localhost displays.
  2420. */
  2421. if (options.x11_use_localhost) {
  2422. snprintf(display, sizeof display, "localhost:%u.%u",
  2423. s->display_number, s->screen);
  2424. snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
  2425. s->display_number, s->screen);
  2426. s->display = xstrdup(display);
  2427. s->auth_display = xstrdup(auth_display);
  2428. } else {
  2429. #ifdef IPADDR_IN_DISPLAY
  2430. struct hostent *he;
  2431. struct in_addr my_addr;
  2432. he = gethostbyname(hostname);
  2433. if (he == NULL) {
  2434. error("Can't get IP address for X11 DISPLAY.");
  2435. ssh_packet_send_debug(ssh, "Can't get IP address for X11 DISPLAY.");
  2436. return 0;
  2437. }
  2438. memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
  2439. snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
  2440. s->display_number, s->screen);
  2441. #else
  2442. snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
  2443. s->display_number, s->screen);
  2444. #endif
  2445. s->display = xstrdup(display);
  2446. s->auth_display = xstrdup(display);
  2447. }
  2448. return 1;
  2449. }
  2450. static void
  2451. do_authenticated2(struct ssh *ssh, Authctxt *authctxt)
  2452. {
  2453. server_loop2(ssh, authctxt);
  2454. }
  2455. static void
  2456. do_cleanup_one_session(struct ssh *ssh, Session *s)
  2457. {
  2458. session_pty_cleanup2(s);
  2459. #ifdef SSH_AUDIT_EVENTS
  2460. session_end_command2(ssh, s);
  2461. #endif
  2462. }
  2463. void
  2464. do_cleanup(struct ssh *ssh, Authctxt *authctxt)
  2465. {
  2466. static int called = 0;
  2467. debug("do_cleanup");
  2468. /* no cleanup if we're in the child for login shell */
  2469. if (is_child)
  2470. return;
  2471. /* avoid double cleanup */
  2472. if (called)
  2473. return;
  2474. called = 1;
  2475. if (authctxt == NULL)
  2476. return;
  2477. #ifdef USE_PAM
  2478. if (options.use_pam) {
  2479. sshpam_cleanup();
  2480. sshpam_thread_cleanup();
  2481. }
  2482. #endif
  2483. if (!authctxt->authenticated)
  2484. return;
  2485. #ifdef KRB5
  2486. if (options.kerberos_ticket_cleanup &&
  2487. authctxt->krb5_ctx)
  2488. krb5_cleanup_proc(authctxt);
  2489. #endif
  2490. #ifdef GSSAPI
  2491. if (options.gss_cleanup_creds)
  2492. ssh_gssapi_cleanup_creds();
  2493. #endif
  2494. /* remove agent socket */
  2495. auth_sock_cleanup_proc(authctxt->pw);
  2496. /* remove userauth info */
  2497. if (auth_info_file != NULL) {
  2498. temporarily_use_uid(authctxt->pw);
  2499. unlink(auth_info_file);
  2500. restore_uid();
  2501. free(auth_info_file);
  2502. auth_info_file = NULL;
  2503. }
  2504. /*
  2505. * Cleanup ptys/utmp only if privsep is disabled,
  2506. * or if running in monitor.
  2507. */
  2508. if (!use_privsep || mm_is_monitor())
  2509. session_destroy_all(ssh, do_cleanup_one_session);
  2510. }
  2511. /* Return a name for the remote host that fits inside utmp_size */
  2512. const char *
  2513. session_get_remote_name_or_ip(struct ssh *ssh, u_int utmp_size, int use_dns)
  2514. {
  2515. const char *remote = "";
  2516. if (utmp_size > 0)
  2517. remote = auth_get_canonical_hostname(ssh, use_dns);
  2518. if (utmp_size == 0 || strlen(remote) > utmp_size)
  2519. remote = ssh_remote_ipaddr(ssh);
  2520. return remote;
  2521. }