]> andersk Git - openssh.git/blame - session.c
- markus@cvs.openbsd.org 2003/12/02 17:01:15
[openssh.git] / session.c
CommitLineData
7368a6c8 1/*
2 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
3 * All rights reserved
bcbf86ec 4 *
5 * As far as I am concerned, the code I have written for this software
6 * can be used freely for any purpose. Any derived versions of this
7 * software must be clearly marked as such, and if the derived work is
8 * incompatible with the protocol description in the RFC file, it must be
9 * called by a name other than "ssh" or "Secure Shell".
10 *
e78a59f5 11 * SSH2 support by Markus Friedl.
a96070d4 12 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
bcbf86ec 13 *
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
16 * are met:
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
e78a59f5 33 */
7368a6c8 34
35#include "includes.h"
fce39749 36RCSID("$OpenBSD: session.c,v 1.169 2003/12/02 17:01:15 markus Exp $");
7368a6c8 37
7368a6c8 38#include "ssh.h"
42f11eb2 39#include "ssh1.h"
40#include "ssh2.h"
41#include "xmalloc.h"
1729c161 42#include "sshpty.h"
7368a6c8 43#include "packet.h"
44#include "buffer.h"
7368a6c8 45#include "mpaux.h"
7368a6c8 46#include "uidswap.h"
47#include "compat.h"
a5efa1bb 48#include "channels.h"
e78a59f5 49#include "bufaux.h"
e78a59f5 50#include "auth.h"
38c295d6 51#include "auth-options.h"
42f11eb2 52#include "pathnames.h"
53#include "log.h"
54#include "servconf.h"
1729c161 55#include "sshlogin.h"
42f11eb2 56#include "serverloop.h"
57#include "canohost.h"
5ca51e19 58#include "session.h"
1853d1ef 59#include "monitor_wrap.h"
e78a59f5 60
7364bd04 61#ifdef GSSAPI
62#include "ssh-gss.h"
63#endif
64
7368a6c8 65/* func */
66
67Session *session_new(void);
9c328529 68void session_set_fds(Session *, int, int, int);
2362db19 69void session_pty_cleanup(Session *);
9c328529 70void session_proctitle(Session *);
71int session_setup_x11fwd(Session *);
72void do_exec_pty(Session *, const char *);
73void do_exec_no_pty(Session *, const char *);
74void do_exec(Session *, const char *);
75void do_login(Session *, const char *);
8a9ac95d 76#ifdef LOGIN_NEEDS_UTMPX
77static void do_pre_login(Session *s);
78#endif
9c328529 79void do_child(Session *, const char *);
f2c2fd71 80void do_motd(void);
9c328529 81int check_quietlogin(Session *, const char *);
7368a6c8 82
396c147e 83static void do_authenticated1(Authctxt *);
84static void do_authenticated2(Authctxt *);
9c328529 85
396c147e 86static int session_pty_req(Session *);
bb5639fe 87
7368a6c8 88/* import */
89extern ServerOptions options;
90extern char *__progname;
91extern int log_stderr;
92extern int debug_flag;
1e3b8b07 93extern u_int utmp_len;
089fbbd2 94extern int startup_pipe;
e78e738a 95extern void destroy_sensitive_data(void);
bc7dfc06 96extern Buffer loginmsg;
089fbbd2 97
b5e300c2 98/* original command from peer. */
c95add71 99const char *original_command = NULL;
b5e300c2 100
7368a6c8 101/* data */
102#define MAX_SESSIONS 10
103Session sessions[MAX_SESSIONS];
c5d85828 104
2e73a022 105#ifdef HAVE_LOGIN_CAP
1836f69f 106login_cap_t *lc;
2e73a022 107#endif
108
2362db19 109static int is_child = 0;
110
149cdb60 111/* Name and directory of socket for authentication agent forwarding. */
112static char *auth_sock_name = NULL;
113static char *auth_sock_dir = NULL;
114
115/* removes the agent forwarding socket */
116
117static void
2362db19 118auth_sock_cleanup_proc(struct passwd *pw)
149cdb60 119{
149cdb60 120 if (auth_sock_name != NULL) {
121 temporarily_use_uid(pw);
122 unlink(auth_sock_name);
123 rmdir(auth_sock_dir);
124 auth_sock_name = NULL;
125 restore_uid();
126 }
127}
128
129static int
130auth_input_request_forwarding(struct passwd * pw)
131{
132 Channel *nc;
133 int sock;
134 struct sockaddr_un sunaddr;
135
136 if (auth_sock_name != NULL) {
137 error("authentication forwarding requested twice.");
138 return 0;
139 }
140
141 /* Temporarily drop privileged uid for mkdir/bind. */
142 temporarily_use_uid(pw);
143
144 /* Allocate a buffer for the socket name, and format the name. */
145 auth_sock_name = xmalloc(MAXPATHLEN);
146 auth_sock_dir = xmalloc(MAXPATHLEN);
c88de854 147 strlcpy(auth_sock_dir, "/tmp/ssh-XXXXXXXXXX", MAXPATHLEN);
149cdb60 148
149 /* Create private directory for socket */
150 if (mkdtemp(auth_sock_dir) == NULL) {
151 packet_send_debug("Agent forwarding disabled: "
152 "mkdtemp() failed: %.100s", strerror(errno));
153 restore_uid();
154 xfree(auth_sock_name);
155 xfree(auth_sock_dir);
156 auth_sock_name = NULL;
157 auth_sock_dir = NULL;
158 return 0;
159 }
c457707e 160 snprintf(auth_sock_name, MAXPATHLEN, "%s/agent.%ld",
161 auth_sock_dir, (long) getpid());
149cdb60 162
149cdb60 163 /* Create the socket. */
164 sock = socket(AF_UNIX, SOCK_STREAM, 0);
165 if (sock < 0)
166 packet_disconnect("socket: %.100s", strerror(errno));
167
168 /* Bind it to the name. */
169 memset(&sunaddr, 0, sizeof(sunaddr));
170 sunaddr.sun_family = AF_UNIX;
171 strlcpy(sunaddr.sun_path, auth_sock_name, sizeof(sunaddr.sun_path));
172
173 if (bind(sock, (struct sockaddr *) & sunaddr, sizeof(sunaddr)) < 0)
174 packet_disconnect("bind: %.100s", strerror(errno));
175
176 /* Restore the privileged uid. */
177 restore_uid();
178
179 /* Start listening on the socket. */
fce39749 180 if (listen(sock, SSH_LISTEN_BACKLOG) < 0)
149cdb60 181 packet_disconnect("listen: %.100s", strerror(errno));
182
183 /* Allocate a channel for the authentication agent socket. */
184 nc = channel_new("auth socket",
185 SSH_CHANNEL_AUTH_SOCKET, sock, sock, -1,
186 CHAN_X11_WINDOW_DEFAULT, CHAN_X11_PACKET_DEFAULT,
0d942eff 187 0, "auth socket", 1);
149cdb60 188 strlcpy(nc->path, auth_sock_name, sizeof(nc->path));
189 return 1;
190}
191
192
bb5639fe 193void
194do_authenticated(Authctxt *authctxt)
195{
381b021b 196 setproctitle("%s", authctxt->pw->pw_name);
197
bb5639fe 198 /*
199 * Cancel the alarm we set to limit the time taken for
200 * authentication.
201 */
202 alarm(0);
203 if (startup_pipe != -1) {
204 close(startup_pipe);
205 startup_pipe = -1;
206 }
bb5639fe 207 /* setup the channel layer */
208 if (!no_port_forwarding_flag && options.allow_tcp_forwarding)
209 channel_permit_all_opens();
210
211 if (compat20)
212 do_authenticated2(authctxt);
213 else
214 do_authenticated1(authctxt);
e4f7282d 215
2362db19 216 do_cleanup(authctxt);
bb5639fe 217}
218
7368a6c8 219/*
220 * Prepares for an interactive session. This is called after the user has
221 * been successfully authenticated. During this message exchange, pseudo
222 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
223 * are requested, etc.
224 */
396c147e 225static void
bb5639fe 226do_authenticated1(Authctxt *authctxt)
7368a6c8 227{
228 Session *s;
7368a6c8 229 char *command;
54a5250f 230 int success, type, screen_flag;
7138ebd9 231 int enable_compression_after_reply = 0;
232 u_int proto_len, data_len, dlen, compression_level = 0;
7368a6c8 233
234 s = session_new();
ced49be2 235 s->authctxt = authctxt;
bb5639fe 236 s->pw = authctxt->pw;
2e73a022 237
7368a6c8 238 /*
239 * We stay in this loop until the client requests to execute a shell
240 * or a command.
241 */
242 for (;;) {
bb5639fe 243 success = 0;
7368a6c8 244
245 /* Get a packet from the client. */
54a5250f 246 type = packet_read();
7368a6c8 247
248 /* Process the packet. */
249 switch (type) {
250 case SSH_CMSG_REQUEST_COMPRESSION:
7368a6c8 251 compression_level = packet_get_int();
95500969 252 packet_check_eom();
7368a6c8 253 if (compression_level < 1 || compression_level > 9) {
254 packet_send_debug("Received illegal compression level %d.",
184eed6a 255 compression_level);
7368a6c8 256 break;
257 }
636f76ca 258 if (!options.compression) {
259 debug2("compression disabled");
260 break;
261 }
7368a6c8 262 /* Enable compression after we have responded with SUCCESS. */
263 enable_compression_after_reply = 1;
264 success = 1;
265 break;
266
267 case SSH_CMSG_REQUEST_PTY:
653d5f86 268 success = session_pty_req(s);
7368a6c8 269 break;
270
271 case SSH_CMSG_X11_REQUEST_FORWARDING:
7368a6c8 272 s->auth_proto = packet_get_string(&proto_len);
273 s->auth_data = packet_get_string(&data_len);
7368a6c8 274
2af09193 275 screen_flag = packet_get_protocol_flags() &
276 SSH_PROTOFLAG_SCREEN_NUMBER;
277 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
278
279 if (packet_remaining() == 4) {
280 if (!screen_flag)
281 debug2("Buggy client: "
282 "X11 screen flag missing");
7368a6c8 283 s->screen = packet_get_int();
c8b058b4 284 } else {
7368a6c8 285 s->screen = 0;
c8b058b4 286 }
95500969 287 packet_check_eom();
8dcd9d5c 288 success = session_setup_x11fwd(s);
289 if (!success) {
290 xfree(s->auth_proto);
291 xfree(s->auth_data);
1500bcdd 292 s->auth_proto = NULL;
293 s->auth_data = NULL;
7368a6c8 294 }
7368a6c8 295 break;
7368a6c8 296
297 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
298 if (no_agent_forwarding_flag || compat13) {
299 debug("Authentication agent forwarding not permitted for this authentication.");
300 break;
301 }
302 debug("Received authentication agent forwarding request.");
bb5639fe 303 success = auth_input_request_forwarding(s->pw);
7368a6c8 304 break;
305
306 case SSH_CMSG_PORT_FORWARD_REQUEST:
307 if (no_port_forwarding_flag) {
308 debug("Port forwarding not permitted for this authentication.");
309 break;
310 }
33de75a3 311 if (!options.allow_tcp_forwarding) {
312 debug("Port forwarding not permitted.");
313 break;
314 }
7368a6c8 315 debug("Received TCP/IP port forwarding request.");
bb5639fe 316 channel_input_port_forward_request(s->pw->pw_uid == 0, options.gateway_ports);
7368a6c8 317 success = 1;
318 break;
319
320 case SSH_CMSG_MAX_PACKET_SIZE:
321 if (packet_set_maxsize(packet_get_int()) > 0)
322 success = 1;
323 break;
184eed6a 324
7368a6c8 325 case SSH_CMSG_EXEC_SHELL:
326 case SSH_CMSG_EXEC_CMD:
7368a6c8 327 if (type == SSH_CMSG_EXEC_CMD) {
328 command = packet_get_string(&dlen);
329 debug("Exec command '%.500s'", command);
c95add71 330 do_exec(s, command);
331 xfree(command);
7368a6c8 332 } else {
c95add71 333 do_exec(s, NULL);
7368a6c8 334 }
95500969 335 packet_check_eom();
fc2a1d28 336 session_close(s);
7368a6c8 337 return;
338
339 default:
340 /*
341 * Any unknown messages in this phase are ignored,
342 * and a failure message is returned.
343 */
bbe88b6d 344 logit("Unknown packet type received after authentication: %d", type);
7368a6c8 345 }
346 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
347 packet_send();
348 packet_write_wait();
349
350 /* Enable compression now that we have replied if appropriate. */
351 if (enable_compression_after_reply) {
352 enable_compression_after_reply = 0;
353 packet_start_compression(compression_level);
354 }
355 }
356}
357
358/*
359 * This is called to fork and execute a command when we have no tty. This
360 * will call do_child from the child, and server_loop from the parent after
361 * setting up file descriptors and such.
362 */
6ae2364d 363void
65068d16 364do_exec_no_pty(Session *s, const char *command)
7368a6c8 365{
c457707e 366 pid_t pid;
7368a6c8 367
368#ifdef USE_PIPES
369 int pin[2], pout[2], perr[2];
370 /* Allocate pipes for communicating with the program. */
371 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
372 packet_disconnect("Could not create pipes: %.100s",
373 strerror(errno));
374#else /* USE_PIPES */
375 int inout[2], err[2];
376 /* Uses socket pairs to communicate with the program. */
377 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
378 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
379 packet_disconnect("Could not create socket pairs: %.100s",
380 strerror(errno));
381#endif /* USE_PIPES */
382 if (s == NULL)
383 fatal("do_exec_no_pty: no session");
384
1d1ffb87 385 session_proctitle(s);
7368a6c8 386
b19d61d7 387#if defined(USE_PAM)
7fceb20d 388 if (options.use_pam) {
7fceb20d 389 do_pam_setcred(1);
390 if (is_pam_password_change_required())
391 packet_disconnect("Password change required but no "
392 "TTY available");
393 }
266140a8 394#endif /* USE_PAM */
395
7368a6c8 396 /* Fork the child. */
397 if ((pid = fork()) == 0) {
2362db19 398 is_child = 1;
516f0d7d 399
7368a6c8 400 /* Child. Reinitialize the log since the pid has changed. */
401 log_init(__progname, options.log_level, options.log_facility, log_stderr);
402
403 /*
404 * Create a new session and process group since the 4.4BSD
405 * setlogin() affects the entire process group.
406 */
407 if (setsid() < 0)
408 error("setsid failed: %.100s", strerror(errno));
409
410#ifdef USE_PIPES
411 /*
412 * Redirect stdin. We close the parent side of the socket
413 * pair, and make the child side the standard input.
414 */
415 close(pin[1]);
416 if (dup2(pin[0], 0) < 0)
417 perror("dup2 stdin");
418 close(pin[0]);
419
420 /* Redirect stdout. */
421 close(pout[0]);
422 if (dup2(pout[1], 1) < 0)
423 perror("dup2 stdout");
424 close(pout[1]);
425
426 /* Redirect stderr. */
427 close(perr[0]);
428 if (dup2(perr[1], 2) < 0)
429 perror("dup2 stderr");
430 close(perr[1]);
431#else /* USE_PIPES */
432 /*
433 * Redirect stdin, stdout, and stderr. Stdin and stdout will
434 * use the same socket, as some programs (particularly rdist)
435 * seem to depend on it.
436 */
437 close(inout[1]);
438 close(err[1]);
439 if (dup2(inout[0], 0) < 0) /* stdin */
440 perror("dup2 stdin");
441 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
442 perror("dup2 stdout");
443 if (dup2(err[0], 2) < 0) /* stderr */
444 perror("dup2 stderr");
445#endif /* USE_PIPES */
446
ef51930f 447#ifdef _UNICOS
448 cray_init_job(s->pw); /* set up cray jid and tmpdir */
449#endif
450
7368a6c8 451 /* Do processing for the child (exec command etc). */
56b3e9ce 452 do_child(s, command);
7368a6c8 453 /* NOTREACHED */
454 }
ef51930f 455#ifdef _UNICOS
456 signal(WJSIGNAL, cray_job_termination_handler);
457#endif /* _UNICOS */
3c62e7eb 458#ifdef HAVE_CYGWIN
459 if (is_winnt)
460 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
461#endif
7368a6c8 462 if (pid < 0)
463 packet_disconnect("fork failed: %.100s", strerror(errno));
464 s->pid = pid;
b5c334cc 465 /* Set interactive/non-interactive mode. */
466 packet_set_interactive(s->display != NULL);
7368a6c8 467#ifdef USE_PIPES
468 /* We are the parent. Close the child sides of the pipes. */
469 close(pin[0]);
470 close(pout[1]);
471 close(perr[1]);
472
e78a59f5 473 if (compat20) {
e5d7a405 474 session_set_fds(s, pin[1], pout[0], s->is_subsystem ? -1 : perr[0]);
e78a59f5 475 } else {
476 /* Enter the interactive session. */
477 server_loop(pid, pin[1], pout[0], perr[0]);
e5d7a405 478 /* server_loop has closed pin[1], pout[0], and perr[0]. */
e78a59f5 479 }
7368a6c8 480#else /* USE_PIPES */
481 /* We are the parent. Close the child sides of the socket pairs. */
482 close(inout[0]);
483 close(err[0]);
484
485 /*
486 * Enter the interactive session. Note: server_loop must be able to
487 * handle the case that fdin and fdout are the same.
488 */
e78a59f5 489 if (compat20) {
e5d7a405 490 session_set_fds(s, inout[1], inout[1], s->is_subsystem ? -1 : err[1]);
e78a59f5 491 } else {
492 server_loop(pid, inout[1], inout[1], err[1]);
493 /* server_loop has closed inout[1] and err[1]. */
494 }
7368a6c8 495#endif /* USE_PIPES */
496}
497
498/*
499 * This is called to fork and execute a command when we have a tty. This
500 * will call do_child from the child, and server_loop from the parent after
501 * setting up file descriptors, controlling tty, updating wtmp, utmp,
502 * lastlog, and other such operations.
503 */
6ae2364d 504void
65068d16 505do_exec_pty(Session *s, const char *command)
7368a6c8 506{
7368a6c8 507 int fdout, ptyfd, ttyfd, ptymaster;
7368a6c8 508 pid_t pid;
7368a6c8 509
510 if (s == NULL)
511 fatal("do_exec_pty: no session");
512 ptyfd = s->ptyfd;
513 ttyfd = s->ttyfd;
514
b19d61d7 515#if defined(USE_PAM)
7fceb20d 516 if (options.use_pam) {
49e82bb9 517 do_pam_set_tty(s->tty);
7fceb20d 518 do_pam_setcred(1);
519 }
27cf96de 520#endif
266140a8 521
7368a6c8 522 /* Fork the child. */
523 if ((pid = fork()) == 0) {
2362db19 524 is_child = 1;
57156994 525
c345cf9d 526 /* Child. Reinitialize the log because the pid has changed. */
7368a6c8 527 log_init(__progname, options.log_level, options.log_facility, log_stderr);
7368a6c8 528 /* Close the master side of the pseudo tty. */
529 close(ptyfd);
530
531 /* Make the pseudo tty our controlling tty. */
532 pty_make_controlling_tty(&ttyfd, s->tty);
533
05fd093c 534 /* Redirect stdin/stdout/stderr from the pseudo tty. */
535 if (dup2(ttyfd, 0) < 0)
536 error("dup2 stdin: %s", strerror(errno));
537 if (dup2(ttyfd, 1) < 0)
538 error("dup2 stdout: %s", strerror(errno));
539 if (dup2(ttyfd, 2) < 0)
540 error("dup2 stderr: %s", strerror(errno));
7368a6c8 541
542 /* Close the extra descriptor for the pseudo tty. */
543 close(ttyfd);
544
c345cf9d 545 /* record login, etc. similar to login(1) */
c96a4aaf 546#ifndef HAVE_OSF_SIA
ef51930f 547 if (!(options.use_login && command == NULL)) {
548#ifdef _UNICOS
549 cray_init_job(s->pw); /* set up cray jid and tmpdir */
550#endif /* _UNICOS */
a22aff1f 551 do_login(s, command);
ef51930f 552 }
7e2d5fa4 553# ifdef LOGIN_NEEDS_UTMPX
554 else
555 do_pre_login(s);
556# endif
c96a4aaf 557#endif
7368a6c8 558
7368a6c8 559 /* Do common processing for the child, such as execing the command. */
56b3e9ce 560 do_child(s, command);
7368a6c8 561 /* NOTREACHED */
562 }
ef51930f 563#ifdef _UNICOS
564 signal(WJSIGNAL, cray_job_termination_handler);
565#endif /* _UNICOS */
3c62e7eb 566#ifdef HAVE_CYGWIN
567 if (is_winnt)
568 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
569#endif
7368a6c8 570 if (pid < 0)
571 packet_disconnect("fork failed: %.100s", strerror(errno));
572 s->pid = pid;
573
574 /* Parent. Close the slave side of the pseudo tty. */
575 close(ttyfd);
576
577 /*
578 * Create another descriptor of the pty master side for use as the
579 * standard input. We could use the original descriptor, but this
580 * simplifies code in server_loop. The descriptor is bidirectional.
581 */
582 fdout = dup(ptyfd);
583 if (fdout < 0)
584 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
585
586 /* we keep a reference to the pty master */
587 ptymaster = dup(ptyfd);
588 if (ptymaster < 0)
589 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
590 s->ptymaster = ptymaster;
591
592 /* Enter interactive session. */
b5c334cc 593 packet_set_interactive(1);
e78a59f5 594 if (compat20) {
595 session_set_fds(s, ptyfd, fdout, -1);
596 } else {
597 server_loop(pid, ptyfd, fdout, -1);
598 /* server_loop _has_ closed ptyfd and fdout. */
e78a59f5 599 }
7368a6c8 600}
601
7e2d5fa4 602#ifdef LOGIN_NEEDS_UTMPX
0e0144b7 603static void
7e2d5fa4 604do_pre_login(Session *s)
605{
606 socklen_t fromlen;
607 struct sockaddr_storage from;
608 pid_t pid = getpid();
609
610 /*
611 * Get IP address of client. If the connection is not a socket, let
612 * the address be 0.0.0.0.
613 */
614 memset(&from, 0, sizeof(from));
ba1566dd 615 fromlen = sizeof(from);
7e2d5fa4 616 if (packet_connection_is_on_socket()) {
7e2d5fa4 617 if (getpeername(packet_get_connection_in(),
184eed6a 618 (struct sockaddr *) & from, &fromlen) < 0) {
7e2d5fa4 619 debug("getpeername: %.100s", strerror(errno));
2362db19 620 cleanup_exit(255);
7e2d5fa4 621 }
622 }
623
624 record_utmp_only(pid, s->tty, s->pw->pw_name,
c5a7d788 625 get_remote_name_or_ip(utmp_len, options.use_dns),
d4ac26ed 626 (struct sockaddr *)&from, fromlen);
7e2d5fa4 627}
628#endif
629
dac6753b 630/*
631 * This is called to fork and execute a command. If another command is
632 * to be forced, execute that instead.
633 */
634void
635do_exec(Session *s, const char *command)
636{
637 if (forced_command) {
638 original_command = command;
639 command = forced_command;
dac6753b 640 debug("Forced command '%.900s'", command);
641 }
642
f89f8ddc 643#ifdef GSSAPI
644 if (options.gss_authentication) {
645 temporarily_use_uid(s->pw);
646 ssh_gssapi_storecreds();
647 restore_uid();
648 }
649#endif
650
dac6753b 651 if (s->ttyfd != -1)
652 do_exec_pty(s, command);
653 else
654 do_exec_no_pty(s, command);
655
c95add71 656 original_command = NULL;
dac6753b 657}
658
f7342052 659
c345cf9d 660/* administrative, login(1)-like work */
661void
a22aff1f 662do_login(Session *s, const char *command)
c345cf9d 663{
c345cf9d 664 char *time_string;
c345cf9d 665 socklen_t fromlen;
666 struct sockaddr_storage from;
c345cf9d 667 struct passwd * pw = s->pw;
668 pid_t pid = getpid();
669
670 /*
671 * Get IP address of client. If the connection is not a socket, let
672 * the address be 0.0.0.0.
673 */
674 memset(&from, 0, sizeof(from));
d4ac26ed 675 fromlen = sizeof(from);
c345cf9d 676 if (packet_connection_is_on_socket()) {
c345cf9d 677 if (getpeername(packet_get_connection_in(),
f7342052 678 (struct sockaddr *) & from, &fromlen) < 0) {
c345cf9d 679 debug("getpeername: %.100s", strerror(errno));
2362db19 680 cleanup_exit(255);
c345cf9d 681 }
682 }
683
684 /* Record that there was a login on that tty from the remote host. */
49a34e84 685 if (!use_privsep)
686 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
687 get_remote_name_or_ip(utmp_len,
c5a7d788 688 options.use_dns),
ba1566dd 689 (struct sockaddr *)&from, fromlen);
c345cf9d 690
2919e060 691#ifdef USE_PAM
692 /*
693 * If password change is needed, do it now.
694 * This needs to occur before the ~/.hushlogin check.
695 */
7fceb20d 696 if (options.use_pam && is_pam_password_change_required()) {
2919e060 697 print_pam_messages();
698 do_pam_chauthtok();
5b9e2464 699 /* XXX - signal [net] parent to enable forwardings */
2919e060 700 }
701#endif
702
f2c2fd71 703 if (check_quietlogin(s, command))
c345cf9d 704 return;
705
706#ifdef USE_PAM
7fceb20d 707 if (options.use_pam && !is_pam_password_change_required())
2919e060 708 print_pam_messages();
c345cf9d 709#endif /* USE_PAM */
bc7dfc06 710
711 /* display post-login message */
712 if (buffer_len(&loginmsg) > 0) {
713 buffer_append(&loginmsg, "\0", 1);
714 printf("%s\n", (char *)buffer_ptr(&loginmsg));
715 }
716 buffer_free(&loginmsg);
c345cf9d 717
ef51930f 718#ifndef NO_SSH_LASTLOG
ffbf7323 719 if (options.print_lastlog && s->last_login_time != 0) {
720 time_string = ctime(&s->last_login_time);
c345cf9d 721 if (strchr(time_string, '\n'))
722 *strchr(time_string, '\n') = 0;
ffbf7323 723 if (strcmp(s->hostname, "") == 0)
c345cf9d 724 printf("Last login: %s\r\n", time_string);
725 else
ffbf7323 726 printf("Last login: %s from %s\r\n", time_string,
727 s->hostname);
c345cf9d 728 }
ef51930f 729#endif /* NO_SSH_LASTLOG */
f2c2fd71 730
731 do_motd();
732}
733
734/*
735 * Display the message of the day.
736 */
737void
738do_motd(void)
739{
740 FILE *f;
741 char buf[256];
742
c345cf9d 743 if (options.print_motd) {
2e73a022 744#ifdef HAVE_LOGIN_CAP
745 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
746 "/etc/motd"), "r");
747#else
c345cf9d 748 f = fopen("/etc/motd", "r");
2e73a022 749#endif
c345cf9d 750 if (f) {
751 while (fgets(buf, sizeof(buf), f))
752 fputs(buf, stdout);
753 fclose(f);
754 }
755 }
756}
757
9c328529 758
759/*
760 * Check for quiet login, either .hushlogin or command given.
761 */
762int
763check_quietlogin(Session *s, const char *command)
764{
765 char buf[256];
766 struct passwd *pw = s->pw;
767 struct stat st;
768
769 /* Return 1 if .hushlogin exists or a command given. */
770 if (command != NULL)
771 return 1;
772 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
773#ifdef HAVE_LOGIN_CAP
774 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
775 return 1;
776#else
777 if (stat(buf, &st) >= 0)
778 return 1;
779#endif
780 return 0;
781}
782
7368a6c8 783/*
784 * Sets the value of the given variable in the environment. If the variable
785 * already exists, its value is overriden.
786 */
7364bd04 787void
1e3b8b07 788child_set_env(char ***envp, u_int *envsizep, const char *name,
184eed6a 789 const char *value)
7368a6c8 790{
7368a6c8 791 char **env;
c46e584f 792 u_int envsize;
793 u_int i, namelen;
7368a6c8 794
95b99395 795 /*
796 * If we're passed an uninitialized list, allocate a single null
797 * entry before continuing.
798 */
799 if (*envp == NULL && *envsizep == 0) {
800 *envp = xmalloc(sizeof(char *));
801 *envp[0] = NULL;
802 *envsizep = 1;
803 }
804
7368a6c8 805 /*
806 * Find the slot where the value should be stored. If the variable
807 * already exists, we reuse the slot; otherwise we append a new slot
808 * at the end of the array, expanding if necessary.
809 */
810 env = *envp;
811 namelen = strlen(name);
812 for (i = 0; env[i]; i++)
813 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
814 break;
815 if (env[i]) {
816 /* Reuse the slot. */
817 xfree(env[i]);
818 } else {
819 /* New variable. Expand if necessary. */
c46e584f 820 envsize = *envsizep;
821 if (i >= envsize - 1) {
822 if (envsize >= 1000)
823 fatal("child_set_env: too many env vars");
824 envsize += 50;
825 env = (*envp) = xrealloc(env, envsize * sizeof(char *));
826 *envsizep = envsize;
7368a6c8 827 }
828 /* Need to set the NULL pointer at end of array beyond the new slot. */
829 env[i + 1] = NULL;
830 }
831
832 /* Allocate space and format the variable in the appropriate slot. */
833 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
834 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
835}
836
837/*
838 * Reads environment variables from the given file and adds/overrides them
839 * into the environment. If the file does not exist, this does nothing.
840 * Otherwise, it must consist of empty lines, comments (line starts with '#')
841 * and assignments of the form name=value. No other forms are allowed.
842 */
396c147e 843static void
1e3b8b07 844read_environment_file(char ***env, u_int *envsize,
184eed6a 845 const char *filename)
7368a6c8 846{
847 FILE *f;
848 char buf[4096];
849 char *cp, *value;
66087567 850 u_int lineno = 0;
7368a6c8 851
852 f = fopen(filename, "r");
853 if (!f)
854 return;
855
856 while (fgets(buf, sizeof(buf), f)) {
66087567 857 if (++lineno > 1000)
858 fatal("Too many lines in environment file %s", filename);
7368a6c8 859 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
860 ;
861 if (!*cp || *cp == '#' || *cp == '\n')
862 continue;
863 if (strchr(cp, '\n'))
864 *strchr(cp, '\n') = '\0';
865 value = strchr(cp, '=');
866 if (value == NULL) {
66087567 867 fprintf(stderr, "Bad line %u in %.100s\n", lineno,
868 filename);
7368a6c8 869 continue;
870 }
71276795 871 /*
872 * Replace the equals sign by nul, and advance value to
873 * the value string.
874 */
7368a6c8 875 *value = '\0';
876 value++;
877 child_set_env(env, envsize, cp, value);
878 }
879 fclose(f);
880}
881
95b99395 882#ifdef HAVE_ETC_DEFAULT_LOGIN
883/*
884 * Return named variable from specified environment, or NULL if not present.
885 */
886static char *
887child_get_env(char **env, const char *name)
888{
889 int i;
890 size_t len;
891
892 len = strlen(name);
893 for (i=0; env[i] != NULL; i++)
894 if (strncmp(name, env[i], len) == 0 && env[i][len] == '=')
895 return(env[i] + len + 1);
896 return NULL;
897}
898
899/*
900 * Read /etc/default/login.
901 * We pick up the PATH (or SUPATH for root) and UMASK.
902 */
903static void
904read_etc_default_login(char ***env, u_int *envsize, uid_t uid)
905{
906 char **tmpenv = NULL, *var;
6f99680f 907 u_int i, tmpenvsize = 0;
3a23ba0e 908 u_long mask;
95b99395 909
910 /*
911 * We don't want to copy the whole file to the child's environment,
912 * so we use a temporary environment and copy the variables we're
913 * interested in.
914 */
915 read_environment_file(&tmpenv, &tmpenvsize, "/etc/default/login");
916
6f99680f 917 if (tmpenv == NULL)
918 return;
919
95b99395 920 if (uid == 0)
921 var = child_get_env(tmpenv, "SUPATH");
922 else
923 var = child_get_env(tmpenv, "PATH");
924 if (var != NULL)
925 child_set_env(env, envsize, "PATH", var);
b6453d99 926
95b99395 927 if ((var = child_get_env(tmpenv, "UMASK")) != NULL)
928 if (sscanf(var, "%5lo", &mask) == 1)
3a23ba0e 929 umask((mode_t)mask);
b6453d99 930
95b99395 931 for (i = 0; tmpenv[i] != NULL; i++)
932 xfree(tmpenv[i]);
933 xfree(tmpenv);
934}
935#endif /* HAVE_ETC_DEFAULT_LOGIN */
936
760b35a6 937void copy_environment(char **source, char ***env, u_int *envsize)
7368a6c8 938{
760b35a6 939 char *var_name, *var_val;
7368a6c8 940 int i;
941
760b35a6 942 if (source == NULL)
7368a6c8 943 return;
2b87da3b 944
760b35a6 945 for(i = 0; source[i] != NULL; i++) {
946 var_name = xstrdup(source[i]);
947 if ((var_val = strstr(var_name, "=")) == NULL) {
948 xfree(var_name);
7368a6c8 949 continue;
7368a6c8 950 }
760b35a6 951 *var_val++ = '\0';
7368a6c8 952
760b35a6 953 debug3("Copy environment: %s=%s", var_name, var_val);
954 child_set_env(env, envsize, var_name, var_val);
b6453d99 955
760b35a6 956 xfree(var_name);
22d89d24 957 }
958}
22d89d24 959
f7342052 960static char **
961do_setup_env(Session *s, const char *shell)
7368a6c8 962{
7368a6c8 963 char buf[256];
f7342052 964 u_int i, envsize;
95b99395 965 char **env, *laddr, *path = NULL;
f7342052 966 struct passwd *pw = s->pw;
7368a6c8 967
7368a6c8 968 /* Initialize the environment. */
969 envsize = 100;
970 env = xmalloc(envsize * sizeof(char *));
971 env[0] = NULL;
972
3c62e7eb 973#ifdef HAVE_CYGWIN
974 /*
975 * The Windows environment contains some setting which are
976 * important for a running system. They must not be dropped.
977 */
760b35a6 978 copy_environment(environ, &env, &envsize);
3c62e7eb 979#endif
980
7364bd04 981#ifdef GSSAPI
aff51935 982 /* Allow any GSSAPI methods that we've used to alter
7364bd04 983 * the childs environment as they see fit
984 */
985 ssh_gssapi_do_child(&env, &envsize);
986#endif
987
7368a6c8 988 if (!options.use_login) {
989 /* Set basic environment. */
990 child_set_env(&env, &envsize, "USER", pw->pw_name);
991 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
17ed08c5 992#ifdef _AIX
993 child_set_env(&env, &envsize, "LOGIN", pw->pw_name);
994#endif
7368a6c8 995 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2e73a022 996#ifdef HAVE_LOGIN_CAP
97686bf9 997 if (setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH) < 0)
998 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
999 else
1000 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
22d89d24 1001#else /* HAVE_LOGIN_CAP */
1002# ifndef HAVE_CYGWIN
3c62e7eb 1003 /*
1004 * There's no standard path on Windows. The path contains
1005 * important components pointing to the system directories,
1006 * needed for loading shared libraries. So the path better
1007 * remains intact here.
1008 */
95b99395 1009# ifdef HAVE_ETC_DEFAULT_LOGIN
1010 read_etc_default_login(&env, &envsize, pw->pw_uid);
1011 path = child_get_env(env, "PATH");
1012# endif /* HAVE_ETC_DEFAULT_LOGIN */
1013 if (path == NULL || *path == '\0') {
aff51935 1014 child_set_env(&env, &envsize, "PATH",
95b99395 1015 s->pw->pw_uid == 0 ?
1016 SUPERUSER_PATH : _PATH_STDPATH);
1017 }
22d89d24 1018# endif /* HAVE_CYGWIN */
1019#endif /* HAVE_LOGIN_CAP */
7368a6c8 1020
1021 snprintf(buf, sizeof buf, "%.200s/%.50s",
1022 _PATH_MAILDIR, pw->pw_name);
1023 child_set_env(&env, &envsize, "MAIL", buf);
1024
1025 /* Normal systems set SHELL by default. */
1026 child_set_env(&env, &envsize, "SHELL", shell);
1027 }
1028 if (getenv("TZ"))
1029 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1030
1031 /* Set custom environment options from RSA authentication. */
2548961d 1032 if (!options.use_login) {
1033 while (custom_environment) {
1034 struct envstring *ce = custom_environment;
7fdc56c5 1035 char *str = ce->s;
f7342052 1036
7fdc56c5 1037 for (i = 0; str[i] != '=' && str[i]; i++)
2548961d 1038 ;
7fdc56c5 1039 if (str[i] == '=') {
1040 str[i] = 0;
1041 child_set_env(&env, &envsize, str, str + i + 1);
2548961d 1042 }
1043 custom_environment = ce->next;
1044 xfree(ce->s);
1045 xfree(ce);
7368a6c8 1046 }
7368a6c8 1047 }
1048
da0561eb 1049 /* SSH_CLIENT deprecated */
7368a6c8 1050 snprintf(buf, sizeof buf, "%.50s %d %d",
f7342052 1051 get_remote_ipaddr(), get_remote_port(), get_local_port());
7368a6c8 1052 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1053
3e2f2431 1054 laddr = get_local_ipaddr(packet_get_connection_in());
da0561eb 1055 snprintf(buf, sizeof buf, "%.50s %d %.50s %d",
3e2f2431 1056 get_remote_ipaddr(), get_remote_port(), laddr, get_local_port());
1057 xfree(laddr);
da0561eb 1058 child_set_env(&env, &envsize, "SSH_CONNECTION", buf);
1059
56b3e9ce 1060 if (s->ttyfd != -1)
1061 child_set_env(&env, &envsize, "SSH_TTY", s->tty);
1062 if (s->term)
1063 child_set_env(&env, &envsize, "TERM", s->term);
1064 if (s->display)
1065 child_set_env(&env, &envsize, "DISPLAY", s->display);
b5e300c2 1066 if (original_command)
1067 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1068 original_command);
7368a6c8 1069
ef51930f 1070#ifdef _UNICOS
1071 if (cray_tmpdir[0] != '\0')
1072 child_set_env(&env, &envsize, "TMPDIR", cray_tmpdir);
1073#endif /* _UNICOS */
1074
7368a6c8 1075#ifdef _AIX
4936fcee 1076 {
1077 char *cp;
1078
1079 if ((cp = getenv("AUTHSTATE")) != NULL)
1080 child_set_env(&env, &envsize, "AUTHSTATE", cp);
1081 if ((cp = getenv("KRB5CCNAME")) != NULL)
1082 child_set_env(&env, &envsize, "KRB5CCNAME", cp);
1083 read_environment_file(&env, &envsize, "/etc/environment");
1084 }
7368a6c8 1085#endif
ced49be2 1086#ifdef KRB5
1087 if (s->authctxt->krb5_ticket_file)
1088 child_set_env(&env, &envsize, "KRB5CCNAME",
1089 s->authctxt->krb5_ticket_file);
1090#endif
7368a6c8 1091#ifdef USE_PAM
ee48c949 1092 /*
1093 * Pull in any environment variables that may have
1094 * been set by PAM.
1095 */
7fceb20d 1096 if (options.use_pam) {
2212fc98 1097 char **p;
b6453d99 1098
2212fc98 1099 p = fetch_pam_child_environment();
1100 copy_environment(p, &env, &envsize);
1101 free_pam_environment(p);
ee48c949 1102
2212fc98 1103 p = fetch_pam_environment();
ee48c949 1104 copy_environment(p, &env, &envsize);
1105 free_pam_environment(p);
1106 }
7368a6c8 1107#endif /* USE_PAM */
1108
149cdb60 1109 if (auth_sock_name != NULL)
7368a6c8 1110 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
149cdb60 1111 auth_sock_name);
7368a6c8 1112
1113 /* read $HOME/.ssh/environment. */
f00bab84 1114 if (options.permit_user_env && !options.use_login) {
71276795 1115 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
e2e36358 1116 strcmp(pw->pw_dir, "/") ? pw->pw_dir : "");
7368a6c8 1117 read_environment_file(&env, &envsize, buf);
1118 }
1119 if (debug_flag) {
1120 /* dump the environment */
1121 fprintf(stderr, "Environment:\n");
1122 for (i = 0; env[i]; i++)
1123 fprintf(stderr, " %.200s\n", env[i]);
1124 }
f7342052 1125 return env;
1126}
1127
1128/*
1129 * Run $HOME/.ssh/rc, /etc/ssh/sshrc, or xauth (whichever is found
1130 * first in this order).
1131 */
1132static void
1133do_rc_files(Session *s, const char *shell)
1134{
1135 FILE *f = NULL;
1136 char cmd[1024];
1137 int do_xauth;
1138 struct stat st;
1139
1140 do_xauth =
1141 s->display != NULL && s->auth_proto != NULL && s->auth_data != NULL;
1142
1143 /* ignore _PATH_SSH_USER_RC for subsystems */
1144 if (!s->is_subsystem && (stat(_PATH_SSH_USER_RC, &st) >= 0)) {
1145 snprintf(cmd, sizeof cmd, "%s -c '%s %s'",
1146 shell, _PATH_BSHELL, _PATH_SSH_USER_RC);
1147 if (debug_flag)
1148 fprintf(stderr, "Running %s\n", cmd);
1149 f = popen(cmd, "w");
1150 if (f) {
1151 if (do_xauth)
1152 fprintf(f, "%s %s\n", s->auth_proto,
1153 s->auth_data);
1154 pclose(f);
1155 } else
1156 fprintf(stderr, "Could not run %s\n",
1157 _PATH_SSH_USER_RC);
1158 } else if (stat(_PATH_SSH_SYSTEM_RC, &st) >= 0) {
1159 if (debug_flag)
1160 fprintf(stderr, "Running %s %s\n", _PATH_BSHELL,
1161 _PATH_SSH_SYSTEM_RC);
1162 f = popen(_PATH_BSHELL " " _PATH_SSH_SYSTEM_RC, "w");
1163 if (f) {
1164 if (do_xauth)
1165 fprintf(f, "%s %s\n", s->auth_proto,
1166 s->auth_data);
1167 pclose(f);
1168 } else
1169 fprintf(stderr, "Could not run %s\n",
1170 _PATH_SSH_SYSTEM_RC);
1171 } else if (do_xauth && options.xauth_location != NULL) {
1172 /* Add authority data to .Xauthority if appropriate. */
1173 if (debug_flag) {
1174 fprintf(stderr,
fe661d8f 1175 "Running %.500s remove %.100s\n",
2362db19 1176 options.xauth_location, s->auth_display);
fe661d8f 1177 fprintf(stderr,
1178 "%.500s add %.100s %.100s %.100s\n",
f7342052 1179 options.xauth_location, s->auth_display,
1180 s->auth_proto, s->auth_data);
1181 }
1182 snprintf(cmd, sizeof cmd, "%s -q -",
1183 options.xauth_location);
1184 f = popen(cmd, "w");
1185 if (f) {
fe661d8f 1186 fprintf(f, "remove %s\n",
1187 s->auth_display);
f7342052 1188 fprintf(f, "add %s %s %s\n",
1189 s->auth_display, s->auth_proto,
1190 s->auth_data);
1191 pclose(f);
1192 } else {
1193 fprintf(stderr, "Could not run %s\n",
1194 cmd);
1195 }
1196 }
1197}
1198
1199static void
1200do_nologin(struct passwd *pw)
1201{
1202 FILE *f = NULL;
1203 char buf[1024];
1204
1205#ifdef HAVE_LOGIN_CAP
1206 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
1207 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
1208 _PATH_NOLOGIN), "r");
1209#else
1210 if (pw->pw_uid)
1211 f = fopen(_PATH_NOLOGIN, "r");
1212#endif
1213 if (f) {
1214 /* /etc/nologin exists. Print its contents and exit. */
bbe88b6d 1215 logit("User %.100s not allowed because %s exists",
8bd4e2ae 1216 pw->pw_name, _PATH_NOLOGIN);
f7342052 1217 while (fgets(buf, sizeof(buf), f))
1218 fputs(buf, stderr);
1219 fclose(f);
99f4fb69 1220 fflush(NULL);
f7342052 1221 exit(254);
1222 }
1223}
1224
1225/* Set login name, uid, gid, and groups. */
1853d1ef 1226void
f7342052 1227do_setusercontext(struct passwd *pw)
1228{
2731632a 1229#ifndef HAVE_CYGWIN
1230 if (getuid() == 0 || geteuid() == 0)
f7342052 1231#endif /* HAVE_CYGWIN */
2731632a 1232 {
1233
8bbfc882 1234#ifdef HAVE_SETPCRED
166baacc 1235 if (setpcred(pw->pw_name, (char **)NULL) == -1)
1236 fatal("Failed to set process credentials");
8bbfc882 1237#endif /* HAVE_SETPCRED */
f7342052 1238#ifdef HAVE_LOGIN_CAP
2d199535 1239# ifdef __bsdi__
8695f9f7 1240 setpgid(0, 0);
2d199535 1241# endif
f7342052 1242 if (setusercontext(lc, pw, pw->pw_uid,
1243 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1244 perror("unable to set user context");
1245 exit(1);
1246 }
1247#else
1248# if defined(HAVE_GETLUID) && defined(HAVE_SETLUID)
1249 /* Sets login uid for accounting */
1250 if (getluid() == -1 && setluid(pw->pw_uid) == -1)
1251 error("setluid: %s", strerror(errno));
1252# endif /* defined(HAVE_GETLUID) && defined(HAVE_SETLUID) */
1253
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# ifdef USE_PAM
1267 /*
aff51935 1268 * PAM credentials may take the form of supplementary groups.
f7342052 1269 * These will have been wiped by the above initgroups() call.
1270 * Reestablish them here.
1271 */
49e82bb9 1272 if (options.use_pam) {
1273 do_pam_session();
7fceb20d 1274 do_pam_setcred(0);
49e82bb9 1275 }
f7342052 1276# endif /* USE_PAM */
1277# if defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY)
1278 irix_setusercontext(pw);
1279# endif /* defined(WITH_IRIX_PROJECT) || defined(WITH_IRIX_JOBS) || defined(WITH_IRIX_ARRAY) */
e2bc41f9 1280# ifdef _AIX
0ba40daa 1281 aix_usrinfo(pw);
e2bc41f9 1282# endif /* _AIX */
f7342052 1283 /* Permanently switch to the desired uid. */
1284 permanently_set_uid(pw);
1285#endif
1286 }
2731632a 1287
1288#ifdef HAVE_CYGWIN
1289 if (is_winnt)
1290#endif
f7342052 1291 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
1292 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
1293}
1294
51aeb639 1295static void
1853d1ef 1296launch_login(struct passwd *pw, const char *hostname)
1297{
1298 /* Launch login(1). */
1299
85cc9118 1300 execl(LOGIN_PROGRAM, "login", "-h", hostname,
1178e8db 1301#ifdef xxxLOGIN_NEEDS_TERM
875ec275 1302 (s->term ? s->term : "unknown"),
1853d1ef 1303#endif /* LOGIN_NEEDS_TERM */
a2572aa7 1304#ifdef LOGIN_NO_ENDOPT
1305 "-p", "-f", pw->pw_name, (char *)NULL);
1306#else
1853d1ef 1307 "-p", "-f", "--", pw->pw_name, (char *)NULL);
a2572aa7 1308#endif
1853d1ef 1309
1310 /* Login couldn't be executed, die. */
1311
1312 perror("login");
1313 exit(1);
1314}
1315
f7342052 1316/*
1317 * Performs common processing for the child, such as setting up the
1318 * environment, closing extra file descriptors, setting the user and group
1319 * ids, and executing the command or shell.
1320 */
1321void
1322do_child(Session *s, const char *command)
1323{
1324 extern char **environ;
1325 char **env;
1326 char *argv[10];
1327 const char *shell, *shell0, *hostname = NULL;
1328 struct passwd *pw = s->pw;
1329 u_int i;
1330
1331 /* remove hostkey from the child's memory */
1332 destroy_sensitive_data();
1333
1334 /* login(1) is only called if we execute the login shell */
1335 if (options.use_login && command != NULL)
1336 options.use_login = 0;
1337
ef51930f 1338#ifdef _UNICOS
1339 cray_setup(pw->pw_uid, pw->pw_name, command);
1340#endif /* _UNICOS */
1341
f7342052 1342 /*
1343 * Login(1) does this as well, and it needs uid 0 for the "-h"
1344 * switch, so we let login(1) to this for us.
1345 */
1346 if (!options.use_login) {
1347#ifdef HAVE_OSF_SIA
58d0df4e 1348 session_setup_sia(pw, s->ttyfd == -1 ? NULL : s->tty);
f7342052 1349 if (!check_quietlogin(s, command))
1350 do_motd();
1351#else /* HAVE_OSF_SIA */
1352 do_nologin(pw);
1353 do_setusercontext(pw);
1354#endif /* HAVE_OSF_SIA */
1355 }
1356
1357 /*
1358 * Get the shell from the password data. An empty shell field is
1359 * legal, and means /bin/sh.
1360 */
1361 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
32214c88 1362
1363 /*
1364 * Make sure $SHELL points to the shell from the password file,
1365 * even if shell is overridden from login.conf
1366 */
1367 env = do_setup_env(s, shell);
1368
f7342052 1369#ifdef HAVE_LOGIN_CAP
1370 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1371#endif
1372
2e73a022 1373 /* we have to stash the hostname before we close our socket. */
1374 if (options.use_login)
46e3af7f 1375 hostname = get_remote_name_or_ip(utmp_len,
c5a7d788 1376 options.use_dns);
7368a6c8 1377 /*
1378 * Close the connection descriptors; note that this is the child, and
1379 * the server will still have the socket open, and it is important
1380 * that we do not shutdown it. Note that the descriptors cannot be
1381 * closed before building the environment, as we call
1382 * get_remote_ipaddr there.
1383 */
1384 if (packet_get_connection_in() == packet_get_connection_out())
1385 close(packet_get_connection_in());
1386 else {
1387 close(packet_get_connection_in());
1388 close(packet_get_connection_out());
1389 }
1390 /*
1391 * Close all descriptors related to channels. They will still remain
1392 * open in the parent.
1393 */
1394 /* XXX better use close-on-exec? -markus */
1395 channel_close_all();
1396
1397 /*
1398 * Close any extra file descriptors. Note that there may still be
1399 * descriptors left by system functions. They will be closed later.
1400 */
1401 endpwent();
1402
1403 /*
1404 * Close any extra open file descriptors so that we don\'t have them
1405 * hanging around in clients. Note that we want to do this after
1406 * initgroups, because at least on Solaris 2.3 it leaves file
1407 * descriptors open.
1408 */
1409 for (i = 3; i < 64; i++)
1410 close(i);
1411
7368a6c8 1412 /*
2a8a6488 1413 * Must take new environment into use so that .ssh/rc,
1414 * /etc/ssh/sshrc and xauth are run in the proper environment.
7368a6c8 1415 */
1416 environ = env;
1417
dab89049 1418 /* Change current directory to the user\'s home directory. */
1419 if (chdir(pw->pw_dir) < 0) {
1420 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1421 pw->pw_dir, strerror(errno));
1422#ifdef HAVE_LOGIN_CAP
1423 if (login_getcapbool(lc, "requirehome", 0))
1424 exit(1);
1425#endif
1426 }
1427
f7342052 1428 if (!options.use_login)
1429 do_rc_files(s, shell);
1d3c30db 1430
1431 /* restore SIGPIPE for child */
1432 signal(SIGPIPE, SIG_DFL);
1433
f7342052 1434 if (options.use_login) {
1853d1ef 1435 launch_login(pw, hostname);
1436 /* NEVERREACHED */
f7342052 1437 }
1438
1439 /* Get the last component of the shell name. */
1440 if ((shell0 = strrchr(shell, '/')) != NULL)
1441 shell0++;
1442 else
1443 shell0 = shell;
1444
7368a6c8 1445 /*
1446 * If we have no command, execute the shell. In this case, the shell
1447 * name to be passed in argv[0] is preceded by '-' to indicate that
1448 * this is a login shell.
1449 */
1450 if (!command) {
f7342052 1451 char argv0[256];
7368a6c8 1452
f7342052 1453 /* Start the shell. Set initial character to '-'. */
1454 argv0[0] = '-';
7368a6c8 1455
f7342052 1456 if (strlcpy(argv0 + 1, shell0, sizeof(argv0) - 1)
1457 >= sizeof(argv0) - 1) {
1458 errno = EINVAL;
7368a6c8 1459 perror(shell);
1460 exit(1);
f7342052 1461 }
7368a6c8 1462
f7342052 1463 /* Execute the shell. */
1464 argv[0] = argv0;
1465 argv[1] = NULL;
1466 execve(shell, argv, env);
7368a6c8 1467
f7342052 1468 /* Executing the shell failed. */
1469 perror(shell);
1470 exit(1);
7368a6c8 1471 }
1472 /*
1473 * Execute the command using the user's shell. This uses the -c
1474 * option to execute the command.
1475 */
f7342052 1476 argv[0] = (char *) shell0;
7368a6c8 1477 argv[1] = "-c";
1478 argv[2] = (char *) command;
1479 argv[3] = NULL;
1480 execve(shell, argv, env);
1481 perror(shell);
1482 exit(1);
1483}
1484
1485Session *
1486session_new(void)
1487{
1488 int i;
1489 static int did_init = 0;
1490 if (!did_init) {
1491 debug("session_new: init");
184eed6a 1492 for (i = 0; i < MAX_SESSIONS; i++) {
7368a6c8 1493 sessions[i].used = 0;
7368a6c8 1494 }
1495 did_init = 1;
1496 }
184eed6a 1497 for (i = 0; i < MAX_SESSIONS; i++) {
7368a6c8 1498 Session *s = &sessions[i];
1499 if (! s->used) {
690d0d7f 1500 memset(s, 0, sizeof(*s));
7368a6c8 1501 s->chanid = -1;
1502 s->ptyfd = -1;
1503 s->ttyfd = -1;
7368a6c8 1504 s->used = 1;
86066315 1505 s->self = i;
02323c45 1506 debug("session_new: session %d", i);
7368a6c8 1507 return s;
1508 }
1509 }
1510 return NULL;
1511}
1512
396c147e 1513static void
7368a6c8 1514session_dump(void)
1515{
1516 int i;
184eed6a 1517 for (i = 0; i < MAX_SESSIONS; i++) {
7368a6c8 1518 Session *s = &sessions[i];
c457707e 1519 debug("dump: used %d session %d %p channel %d pid %ld",
7368a6c8 1520 s->used,
1521 s->self,
1522 s,
1523 s->chanid,
c457707e 1524 (long)s->pid);
7368a6c8 1525 }
1526}
1527
e78a59f5 1528int
57156994 1529session_open(Authctxt *authctxt, int chanid)
e78a59f5 1530{
1531 Session *s = session_new();
1532 debug("session_open: channel %d", chanid);
1533 if (s == NULL) {
1534 error("no more sessions");
1535 return 0;
1536 }
57156994 1537 s->authctxt = authctxt;
1538 s->pw = authctxt->pw;
fdaef11e 1539 if (s->pw == NULL || !authctxt->valid)
0725ea77 1540 fatal("no user for session %d", s->self);
0b242b12 1541 debug("session_open: session %d: link with channel %d", s->self, chanid);
1542 s->chanid = chanid;
e78a59f5 1543 return 1;
1544}
1545
1853d1ef 1546Session *
1547session_by_tty(char *tty)
1548{
1549 int i;
1550 for (i = 0; i < MAX_SESSIONS; i++) {
1551 Session *s = &sessions[i];
1552 if (s->used && s->ttyfd != -1 && strcmp(s->tty, tty) == 0) {
1553 debug("session_by_tty: session %d tty %s", i, tty);
1554 return s;
1555 }
1556 }
1557 debug("session_by_tty: unknown tty %.100s", tty);
1558 session_dump();
1559 return NULL;
1560}
1561
396c147e 1562static Session *
e78a59f5 1563session_by_channel(int id)
1564{
1565 int i;
184eed6a 1566 for (i = 0; i < MAX_SESSIONS; i++) {
e78a59f5 1567 Session *s = &sessions[i];
1568 if (s->used && s->chanid == id) {
1569 debug("session_by_channel: session %d channel %d", i, id);
1570 return s;
1571 }
1572 }
1573 debug("session_by_channel: unknown channel %d", id);
1574 session_dump();
1575 return NULL;
1576}
1577
396c147e 1578static Session *
e78a59f5 1579session_by_pid(pid_t pid)
1580{
1581 int i;
c457707e 1582 debug("session_by_pid: pid %ld", (long)pid);
184eed6a 1583 for (i = 0; i < MAX_SESSIONS; i++) {
e78a59f5 1584 Session *s = &sessions[i];
1585 if (s->used && s->pid == pid)
1586 return s;
1587 }
c457707e 1588 error("session_by_pid: unknown pid %ld", (long)pid);
e78a59f5 1589 session_dump();
1590 return NULL;
1591}
1592
396c147e 1593static int
e78a59f5 1594session_window_change_req(Session *s)
1595{
1596 s->col = packet_get_int();
1597 s->row = packet_get_int();
1598 s->xpixel = packet_get_int();
1599 s->ypixel = packet_get_int();
95500969 1600 packet_check_eom();
e78a59f5 1601 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1602 return 1;
1603}
1604
396c147e 1605static int
e78a59f5 1606session_pty_req(Session *s)
1607{
1e3b8b07 1608 u_int len;
30dcc918 1609 int n_bytes;
762715ce 1610
653d5f86 1611 if (no_pty_flag) {
1612 debug("Allocating a pty not permitted for this authentication.");
38c295d6 1613 return 0;
653d5f86 1614 }
1615 if (s->ttyfd != -1) {
1616 packet_disconnect("Protocol error: you already have a pty.");
6ae2364d 1617 return 0;
653d5f86 1618 }
ffbf7323 1619 /* Get the time and hostname when the user last logged in. */
1620 if (options.print_lastlog) {
1621 s->hostname[0] = '\0';
1622 s->last_login_time = get_last_login_time(s->pw->pw_uid,
1623 s->pw->pw_name, s->hostname, sizeof(s->hostname));
1624 }
653d5f86 1625
e78a59f5 1626 s->term = packet_get_string(&len);
653d5f86 1627
1628 if (compat20) {
1629 s->col = packet_get_int();
1630 s->row = packet_get_int();
1631 } else {
1632 s->row = packet_get_int();
1633 s->col = packet_get_int();
1634 }
e78a59f5 1635 s->xpixel = packet_get_int();
1636 s->ypixel = packet_get_int();
1637
1638 if (strcmp(s->term, "") == 0) {
1639 xfree(s->term);
1640 s->term = NULL;
1641 }
653d5f86 1642
e78a59f5 1643 /* Allocate a pty and open it. */
653d5f86 1644 debug("Allocating pty.");
1853d1ef 1645 if (!PRIVSEP(pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty)))) {
653d5f86 1646 if (s->term)
1647 xfree(s->term);
e78a59f5 1648 s->term = NULL;
1649 s->ptyfd = -1;
1650 s->ttyfd = -1;
1651 error("session_pty_req: session %d alloc failed", s->self);
6ae2364d 1652 return 0;
e78a59f5 1653 }
1654 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
653d5f86 1655
1656 /* for SSH1 the tty modes length is not given */
1657 if (!compat20)
1658 n_bytes = packet_remaining();
1659 tty_parse_modes(s->ttyfd, &n_bytes);
1660
1853d1ef 1661 if (!use_privsep)
1662 pty_setowner(s->pw, s->tty);
653d5f86 1663
1664 /* Set window size from the packet. */
e78a59f5 1665 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1666
95500969 1667 packet_check_eom();
1d1ffb87 1668 session_proctitle(s);
e78a59f5 1669 return 1;
1670}
1671
396c147e 1672static int
0b242b12 1673session_subsystem_req(Session *s)
1674{
01855277 1675 struct stat st;
1e3b8b07 1676 u_int len;
0b242b12 1677 int success = 0;
01855277 1678 char *cmd, *subsys = packet_get_string(&len);
38c295d6 1679 int i;
0b242b12 1680
95500969 1681 packet_check_eom();
bbe88b6d 1682 logit("subsystem request for %.100s", subsys);
0b242b12 1683
38c295d6 1684 for (i = 0; i < options.num_subsystems; i++) {
01855277 1685 if (strcmp(subsys, options.subsystem_name[i]) == 0) {
1686 cmd = options.subsystem_command[i];
1687 if (stat(cmd, &st) < 0) {
1688 error("subsystem: cannot stat %s: %s", cmd,
1689 strerror(errno));
1690 break;
1691 }
1692 debug("subsystem: exec() %s", cmd);
e5d7a405 1693 s->is_subsystem = 1;
01855277 1694 do_exec(s, cmd);
38c295d6 1695 success = 1;
24932ee9 1696 break;
38c295d6 1697 }
1698 }
1699
1700 if (!success)
bbe88b6d 1701 logit("subsystem request for %.100s failed, subsystem not found",
01855277 1702 subsys);
38c295d6 1703
0b242b12 1704 xfree(subsys);
1705 return success;
1706}
1707
396c147e 1708static int
0b242b12 1709session_x11_req(Session *s)
1710{
8dcd9d5c 1711 int success;
0b242b12 1712
1713 s->single_connection = packet_get_char();
1714 s->auth_proto = packet_get_string(NULL);
1715 s->auth_data = packet_get_string(NULL);
1716 s->screen = packet_get_int();
95500969 1717 packet_check_eom();
0b242b12 1718
8dcd9d5c 1719 success = session_setup_x11fwd(s);
1720 if (!success) {
0b242b12 1721 xfree(s->auth_proto);
1722 xfree(s->auth_data);
1500bcdd 1723 s->auth_proto = NULL;
1724 s->auth_data = NULL;
0b242b12 1725 }
8dcd9d5c 1726 return success;
0b242b12 1727}
1728
396c147e 1729static int
38c295d6 1730session_shell_req(Session *s)
1731{
95500969 1732 packet_check_eom();
dac6753b 1733 do_exec(s, NULL);
38c295d6 1734 return 1;
1735}
1736
396c147e 1737static int
38c295d6 1738session_exec_req(Session *s)
1739{
1e3b8b07 1740 u_int len;
38c295d6 1741 char *command = packet_get_string(&len);
95500969 1742 packet_check_eom();
dac6753b 1743 do_exec(s, command);
c95add71 1744 xfree(command);
38c295d6 1745 return 1;
1746}
1747
16a79097 1748static int
1749session_break_req(Session *s)
1750{
1751 u_int break_length;
1752
8168a86a 1753 break_length = packet_get_int(); /* ignored */
16a79097 1754 packet_check_eom();
1755
8168a86a 1756 if (s->ttyfd == -1 ||
1757 tcsendbreak(s->ttyfd, 0) < 0)
16a79097 1758 return 0;
16a79097 1759 return 1;
1760}
1761
396c147e 1762static int
fa08c86b 1763session_auth_agent_req(Session *s)
1764{
1765 static int called = 0;
95500969 1766 packet_check_eom();
d343d900 1767 if (no_agent_forwarding_flag) {
1768 debug("session_auth_agent_req: no_agent_forwarding_flag");
1769 return 0;
1770 }
fa08c86b 1771 if (called) {
1772 return 0;
1773 } else {
1774 called = 1;
1775 return auth_input_request_forwarding(s->pw);
1776 }
1777}
1778
7899c98f 1779int
1780session_input_channel_req(Channel *c, const char *rtype)
e78a59f5 1781{
e78a59f5 1782 int success = 0;
e78a59f5 1783 Session *s;
e78a59f5 1784
7899c98f 1785 if ((s = session_by_channel(c->self)) == NULL) {
bbe88b6d 1786 logit("session_input_channel_req: no session %d req %.100s",
7899c98f 1787 c->self, rtype);
1788 return 0;
1789 }
1790 debug("session_input_channel_req: session %d req %s", s->self, rtype);
e78a59f5 1791
1792 /*
e5d7a405 1793 * a session is in LARVAL state until a shell, a command
1794 * or a subsystem is executed
e78a59f5 1795 */
1796 if (c->type == SSH_CHANNEL_LARVAL) {
1797 if (strcmp(rtype, "shell") == 0) {
38c295d6 1798 success = session_shell_req(s);
e78a59f5 1799 } else if (strcmp(rtype, "exec") == 0) {
38c295d6 1800 success = session_exec_req(s);
e78a59f5 1801 } else if (strcmp(rtype, "pty-req") == 0) {
35484284 1802 success = session_pty_req(s);
0b242b12 1803 } else if (strcmp(rtype, "x11-req") == 0) {
1804 success = session_x11_req(s);
fa08c86b 1805 } else if (strcmp(rtype, "auth-agent-req@openssh.com") == 0) {
1806 success = session_auth_agent_req(s);
0b242b12 1807 } else if (strcmp(rtype, "subsystem") == 0) {
1808 success = session_subsystem_req(s);
16a79097 1809 } else if (strcmp(rtype, "break") == 0) {
1810 success = session_break_req(s);
e78a59f5 1811 }
1812 }
1813 if (strcmp(rtype, "window-change") == 0) {
1814 success = session_window_change_req(s);
1815 }
7899c98f 1816 return success;
e78a59f5 1817}
1818
1819void
1820session_set_fds(Session *s, int fdin, int fdout, int fderr)
1821{
1822 if (!compat20)
1823 fatal("session_set_fds: called for proto != 2.0");
1824 /*
1825 * now that have a child and a pipe to the child,
1826 * we can activate our channel and register the fd's
1827 */
1828 if (s->chanid == -1)
1829 fatal("no channel for session %d", s->self);
1830 channel_set_fds(s->chanid,
1831 fdout, fdin, fderr,
a22aff1f 1832 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ,
ea9700ba 1833 1,
1834 CHAN_SES_WINDOW_DEFAULT);
e78a59f5 1835}
1836
86066315 1837/*
1838 * Function to perform pty cleanup. Also called if we get aborted abnormally
1839 * (e.g., due to a dropped connection).
1840 */
1853d1ef 1841void
2362db19 1842session_pty_cleanup2(Session *s)
7368a6c8 1843{
86066315 1844 if (s == NULL) {
1845 error("session_pty_cleanup: no session");
1846 return;
1847 }
1848 if (s->ttyfd == -1)
7368a6c8 1849 return;
1850
0725ea77 1851 debug("session_pty_cleanup: session %d release %s", s->self, s->tty);
7368a6c8 1852
7368a6c8 1853 /* Record that the user has logged out. */
86066315 1854 if (s->pid != 0)
f3837bc6 1855 record_logout(s->pid, s->tty, s->pw->pw_name);
7368a6c8 1856
1857 /* Release the pseudo-tty. */
1853d1ef 1858 if (getuid() == 0)
1859 pty_release(s->tty);
7368a6c8 1860
1861 /*
1862 * Close the server side of the socket pairs. We must do this after
1863 * the pty cleanup, so that another process doesn't get this pty
1864 * while we're still cleaning up.
1865 */
1866 if (close(s->ptymaster) < 0)
1853d1ef 1867 error("close(s->ptymaster/%d): %s", s->ptymaster, strerror(errno));
efcc9957 1868
1869 /* unlink pty from session */
1870 s->ttyfd = -1;
7368a6c8 1871}
e78a59f5 1872
1853d1ef 1873void
2362db19 1874session_pty_cleanup(Session *s)
1853d1ef 1875{
2362db19 1876 PRIVSEP(session_pty_cleanup2(s));
1853d1ef 1877}
1878
6c723e7c 1879static char *
1880sig2name(int sig)
1881{
1882#define SSH_SIG(x) if (sig == SIG ## x) return #x
1883 SSH_SIG(ABRT);
1884 SSH_SIG(ALRM);
1885 SSH_SIG(FPE);
1886 SSH_SIG(HUP);
1887 SSH_SIG(ILL);
1888 SSH_SIG(INT);
1889 SSH_SIG(KILL);
1890 SSH_SIG(PIPE);
1891 SSH_SIG(QUIT);
1892 SSH_SIG(SEGV);
1893 SSH_SIG(TERM);
1894 SSH_SIG(USR1);
1895 SSH_SIG(USR2);
1896#undef SSH_SIG
1897 return "SIG@openssh.com";
1898}
1899
396c147e 1900static void
e78a59f5 1901session_exit_message(Session *s, int status)
1902{
1903 Channel *c;
5a4ae906 1904
1905 if ((c = channel_lookup(s->chanid)) == NULL)
86066315 1906 fatal("session_exit_message: session %d: no channel %d",
e78a59f5 1907 s->self, s->chanid);
c457707e 1908 debug("session_exit_message: session %d channel %d pid %ld",
1909 s->self, s->chanid, (long)s->pid);
e78a59f5 1910
1911 if (WIFEXITED(status)) {
5a4ae906 1912 channel_request_start(s->chanid, "exit-status", 0);
e78a59f5 1913 packet_put_int(WEXITSTATUS(status));
1914 packet_send();
1915 } else if (WIFSIGNALED(status)) {
5a4ae906 1916 channel_request_start(s->chanid, "exit-signal", 0);
6c723e7c 1917 packet_put_cstring(sig2name(WTERMSIG(status)));
a64009ad 1918#ifdef WCOREDUMP
e78a59f5 1919 packet_put_char(WCOREDUMP(status));
a64009ad 1920#else /* WCOREDUMP */
1921 packet_put_char(0);
1922#endif /* WCOREDUMP */
e78a59f5 1923 packet_put_cstring("");
1924 packet_put_cstring("");
1925 packet_send();
1926 } else {
1927 /* Some weird exit cause. Just exit. */
1928 packet_disconnect("wait returned status %04x.", status);
1929 }
1930
1931 /* disconnect channel */
1932 debug("session_exit_message: release channel %d", s->chanid);
1933 channel_cancel_cleanup(s->chanid);
9da5c3c9 1934 /*
1935 * emulate a write failure with 'chan_write_failed', nobody will be
1936 * interested in data we write.
1937 * Note that we must not call 'chan_read_failed', since there could
1938 * be some more data waiting in the pipe.
1939 */
0b242b12 1940 if (c->ostate != CHAN_OUTPUT_CLOSED)
1941 chan_write_failed(c);
e78a59f5 1942 s->chanid = -1;
1943}
1944
1853d1ef 1945void
86066315 1946session_close(Session *s)
e78a59f5 1947{
c457707e 1948 debug("session_close: session %d pid %ld", s->self, (long)s->pid);
2362db19 1949 if (s->ttyfd != -1)
86066315 1950 session_pty_cleanup(s);
e78a59f5 1951 if (s->term)
1952 xfree(s->term);
1953 if (s->display)
1954 xfree(s->display);
f9314d9a 1955 if (s->auth_display)
1956 xfree(s->auth_display);
e78a59f5 1957 if (s->auth_data)
1958 xfree(s->auth_data);
1959 if (s->auth_proto)
1960 xfree(s->auth_proto);
1961 s->used = 0;
1d1ffb87 1962 session_proctitle(s);
e78a59f5 1963}
1964
1965void
1966session_close_by_pid(pid_t pid, int status)
1967{
1968 Session *s = session_by_pid(pid);
1969 if (s == NULL) {
c457707e 1970 debug("session_close_by_pid: no session for pid %ld",
1971 (long)pid);
e78a59f5 1972 return;
1973 }
1974 if (s->chanid != -1)
1975 session_exit_message(s, status);
1976 session_close(s);
1977}
1978
1979/*
1980 * this is called when a channel dies before
1981 * the session 'child' itself dies
1982 */
1983void
1984session_close_by_channel(int id, void *arg)
1985{
1986 Session *s = session_by_channel(id);
1987 if (s == NULL) {
418e724c 1988 debug("session_close_by_channel: no session for id %d", id);
e78a59f5 1989 return;
1990 }
c457707e 1991 debug("session_close_by_channel: channel %d child %ld",
1992 id, (long)s->pid);
d5f24f94 1993 if (s->pid != 0) {
418e724c 1994 debug("session_close_by_channel: channel %d: has child", id);
efcc9957 1995 /*
1996 * delay detach of session, but release pty, since
1997 * the fd's to the child are already closed
1998 */
2362db19 1999 if (s->ttyfd != -1)
efcc9957 2000 session_pty_cleanup(s);
418e724c 2001 return;
e78a59f5 2002 }
418e724c 2003 /* detach by removing callback */
2004 channel_cancel_cleanup(s->chanid);
2005 s->chanid = -1;
d5f24f94 2006 session_close(s);
2007}
2008
2009void
1853d1ef 2010session_destroy_all(void (*closefunc)(Session *))
d5f24f94 2011{
2012 int i;
184eed6a 2013 for (i = 0; i < MAX_SESSIONS; i++) {
d5f24f94 2014 Session *s = &sessions[i];
1853d1ef 2015 if (s->used) {
2016 if (closefunc != NULL)
2017 closefunc(s);
2018 else
2019 session_close(s);
2020 }
d5f24f94 2021 }
e78a59f5 2022}
2023
396c147e 2024static char *
1d1ffb87 2025session_tty_list(void)
2026{
2027 static char buf[1024];
2028 int i;
d0104542 2029 char *cp;
2030
1d1ffb87 2031 buf[0] = '\0';
184eed6a 2032 for (i = 0; i < MAX_SESSIONS; i++) {
1d1ffb87 2033 Session *s = &sessions[i];
2034 if (s->used && s->ttyfd != -1) {
b6453d99 2035
d0104542 2036 if (strncmp(s->tty, "/dev/", 5) != 0) {
2037 cp = strrchr(s->tty, '/');
2038 cp = (cp == NULL) ? s->tty : cp + 1;
2039 } else
2040 cp = s->tty + 5;
b6453d99 2041
1d1ffb87 2042 if (buf[0] != '\0')
2043 strlcat(buf, ",", sizeof buf);
d0104542 2044 strlcat(buf, cp, sizeof buf);
1d1ffb87 2045 }
2046 }
2047 if (buf[0] == '\0')
2048 strlcpy(buf, "notty", sizeof buf);
2049 return buf;
2050}
2051
2052void
2053session_proctitle(Session *s)
2054{
2055 if (s->pw == NULL)
2056 error("no user for session %d", s->self);
2057 else
2058 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
2059}
2060
8dcd9d5c 2061int
2062session_setup_x11fwd(Session *s)
2063{
8dcd9d5c 2064 struct stat st;
c9d0ad9b 2065 char display[512], auth_display[512];
2066 char hostname[MAXHOSTNAMELEN];
8dcd9d5c 2067
2068 if (no_x11_forwarding_flag) {
2069 packet_send_debug("X11 forwarding disabled in user configuration file.");
2070 return 0;
2071 }
2072 if (!options.x11_forwarding) {
2073 debug("X11 forwarding disabled in server configuration file.");
2074 return 0;
2075 }
2076 if (!options.xauth_location ||
2077 (stat(options.xauth_location, &st) == -1)) {
2078 packet_send_debug("No xauth program; cannot forward with spoofing.");
2079 return 0;
2080 }
ff027d84 2081 if (options.use_login) {
2082 packet_send_debug("X11 forwarding disabled; "
2083 "not compatible with UseLogin=yes.");
2084 return 0;
2085 }
b44de2b1 2086 if (s->display != NULL) {
8dcd9d5c 2087 debug("X11 display already set.");
2088 return 0;
2089 }
57f228e8 2090 if (x11_create_display_inet(options.x11_display_offset,
2091 options.x11_use_localhost, s->single_connection,
2092 &s->display_number) == -1) {
b44de2b1 2093 debug("x11_create_display_inet failed.");
8dcd9d5c 2094 return 0;
2095 }
c9d0ad9b 2096
2097 /* Set up a suitable value for the DISPLAY variable. */
2098 if (gethostname(hostname, sizeof(hostname)) < 0)
2099 fatal("gethostname: %.100s", strerror(errno));
2100 /*
2101 * auth_display must be used as the displayname when the
2102 * authorization entry is added with xauth(1). This will be
2103 * different than the DISPLAY string for localhost displays.
2104 */
e6e573bd 2105 if (options.x11_use_localhost) {
57f228e8 2106 snprintf(display, sizeof display, "localhost:%u.%u",
c9d0ad9b 2107 s->display_number, s->screen);
57f228e8 2108 snprintf(auth_display, sizeof auth_display, "unix:%u.%u",
f9314d9a 2109 s->display_number, s->screen);
c9d0ad9b 2110 s->display = xstrdup(display);
f9314d9a 2111 s->auth_display = xstrdup(auth_display);
c9d0ad9b 2112 } else {
2113#ifdef IPADDR_IN_DISPLAY
2114 struct hostent *he;
2115 struct in_addr my_addr;
2116
2117 he = gethostbyname(hostname);
2118 if (he == NULL) {
2119 error("Can't get IP address for X11 DISPLAY.");
2120 packet_send_debug("Can't get IP address for X11 DISPLAY.");
2121 return 0;
2122 }
2123 memcpy(&my_addr, he->h_addr_list[0], sizeof(struct in_addr));
57f228e8 2124 snprintf(display, sizeof display, "%.50s:%u.%u", inet_ntoa(my_addr),
c9d0ad9b 2125 s->display_number, s->screen);
2126#else
57f228e8 2127 snprintf(display, sizeof display, "%.400s:%u.%u", hostname,
c9d0ad9b 2128 s->display_number, s->screen);
2129#endif
2130 s->display = xstrdup(display);
f9314d9a 2131 s->auth_display = xstrdup(display);
c9d0ad9b 2132 }
2133
8dcd9d5c 2134 return 1;
2135}
2136
396c147e 2137static void
59c97189 2138do_authenticated2(Authctxt *authctxt)
e78a59f5 2139{
57156994 2140 server_loop2(authctxt);
2362db19 2141}
2142
2143void
2144do_cleanup(Authctxt *authctxt)
2145{
2146 static int called = 0;
2147
2148 debug("do_cleanup");
2149
2150 /* no cleanup if we're in the child for login shell */
2151 if (is_child)
2152 return;
2153
2154 /* avoid double cleanup */
2155 if (called)
2156 return;
2157 called = 1;
2158
2159 if (authctxt == NULL)
2160 return;
2161#ifdef KRB5
2162 if (options.kerberos_ticket_cleanup &&
2163 authctxt->krb5_ctx)
2164 krb5_cleanup_proc(authctxt);
7364bd04 2165#endif
2362db19 2166
2167#ifdef GSSAPI
2168 if (compat20 && options.gss_cleanup_creds)
2169 ssh_gssapi_cleanup_creds();
2170#endif
2171
c6630044 2172#ifdef USE_PAM
2173 if (options.use_pam) {
2174 sshpam_cleanup();
2175 sshpam_thread_cleanup();
2176 }
2177#endif
2178
2362db19 2179 /* remove agent socket */
2180 auth_sock_cleanup_proc(authctxt->pw);
2181
2182 /*
2183 * Cleanup ptys/utmp only if privsep is disabled,
2184 * or if running in monitor.
2185 */
2186 if (!use_privsep || mm_is_monitor())
2187 session_destroy_all(session_pty_cleanup2);
e78a59f5 2188}
This page took 0.614899 seconds and 5 git commands to generate.