]> andersk Git - openssh.git/blame - session.c
- (djm) Fix server not exiting with jobs in background.
[openssh.git] / session.c
CommitLineData
7368a6c8 1/*
2 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
3 * All rights reserved
4 */
e78a59f5 5/*
6 * SSH2 support by Markus Friedl.
7 * Copyright (c) 2000 Markus Friedl. All rights reserved.
8 */
7368a6c8 9
10#include "includes.h"
b5e300c2 11RCSID("$OpenBSD: session.c,v 1.35 2000/09/04 19:07:21 markus Exp $");
7368a6c8 12
13#include "xmalloc.h"
14#include "ssh.h"
15#include "pty.h"
16#include "packet.h"
17#include "buffer.h"
18#include "cipher.h"
19#include "mpaux.h"
20#include "servconf.h"
21#include "uidswap.h"
22#include "compat.h"
23#include "channels.h"
24#include "nchan.h"
25
e78a59f5 26#include "bufaux.h"
27#include "ssh2.h"
28#include "auth.h"
38c295d6 29#include "auth-options.h"
e78a59f5 30
3206bb3b 31#ifdef WITH_IRIX_PROJECT
32#include <proj.h>
33#endif /* WITH_IRIX_PROJECT */
34
089fbbd2 35#if defined(HAVE_USERSEC_H)
36#include <usersec.h>
37#endif
38
4d33e531 39#ifdef HAVE_OSF_SIA
40# include <sia.h>
41# include <siad.h>
42#endif
43
3c62e7eb 44#ifdef HAVE_CYGWIN
45#include <windows.h>
46#include <sys/cygwin.h>
47#define is_winnt (GetVersion() < 0x80000000)
48#endif
49
3fcce26c 50/* AIX limits */
51#if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
2a2cb9e7 52# define S_UFSIZE_HARD S_UFSIZE "_hard"
53# define S_UCPU_HARD S_UCPU "_hard"
54# define S_UDATA_HARD S_UDATA "_hard"
55# define S_USTACK_HARD S_USTACK "_hard"
56# define S_URSS_HARD S_URSS "_hard"
57# define S_UCORE_HARD S_UCORE "_hard"
58# define S_UNOFILE_HARD S_UNOFILE "_hard"
3fcce26c 59#endif
60
2e73a022 61#ifdef HAVE_LOGIN_CAP
62#include <login_cap.h>
63#endif
64
7368a6c8 65/* types */
66
67#define TTYSZ 64
68typedef struct Session Session;
69struct Session {
70 int used;
71 int self;
0b242b12 72 int extended;
7368a6c8 73 struct passwd *pw;
74 pid_t pid;
75 /* tty */
76 char *term;
77 int ptyfd, ttyfd, ptymaster;
78 int row, col, xpixel, ypixel;
79 char tty[TTYSZ];
80 /* X11 */
81 char *display;
82 int screen;
83 char *auth_proto;
84 char *auth_data;
0b242b12 85 int single_connection;
7368a6c8 86 /* proto 2 */
87 int chanid;
88};
89
90/* func */
91
92Session *session_new(void);
93void session_set_fds(Session *s, int fdin, int fdout, int fderr);
94void session_pty_cleanup(Session *s);
1d1ffb87 95void session_proctitle(Session *s);
7368a6c8 96void do_exec_pty(Session *s, const char *command, struct passwd * pw);
97void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
c345cf9d 98void do_login(Session *s);
7368a6c8 99
100void
101do_child(const char *command, struct passwd * pw, const char *term,
102 const char *display, const char *auth_proto,
103 const char *auth_data, const char *ttyname);
104
105/* import */
106extern ServerOptions options;
3a6cb538 107#ifdef HAVE___PROGNAME
7368a6c8 108extern char *__progname;
3a6cb538 109#else /* HAVE___PROGNAME */
3fd95d9a 110static const char *__progname = "sshd";
3a6cb538 111#endif /* HAVE___PROGNAME */
112
7368a6c8 113extern int log_stderr;
114extern int debug_flag;
c345cf9d 115extern unsigned int utmp_len;
7368a6c8 116
089fbbd2 117extern int startup_pipe;
118
7368a6c8 119/* Local Xauthority file. */
120static char *xauthfile;
121
b5e300c2 122/* original command from peer. */
123char *original_command = NULL;
124
7368a6c8 125/* data */
126#define MAX_SESSIONS 10
127Session sessions[MAX_SESSIONS];
c1ef8333 128#ifdef WITH_AIXAUTHENTICATE
129/* AIX's lastlogin message, set in auth1.c */
130char *aixloginmsg;
131#endif /* WITH_AIXAUTHENTICATE */
7368a6c8 132
2e73a022 133#ifdef HAVE_LOGIN_CAP
134static login_cap_t *lc;
135#endif
136
7368a6c8 137/*
138 * Remove local Xauthority file.
139 */
140void
141xauthfile_cleanup_proc(void *ignore)
142{
143 debug("xauthfile_cleanup_proc called");
144
145 if (xauthfile != NULL) {
146 char *p;
147 unlink(xauthfile);
148 p = strrchr(xauthfile, '/');
149 if (p != NULL) {
150 *p = '\0';
151 rmdir(xauthfile);
152 }
153 xfree(xauthfile);
154 xauthfile = NULL;
155 }
156}
157
158/*
159 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
160 * dropped connection).
161 */
6ae2364d 162void
7368a6c8 163pty_cleanup_proc(void *session)
164{
165 Session *s=session;
166 if (s == NULL)
167 fatal("pty_cleanup_proc: no session");
168 debug("pty_cleanup_proc: %s", s->tty);
169
170 if (s->pid != 0) {
171 /* Record that the user has logged out. */
172 record_logout(s->pid, s->tty);
173 }
174
175 /* Release the pseudo-tty. */
176 pty_release(s->tty);
177}
178
179/*
180 * Prepares for an interactive session. This is called after the user has
181 * been successfully authenticated. During this message exchange, pseudo
182 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
183 * are requested, etc.
184 */
6ae2364d 185void
7368a6c8 186do_authenticated(struct passwd * pw)
187{
188 Session *s;
b5e300c2 189 int type, fd;
7368a6c8 190 int compression_level = 0, enable_compression_after_reply = 0;
191 int have_pty = 0;
192 char *command;
193 int n_bytes;
194 int plen;
195 unsigned int proto_len, data_len, dlen;
196
197 /*
198 * Cancel the alarm we set to limit the time taken for
199 * authentication.
200 */
201 alarm(0);
3f7a7e4a 202 if (startup_pipe != -1) {
5540ea9b 203 close(startup_pipe);
3f7a7e4a 204 startup_pipe = -1;
205 }
7368a6c8 206
207 /*
208 * Inform the channel mechanism that we are the server side and that
209 * the client may request to connect to any port at all. (The user
210 * could do it anyway, and we wouldn\'t know what is permitted except
211 * by the client telling us, so we can equally well trust the client
212 * not to request anything bogus.)
213 */
214 if (!no_port_forwarding_flag)
215 channel_permit_all_opens();
216
217 s = session_new();
0b242b12 218 s->pw = pw;
7368a6c8 219
2e73a022 220#ifdef HAVE_LOGIN_CAP
221 if ((lc = login_getclass(pw->pw_class)) == NULL) {
222 error("unable to get login class");
223 return;
224 }
225#endif
226
7368a6c8 227 /*
228 * We stay in this loop until the client requests to execute a shell
229 * or a command.
230 */
231 for (;;) {
232 int success = 0;
233
234 /* Get a packet from the client. */
235 type = packet_read(&plen);
236
237 /* Process the packet. */
238 switch (type) {
239 case SSH_CMSG_REQUEST_COMPRESSION:
240 packet_integrity_check(plen, 4, type);
241 compression_level = packet_get_int();
242 if (compression_level < 1 || compression_level > 9) {
243 packet_send_debug("Received illegal compression level %d.",
244 compression_level);
245 break;
246 }
247 /* Enable compression after we have responded with SUCCESS. */
248 enable_compression_after_reply = 1;
249 success = 1;
250 break;
251
252 case SSH_CMSG_REQUEST_PTY:
253 if (no_pty_flag) {
254 debug("Allocating a pty not permitted for this authentication.");
255 break;
256 }
257 if (have_pty)
258 packet_disconnect("Protocol error: you already have a pty.");
259
260 debug("Allocating pty.");
261
262 /* Allocate a pty and open it. */
263 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
264 sizeof(s->tty))) {
265 error("Failed to allocate pty.");
266 break;
267 }
268 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
269 pty_setowner(pw, s->tty);
270
271 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
272 s->term = packet_get_string(&dlen);
273 packet_integrity_check(dlen, strlen(s->term), type);
274 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
275 /* Remaining bytes */
276 n_bytes = plen - (4 + dlen + 4 * 4);
277
278 if (strcmp(s->term, "") == 0) {
279 xfree(s->term);
280 s->term = NULL;
281 }
282 /* Get window size from the packet. */
283 s->row = packet_get_int();
284 s->col = packet_get_int();
285 s->xpixel = packet_get_int();
286 s->ypixel = packet_get_int();
287 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
288
289 /* Get tty modes from the packet. */
290 tty_parse_modes(s->ttyfd, &n_bytes);
291 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
292
1d1ffb87 293 session_proctitle(s);
294
7368a6c8 295 /* Indicate that we now have a pty. */
296 success = 1;
297 have_pty = 1;
298 break;
299
300 case SSH_CMSG_X11_REQUEST_FORWARDING:
301 if (!options.x11_forwarding) {
302 packet_send_debug("X11 forwarding disabled in server configuration file.");
303 break;
304 }
6fc1e9f3 305 if (!options.xauth_location) {
306 packet_send_debug("No xauth program; cannot forward with spoofing.");
307 break;
308 }
7368a6c8 309 if (no_x11_forwarding_flag) {
310 packet_send_debug("X11 forwarding not permitted for this authentication.");
311 break;
312 }
313 debug("Received request for X11 forwarding with auth spoofing.");
314 if (s->display != NULL)
315 packet_disconnect("Protocol error: X11 display already set.");
316
317 s->auth_proto = packet_get_string(&proto_len);
318 s->auth_data = packet_get_string(&data_len);
319 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
320
321 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
322 s->screen = packet_get_int();
323 else
324 s->screen = 0;
325 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
326
327 if (s->display == NULL)
328 break;
329
330 /* Setup to always have a local .Xauthority. */
331 xauthfile = xmalloc(MAXPATHLEN);
332 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
333 temporarily_use_uid(pw->pw_uid);
334 if (mkdtemp(xauthfile) == NULL) {
335 restore_uid();
336 error("private X11 dir: mkdtemp %s failed: %s",
337 xauthfile, strerror(errno));
338 xfree(xauthfile);
339 xauthfile = NULL;
0b242b12 340 /* XXXX remove listening channels */
7368a6c8 341 break;
342 }
343 strlcat(xauthfile, "/cookies", MAXPATHLEN);
b5e300c2 344 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
345 if (fd >= 0)
346 close(fd);
7368a6c8 347 restore_uid();
348 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
349 success = 1;
350 break;
7368a6c8 351
352 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
353 if (no_agent_forwarding_flag || compat13) {
354 debug("Authentication agent forwarding not permitted for this authentication.");
355 break;
356 }
357 debug("Received authentication agent forwarding request.");
6fc1e9f3 358 success = auth_input_request_forwarding(pw);
7368a6c8 359 break;
360
361 case SSH_CMSG_PORT_FORWARD_REQUEST:
362 if (no_port_forwarding_flag) {
363 debug("Port forwarding not permitted for this authentication.");
364 break;
365 }
366 debug("Received TCP/IP port forwarding request.");
1d1ffb87 367 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
7368a6c8 368 success = 1;
369 break;
370
371 case SSH_CMSG_MAX_PACKET_SIZE:
372 if (packet_set_maxsize(packet_get_int()) > 0)
373 success = 1;
374 break;
375
376 case SSH_CMSG_EXEC_SHELL:
377 case SSH_CMSG_EXEC_CMD:
378 /* Set interactive/non-interactive mode. */
379 packet_set_interactive(have_pty || s->display != NULL,
380 options.keepalives);
381
382 if (type == SSH_CMSG_EXEC_CMD) {
383 command = packet_get_string(&dlen);
384 debug("Exec command '%.500s'", command);
385 packet_integrity_check(plen, 4 + dlen, type);
386 } else {
387 command = NULL;
388 packet_integrity_check(plen, 0, type);
389 }
390 if (forced_command != NULL) {
b5e300c2 391 original_command = command;
7368a6c8 392 command = forced_command;
393 debug("Forced command '%.500s'", forced_command);
394 }
395 if (have_pty)
396 do_exec_pty(s, command, pw);
397 else
398 do_exec_no_pty(s, command, pw);
399
400 if (command != NULL)
401 xfree(command);
402 /* Cleanup user's local Xauthority file. */
403 if (xauthfile)
404 xauthfile_cleanup_proc(NULL);
405 return;
406
407 default:
408 /*
409 * Any unknown messages in this phase are ignored,
410 * and a failure message is returned.
411 */
412 log("Unknown packet type received after authentication: %d", type);
413 }
414 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
415 packet_send();
416 packet_write_wait();
417
418 /* Enable compression now that we have replied if appropriate. */
419 if (enable_compression_after_reply) {
420 enable_compression_after_reply = 0;
421 packet_start_compression(compression_level);
422 }
423 }
424}
425
426/*
427 * This is called to fork and execute a command when we have no tty. This
428 * will call do_child from the child, and server_loop from the parent after
429 * setting up file descriptors and such.
430 */
6ae2364d 431void
7368a6c8 432do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
433{
434 int pid;
435
436#ifdef USE_PIPES
437 int pin[2], pout[2], perr[2];
438 /* Allocate pipes for communicating with the program. */
439 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
440 packet_disconnect("Could not create pipes: %.100s",
441 strerror(errno));
442#else /* USE_PIPES */
443 int inout[2], err[2];
444 /* Uses socket pairs to communicate with the program. */
445 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
446 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
447 packet_disconnect("Could not create socket pairs: %.100s",
448 strerror(errno));
449#endif /* USE_PIPES */
450 if (s == NULL)
451 fatal("do_exec_no_pty: no session");
452
1d1ffb87 453 session_proctitle(s);
7368a6c8 454
455#ifdef USE_PAM
456 do_pam_setcred();
457#endif /* USE_PAM */
458
459 /* Fork the child. */
460 if ((pid = fork()) == 0) {
461 /* Child. Reinitialize the log since the pid has changed. */
462 log_init(__progname, options.log_level, options.log_facility, log_stderr);
463
464 /*
465 * Create a new session and process group since the 4.4BSD
466 * setlogin() affects the entire process group.
467 */
468 if (setsid() < 0)
469 error("setsid failed: %.100s", strerror(errno));
470
471#ifdef USE_PIPES
472 /*
473 * Redirect stdin. We close the parent side of the socket
474 * pair, and make the child side the standard input.
475 */
476 close(pin[1]);
477 if (dup2(pin[0], 0) < 0)
478 perror("dup2 stdin");
479 close(pin[0]);
480
481 /* Redirect stdout. */
482 close(pout[0]);
483 if (dup2(pout[1], 1) < 0)
484 perror("dup2 stdout");
485 close(pout[1]);
486
487 /* Redirect stderr. */
488 close(perr[0]);
489 if (dup2(perr[1], 2) < 0)
490 perror("dup2 stderr");
491 close(perr[1]);
492#else /* USE_PIPES */
493 /*
494 * Redirect stdin, stdout, and stderr. Stdin and stdout will
495 * use the same socket, as some programs (particularly rdist)
496 * seem to depend on it.
497 */
498 close(inout[1]);
499 close(err[1]);
500 if (dup2(inout[0], 0) < 0) /* stdin */
501 perror("dup2 stdin");
502 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
503 perror("dup2 stdout");
504 if (dup2(err[0], 2) < 0) /* stderr */
505 perror("dup2 stderr");
506#endif /* USE_PIPES */
507
508 /* Do processing for the child (exec command etc). */
509 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
510 /* NOTREACHED */
511 }
3c62e7eb 512#ifdef HAVE_CYGWIN
513 if (is_winnt)
514 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
515#endif
7368a6c8 516 if (pid < 0)
517 packet_disconnect("fork failed: %.100s", strerror(errno));
518 s->pid = pid;
519#ifdef USE_PIPES
520 /* We are the parent. Close the child sides of the pipes. */
521 close(pin[0]);
522 close(pout[1]);
523 close(perr[1]);
524
e78a59f5 525 if (compat20) {
0b242b12 526 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
e78a59f5 527 } else {
528 /* Enter the interactive session. */
529 server_loop(pid, pin[1], pout[0], perr[0]);
530 /* server_loop has closed pin[1], pout[1], and perr[1]. */
531 }
7368a6c8 532#else /* USE_PIPES */
533 /* We are the parent. Close the child sides of the socket pairs. */
534 close(inout[0]);
535 close(err[0]);
536
537 /*
538 * Enter the interactive session. Note: server_loop must be able to
539 * handle the case that fdin and fdout are the same.
540 */
e78a59f5 541 if (compat20) {
0b242b12 542 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
e78a59f5 543 } else {
544 server_loop(pid, inout[1], inout[1], err[1]);
545 /* server_loop has closed inout[1] and err[1]. */
546 }
7368a6c8 547#endif /* USE_PIPES */
548}
549
550/*
551 * This is called to fork and execute a command when we have a tty. This
552 * will call do_child from the child, and server_loop from the parent after
553 * setting up file descriptors, controlling tty, updating wtmp, utmp,
554 * lastlog, and other such operations.
555 */
6ae2364d 556void
7368a6c8 557do_exec_pty(Session *s, const char *command, struct passwd * pw)
558{
7368a6c8 559 int fdout, ptyfd, ttyfd, ptymaster;
7368a6c8 560 pid_t pid;
7368a6c8 561
562 if (s == NULL)
563 fatal("do_exec_pty: no session");
564 ptyfd = s->ptyfd;
565 ttyfd = s->ttyfd;
566
7368a6c8 567#ifdef USE_PAM
568 do_pam_session(pw->pw_name, s->tty);
569 do_pam_setcred();
570#endif /* USE_PAM */
571
572 /* Fork the child. */
573 if ((pid = fork()) == 0) {
c345cf9d 574 /* Child. Reinitialize the log because the pid has changed. */
7368a6c8 575 log_init(__progname, options.log_level, options.log_facility, log_stderr);
576
577 /* Close the master side of the pseudo tty. */
578 close(ptyfd);
579
580 /* Make the pseudo tty our controlling tty. */
581 pty_make_controlling_tty(&ttyfd, s->tty);
582
583 /* Redirect stdin from the pseudo tty. */
584 if (dup2(ttyfd, fileno(stdin)) < 0)
585 error("dup2 stdin failed: %.100s", strerror(errno));
586
587 /* Redirect stdout to the pseudo tty. */
588 if (dup2(ttyfd, fileno(stdout)) < 0)
589 error("dup2 stdin failed: %.100s", strerror(errno));
590
591 /* Redirect stderr to the pseudo tty. */
592 if (dup2(ttyfd, fileno(stderr)) < 0)
593 error("dup2 stdin failed: %.100s", strerror(errno));
594
595 /* Close the extra descriptor for the pseudo tty. */
596 close(ttyfd);
597
c345cf9d 598 /* record login, etc. similar to login(1) */
599 if (command == NULL && !options.use_login)
600 do_login(s);
7368a6c8 601
7368a6c8 602 /* Do common processing for the child, such as execing the command. */
71276795 603 do_child(command, pw, s->term, s->display, s->auth_proto,
604 s->auth_data, s->tty);
7368a6c8 605 /* NOTREACHED */
606 }
3c62e7eb 607#ifdef HAVE_CYGWIN
608 if (is_winnt)
609 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
610#endif
7368a6c8 611 if (pid < 0)
612 packet_disconnect("fork failed: %.100s", strerror(errno));
613 s->pid = pid;
614
615 /* Parent. Close the slave side of the pseudo tty. */
616 close(ttyfd);
617
618 /*
619 * Create another descriptor of the pty master side for use as the
620 * standard input. We could use the original descriptor, but this
621 * simplifies code in server_loop. The descriptor is bidirectional.
622 */
623 fdout = dup(ptyfd);
624 if (fdout < 0)
625 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
626
627 /* we keep a reference to the pty master */
628 ptymaster = dup(ptyfd);
629 if (ptymaster < 0)
630 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
631 s->ptymaster = ptymaster;
632
633 /* Enter interactive session. */
e78a59f5 634 if (compat20) {
635 session_set_fds(s, ptyfd, fdout, -1);
636 } else {
637 server_loop(pid, ptyfd, fdout, -1);
638 /* server_loop _has_ closed ptyfd and fdout. */
639 session_pty_cleanup(s);
640 }
7368a6c8 641}
642
c345cf9d 643const char *
644get_remote_name_or_ip(void)
645{
646 static const char *remote = "";
647 if (utmp_len > 0)
648 remote = get_canonical_hostname();
649 if (utmp_len == 0 || strlen(remote) > utmp_len)
650 remote = get_remote_ipaddr();
651 return remote;
652}
653
654/* administrative, login(1)-like work */
655void
656do_login(Session *s)
657{
658 FILE *f;
659 char *time_string;
660 char buf[256];
b5e300c2 661 char hostname[MAXHOSTNAMELEN];
c345cf9d 662 socklen_t fromlen;
663 struct sockaddr_storage from;
664 struct stat st;
665 time_t last_login_time;
666 struct passwd * pw = s->pw;
667 pid_t pid = getpid();
668
669 /*
670 * Get IP address of client. If the connection is not a socket, let
671 * the address be 0.0.0.0.
672 */
673 memset(&from, 0, sizeof(from));
674 if (packet_connection_is_on_socket()) {
675 fromlen = sizeof(from);
676 if (getpeername(packet_get_connection_in(),
677 (struct sockaddr *) & from, &fromlen) < 0) {
678 debug("getpeername: %.100s", strerror(errno));
679 fatal_cleanup();
680 }
681 }
682
b5e300c2 683 /* Get the time and hostname when the user last logged in. */
684 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
685 hostname, sizeof(hostname));
686
c345cf9d 687 /* Record that there was a login on that tty from the remote host. */
688 record_login(pid, s->tty, pw->pw_name, pw->pw_uid,
689 get_remote_name_or_ip(), (struct sockaddr *)&from);
690
691 /* Done if .hushlogin exists. */
692 snprintf(buf, sizeof(buf), "%.200s/.hushlogin", pw->pw_dir);
2e73a022 693#ifdef HAVE_LOGIN_CAP
694 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
695#else
c345cf9d 696 if (stat(buf, &st) >= 0)
2e73a022 697#endif
c345cf9d 698 return;
699
700#ifdef USE_PAM
701 print_pam_messages();
702#endif /* USE_PAM */
703#ifdef WITH_AIXAUTHENTICATE
704 if (aixloginmsg && *aixloginmsg)
705 printf("%s\n", aixloginmsg);
706#endif /* WITH_AIXAUTHENTICATE */
707
c345cf9d 708 if (last_login_time != 0) {
709 time_string = ctime(&last_login_time);
710 if (strchr(time_string, '\n'))
711 *strchr(time_string, '\n') = 0;
712 if (strcmp(buf, "") == 0)
713 printf("Last login: %s\r\n", time_string);
714 else
715 printf("Last login: %s from %s\r\n", time_string, buf);
716 }
717 if (options.print_motd) {
2e73a022 718#ifdef HAVE_LOGIN_CAP
719 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
720 "/etc/motd"), "r");
721#else
c345cf9d 722 f = fopen("/etc/motd", "r");
2e73a022 723#endif
c345cf9d 724 if (f) {
725 while (fgets(buf, sizeof(buf), f))
726 fputs(buf, stdout);
727 fclose(f);
728 }
729 }
730}
731
7368a6c8 732/*
733 * Sets the value of the given variable in the environment. If the variable
734 * already exists, its value is overriden.
735 */
6ae2364d 736void
7368a6c8 737child_set_env(char ***envp, unsigned int *envsizep, const char *name,
738 const char *value)
739{
740 unsigned int i, namelen;
741 char **env;
742
743 /*
744 * Find the slot where the value should be stored. If the variable
745 * already exists, we reuse the slot; otherwise we append a new slot
746 * at the end of the array, expanding if necessary.
747 */
748 env = *envp;
749 namelen = strlen(name);
750 for (i = 0; env[i]; i++)
751 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
752 break;
753 if (env[i]) {
754 /* Reuse the slot. */
755 xfree(env[i]);
756 } else {
757 /* New variable. Expand if necessary. */
758 if (i >= (*envsizep) - 1) {
759 (*envsizep) += 50;
760 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
761 }
762 /* Need to set the NULL pointer at end of array beyond the new slot. */
763 env[i + 1] = NULL;
764 }
765
766 /* Allocate space and format the variable in the appropriate slot. */
767 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
768 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
769}
770
771/*
772 * Reads environment variables from the given file and adds/overrides them
773 * into the environment. If the file does not exist, this does nothing.
774 * Otherwise, it must consist of empty lines, comments (line starts with '#')
775 * and assignments of the form name=value. No other forms are allowed.
776 */
6ae2364d 777void
7368a6c8 778read_environment_file(char ***env, unsigned int *envsize,
779 const char *filename)
780{
781 FILE *f;
782 char buf[4096];
783 char *cp, *value;
784
785 f = fopen(filename, "r");
786 if (!f)
787 return;
788
789 while (fgets(buf, sizeof(buf), f)) {
790 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
791 ;
792 if (!*cp || *cp == '#' || *cp == '\n')
793 continue;
794 if (strchr(cp, '\n'))
795 *strchr(cp, '\n') = '\0';
796 value = strchr(cp, '=');
797 if (value == NULL) {
798 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
799 continue;
800 }
71276795 801 /*
802 * Replace the equals sign by nul, and advance value to
803 * the value string.
804 */
7368a6c8 805 *value = '\0';
806 value++;
807 child_set_env(env, envsize, cp, value);
808 }
809 fclose(f);
810}
811
812#ifdef USE_PAM
813/*
814 * Sets any environment variables which have been specified by PAM
815 */
816void do_pam_environment(char ***env, int *envsize)
817{
818 char *equals, var_name[512], var_val[512];
819 char **pam_env;
820 int i;
821
822 if ((pam_env = fetch_pam_environment()) == NULL)
823 return;
824
825 for(i = 0; pam_env[i] != NULL; i++) {
826 if ((equals = strstr(pam_env[i], "=")) == NULL)
827 continue;
828
829 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
830 memset(var_name, '\0', sizeof(var_name));
831 memset(var_val, '\0', sizeof(var_val));
832
833 strncpy(var_name, pam_env[i], equals - pam_env[i]);
834 strcpy(var_val, equals + 1);
835
836 debug("PAM environment: %s=%s", var_name, var_val);
837
838 child_set_env(env, envsize, var_name, var_val);
839 }
840 }
841}
842#endif /* USE_PAM */
843
5fa45897 844#if defined(HAVE_GETUSERATTR)
845/*
846 * AIX-specific login initialisation
847 */
848void set_limit(char *user, char *soft, char *hard, int resource, int mult)
849{
850 struct rlimit rlim;
56118702 851 int slim, hlim;
5fa45897 852
853 getrlimit(resource, &rlim);
854
56118702 855 slim = 0;
856 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
857 if (slim < 0) {
858 rlim.rlim_cur = RLIM_INFINITY;
859 } else if (slim != 0) {
860 /* See the wackiness below */
861 if (rlim.rlim_cur == slim * mult)
862 slim = 0;
863 else
864 rlim.rlim_cur = slim * mult;
865 }
866 }
5fa45897 867
56118702 868 hlim = 0;
869 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
870 if (hlim < 0) {
871 rlim.rlim_max = RLIM_INFINITY;
872 } else if (hlim != 0) {
873 rlim.rlim_max = hlim * mult;
874 }
875 }
5fa45897 876
56118702 877 /*
878 * XXX For cpu and fsize the soft limit is set to the hard limit
879 * if the hard limit is left at its default value and the soft limit
880 * is changed from its default value, either by requesting it
881 * (slim == 0) or by setting it to the current default. At least
882 * that's how rlogind does it. If you're confused you're not alone.
883 * Bug or feature? AIX 4.3.1.2
884 */
885 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
886 && hlim == 0 && slim != 0)
887 rlim.rlim_max = rlim.rlim_cur;
888 /* A specified hard limit limits the soft limit */
889 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
890 rlim.rlim_cur = rlim.rlim_max;
891 /* A soft limit can increase a hard limit */
892 else if (rlim.rlim_cur > rlim.rlim_max)
5fa45897 893 rlim.rlim_max = rlim.rlim_cur;
894
895 if (setrlimit(resource, &rlim) != 0)
56118702 896 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
5fa45897 897}
898
899void set_limits_from_userattr(char *user)
900{
901 int mask;
902 char buf[16];
903
904 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
905 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
906 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
907 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
908 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
909 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
910#if defined(S_UNOFILE)
911 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
912#endif
913
914 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
915 /* Convert decimal to octal */
916 (void) snprintf(buf, sizeof(buf), "%d", mask);
917 if (sscanf(buf, "%o", &mask) == 1)
918 umask(mask);
919 }
920}
921#endif /* defined(HAVE_GETUSERATTR) */
922
7368a6c8 923/*
924 * Performs common processing for the child, such as setting up the
925 * environment, closing extra file descriptors, setting the user and group
926 * ids, and executing the command or shell.
927 */
6ae2364d 928void
7368a6c8 929do_child(const char *command, struct passwd * pw, const char *term,
930 const char *display, const char *auth_proto,
931 const char *auth_data, const char *ttyname)
932{
b5e300c2 933 const char *shell, *hostname = NULL, *cp = NULL;
7368a6c8 934 char buf[256];
6fc1e9f3 935 char cmd[1024];
2e73a022 936 FILE *f = NULL;
7368a6c8 937 unsigned int envsize, i;
938 char **env;
939 extern char **environ;
940 struct stat st;
941 char *argv[10];
3206bb3b 942#ifdef WITH_IRIX_PROJECT
943 prid_t projid;
944#endif /* WITH_IRIX_PROJECT */
7368a6c8 945
fa649821 946 /* login(1) is only called if we execute the login shell */
947 if (options.use_login && command != NULL)
948 options.use_login = 0;
949
7368a6c8 950#ifndef USE_PAM /* pam_nologin handles this */
2e73a022 951 if (!options.use_login) {
952# ifdef HAVE_LOGIN_CAP
953 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
954 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
955 _PATH_NOLOGIN), "r");
956# else /* HAVE_LOGIN_CAP */
957 if (pw->pw_uid)
958 f = fopen(_PATH_NOLOGIN, "r");
959# endif /* HAVE_LOGIN_CAP */
960 if (f) {
961 /* /etc/nologin exists. Print its contents and exit. */
962 while (fgets(buf, sizeof(buf), f))
963 fputs(buf, stderr);
964 fclose(f);
7368a6c8 965 exit(254);
2e73a022 966 }
7368a6c8 967 }
968#endif /* USE_PAM */
969
2e73a022 970 /* Set login name, uid, gid, and groups. */
7368a6c8 971 /* Login(1) does this as well, and it needs uid 0 for the "-h"
972 switch, so we let login(1) to this for us. */
973 if (!options.use_login) {
4d33e531 974#ifdef HAVE_OSF_SIA
975 extern char **saved_argv;
976 extern int saved_argc;
977 char *host = get_canonical_hostname ();
978
979 if (sia_become_user(NULL, saved_argc, saved_argv, host,
980 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
981 SIASUCCESS) {
982 perror("sia_become_user");
983 exit(1);
984 }
985 if (setreuid(geteuid(), geteuid()) < 0) {
986 perror("setreuid");
987 exit(1);
988 }
989#else /* HAVE_OSF_SIA */
3c62e7eb 990#ifdef HAVE_CYGWIN
991 if (is_winnt) {
992#else
7368a6c8 993 if (getuid() == 0 || geteuid() == 0) {
3c62e7eb 994#endif
2e73a022 995# ifdef HAVE_GETUSERATTR
5fa45897 996 set_limits_from_userattr(pw->pw_name);
2e73a022 997# endif /* HAVE_GETUSERATTR */
998# ifdef HAVE_LOGIN_CAP
999 if (setusercontext(lc, pw, pw->pw_uid,
1000 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1001 perror("unable to set user context");
1002 exit(1);
1003 }
1004# else /* HAVE_LOGIN_CAP */
1005 if (setlogin(pw->pw_name) < 0)
1006 error("setlogin failed: %s", strerror(errno));
7368a6c8 1007 if (setgid(pw->pw_gid) < 0) {
1008 perror("setgid");
1009 exit(1);
1010 }
1011 /* Initialize the group list. */
1012 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1013 perror("initgroups");
1014 exit(1);
1015 }
1016 endgrent();
2e73a022 1017# ifdef WITH_IRIX_ARRAY
3206bb3b 1018 /* initialize array session */
1019 if (newarraysess() != 0)
1020 fatal("Failed to set up new array session: %.100s",
1021 strerror(errno));
2e73a022 1022# endif /* WITH_IRIX_ARRAY */
1023# ifdef WITH_IRIX_PROJECT
3206bb3b 1024 /* initialize irix project info */
1025 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1026 debug("Failed to get project id, using projid 0");
1027 projid = 0;
1028 }
3206bb3b 1029 if (setprid(projid))
1030 fatal("Failed to initialize project %d for %s: %.100s",
1031 (int)projid, pw->pw_name, strerror(errno));
2e73a022 1032# endif /* WITH_IRIX_PROJECT */
7368a6c8 1033 /* Permanently switch to the desired uid. */
1034 permanently_set_uid(pw->pw_uid);
2e73a022 1035# endif /* HAVE_LOGIN_CAP */
7368a6c8 1036 }
2e73a022 1037#endif /* HAVE_OSF_SIA */
1038
3c62e7eb 1039#ifdef HAVE_CYGWIN
1040 if (is_winnt)
1041#endif
7368a6c8 1042 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
14a9a859 1043 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
7368a6c8 1044 }
1045 /*
1046 * Get the shell from the password data. An empty shell field is
1047 * legal, and means /bin/sh.
1048 */
1049 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
2e73a022 1050#ifdef HAVE_LOGIN_CAP
1051 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1052#endif
7368a6c8 1053
1054#ifdef AFS
1055 /* Try to get AFS tokens for the local cell. */
1056 if (k_hasafs()) {
1057 char cell[64];
1058
1059 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1060 krb_afslog(cell, 0);
1061
1062 krb_afslog(0, 0);
1063 }
1064#endif /* AFS */
1065
1066 /* Initialize the environment. */
1067 envsize = 100;
1068 env = xmalloc(envsize * sizeof(char *));
1069 env[0] = NULL;
1070
3c62e7eb 1071#ifdef HAVE_CYGWIN
1072 /*
1073 * The Windows environment contains some setting which are
1074 * important for a running system. They must not be dropped.
1075 */
1076 {
1077 char **ep;
1078 for (ep = environ; *ep; ++ep) {
1079 char *esp = strchr(*ep, '=');
1080 *esp = '\0';
1081 child_set_env(&env, &envsize, *ep, esp + 1);
1082 *esp = '=';
1083 }
1084 }
1085#endif
1086
7368a6c8 1087 if (!options.use_login) {
1088 /* Set basic environment. */
1089 child_set_env(&env, &envsize, "USER", pw->pw_name);
1090 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1091 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2e73a022 1092#ifdef HAVE_LOGIN_CAP
1093 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1094 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1095#else
3c62e7eb 1096#ifndef HAVE_CYGWIN
1097 /*
1098 * There's no standard path on Windows. The path contains
1099 * important components pointing to the system directories,
1100 * needed for loading shared libraries. So the path better
1101 * remains intact here.
1102 */
7368a6c8 1103 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
3c62e7eb 1104#endif
2e73a022 1105#endif
7368a6c8 1106
1107 snprintf(buf, sizeof buf, "%.200s/%.50s",
1108 _PATH_MAILDIR, pw->pw_name);
1109 child_set_env(&env, &envsize, "MAIL", buf);
1110
1111 /* Normal systems set SHELL by default. */
1112 child_set_env(&env, &envsize, "SHELL", shell);
1113 }
1114 if (getenv("TZ"))
1115 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1116
1117 /* Set custom environment options from RSA authentication. */
1118 while (custom_environment) {
1119 struct envstring *ce = custom_environment;
1120 char *s = ce->s;
1121 int i;
1122 for (i = 0; s[i] != '=' && s[i]; i++);
1123 if (s[i] == '=') {
1124 s[i] = 0;
1125 child_set_env(&env, &envsize, s, s + i + 1);
1126 }
1127 custom_environment = ce->next;
1128 xfree(ce->s);
1129 xfree(ce);
1130 }
1131
1132 snprintf(buf, sizeof buf, "%.50s %d %d",
1133 get_remote_ipaddr(), get_remote_port(), get_local_port());
1134 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1135
1136 if (ttyname)
1137 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1138 if (term)
1139 child_set_env(&env, &envsize, "TERM", term);
1140 if (display)
1141 child_set_env(&env, &envsize, "DISPLAY", display);
b5e300c2 1142 if (original_command)
1143 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1144 original_command);
7368a6c8 1145
1146#ifdef _AIX
1147 {
1148 char *authstate,*krb5cc;
1149
1150 if ((authstate = getenv("AUTHSTATE")) != NULL)
1151 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
1152
1153 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
1154 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
1155 }
1156#endif
1157
1158#ifdef KRB4
1159 {
1160 extern char *ticket;
1161
1162 if (ticket)
1163 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1164 }
1165#endif /* KRB4 */
1166
1167#ifdef USE_PAM
1168 /* Pull in any environment variables that may have been set by PAM. */
1169 do_pam_environment(&env, &envsize);
1170#endif /* USE_PAM */
1171
1172 read_environment_file(&env,&envsize,"/etc/environment");
1173
1174 if (xauthfile)
1175 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1176 if (auth_get_socket_name() != NULL)
1177 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1178 auth_get_socket_name());
1179
1180 /* read $HOME/.ssh/environment. */
1181 if (!options.use_login) {
71276795 1182 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1183 pw->pw_dir);
7368a6c8 1184 read_environment_file(&env, &envsize, buf);
1185 }
1186 if (debug_flag) {
1187 /* dump the environment */
1188 fprintf(stderr, "Environment:\n");
1189 for (i = 0; env[i]; i++)
1190 fprintf(stderr, " %.200s\n", env[i]);
1191 }
2e73a022 1192 /* we have to stash the hostname before we close our socket. */
1193 if (options.use_login)
1194 hostname = get_remote_name_or_ip();
7368a6c8 1195 /*
1196 * Close the connection descriptors; note that this is the child, and
1197 * the server will still have the socket open, and it is important
1198 * that we do not shutdown it. Note that the descriptors cannot be
1199 * closed before building the environment, as we call
1200 * get_remote_ipaddr there.
1201 */
1202 if (packet_get_connection_in() == packet_get_connection_out())
1203 close(packet_get_connection_in());
1204 else {
1205 close(packet_get_connection_in());
1206 close(packet_get_connection_out());
1207 }
1208 /*
1209 * Close all descriptors related to channels. They will still remain
1210 * open in the parent.
1211 */
1212 /* XXX better use close-on-exec? -markus */
1213 channel_close_all();
1214
1215 /*
1216 * Close any extra file descriptors. Note that there may still be
1217 * descriptors left by system functions. They will be closed later.
1218 */
1219 endpwent();
1220
1221 /*
1222 * Close any extra open file descriptors so that we don\'t have them
1223 * hanging around in clients. Note that we want to do this after
1224 * initgroups, because at least on Solaris 2.3 it leaves file
1225 * descriptors open.
1226 */
1227 for (i = 3; i < 64; i++)
1228 close(i);
1229
1230 /* Change current directory to the user\'s home directory. */
2e73a022 1231 if (chdir(pw->pw_dir) < 0) {
7368a6c8 1232 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1233 pw->pw_dir, strerror(errno));
2e73a022 1234#ifdef HAVE_LOGIN_CAP
1235 if (login_getcapbool(lc, "requirehome", 0))
1236 exit(1);
1237#endif
1238 }
7368a6c8 1239
1240 /*
1241 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1242 * xauth are run in the proper environment.
1243 */
1244 environ = env;
1245
1246 /*
1247 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1248 * in this order).
1249 */
1250 if (!options.use_login) {
1251 if (stat(SSH_USER_RC, &st) >= 0) {
1252 if (debug_flag)
30228d7c 1253 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_USER_RC);
7368a6c8 1254
30228d7c 1255 f = popen(_PATH_BSHELL " " SSH_USER_RC, "w");
7368a6c8 1256 if (f) {
1257 if (auth_proto != NULL && auth_data != NULL)
1258 fprintf(f, "%s %s\n", auth_proto, auth_data);
1259 pclose(f);
1260 } else
1261 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1262 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1263 if (debug_flag)
30228d7c 1264 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_SYSTEM_RC);
7368a6c8 1265
30228d7c 1266 f = popen(_PATH_BSHELL " " SSH_SYSTEM_RC, "w");
7368a6c8 1267 if (f) {
1268 if (auth_proto != NULL && auth_data != NULL)
1269 fprintf(f, "%s %s\n", auth_proto, auth_data);
1270 pclose(f);
1271 } else
1272 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
6fc1e9f3 1273 } else if (options.xauth_location != NULL) {
7368a6c8 1274 /* Add authority data to .Xauthority if appropriate. */
1275 if (auth_proto != NULL && auth_data != NULL) {
29611d9c 1276 char *screen = strchr(display, ':');
1277 if (debug_flag) {
71276795 1278 fprintf(stderr,
1279 "Running %.100s add %.100s %.100s %.100s\n",
6fc1e9f3 1280 options.xauth_location, display,
1281 auth_proto, auth_data);
3c62e7eb 1282#ifndef HAVE_CYGWIN
29611d9c 1283 if (screen != NULL)
71276795 1284 fprintf(stderr,
1285 "Adding %.*s/unix%s %s %s\n",
14a9a859 1286 (int)(screen-display), display,
71276795 1287 screen, auth_proto, auth_data);
3c62e7eb 1288#endif
29611d9c 1289 }
6fc1e9f3 1290 snprintf(cmd, sizeof cmd, "%s -q -",
1291 options.xauth_location);
1292 f = popen(cmd, "w");
7368a6c8 1293 if (f) {
71276795 1294 fprintf(f, "add %s %s %s\n", display,
1295 auth_proto, auth_data);
3c62e7eb 1296#ifndef HAVE_CYGWIN
29611d9c 1297 if (screen != NULL)
1298 fprintf(f, "add %.*s/unix%s %s %s\n",
14a9a859 1299 (int)(screen-display), display,
71276795 1300 screen, auth_proto, auth_data);
3c62e7eb 1301#endif
7368a6c8 1302 pclose(f);
6fc1e9f3 1303 } else {
1304 fprintf(stderr, "Could not run %s\n",
1305 cmd);
1306 }
7368a6c8 1307 }
1308 }
7368a6c8 1309 /* Get the last component of the shell name. */
1310 cp = strrchr(shell, '/');
1311 if (cp)
1312 cp++;
1313 else
1314 cp = shell;
1315 }
1316 /*
1317 * If we have no command, execute the shell. In this case, the shell
1318 * name to be passed in argv[0] is preceded by '-' to indicate that
1319 * this is a login shell.
1320 */
1321 if (!command) {
1322 if (!options.use_login) {
1323 char buf[256];
1324
1325 /*
1326 * Check for mail if we have a tty and it was enabled
1327 * in server options.
1328 */
1329 if (ttyname && options.check_mail) {
1330 char *mailbox;
1331 struct stat mailstat;
1332 mailbox = getenv("MAIL");
1333 if (mailbox != NULL) {
71276795 1334 if (stat(mailbox, &mailstat) != 0 ||
1335 mailstat.st_size == 0)
7368a6c8 1336 printf("No mail.\n");
1337 else if (mailstat.st_mtime < mailstat.st_atime)
1338 printf("You have mail.\n");
1339 else
1340 printf("You have new mail.\n");
1341 }
1342 }
1343 /* Start the shell. Set initial character to '-'. */
1344 buf[0] = '-';
1345 strncpy(buf + 1, cp, sizeof(buf) - 1);
1346 buf[sizeof(buf) - 1] = 0;
1347
1348 /* Execute the shell. */
1349 argv[0] = buf;
1350 argv[1] = NULL;
1351 execve(shell, argv, env);
1352
1353 /* Executing the shell failed. */
1354 perror(shell);
1355 exit(1);
1356
1357 } else {
1358 /* Launch login(1). */
1359
2e73a022 1360 execl(LOGIN_PROGRAM, "login", "-h", hostname,
c345cf9d 1361 "-p", "-f", "--", pw->pw_name, NULL);
7368a6c8 1362
1363 /* Login couldn't be executed, die. */
1364
1365 perror("login");
1366 exit(1);
1367 }
1368 }
1369 /*
1370 * Execute the command using the user's shell. This uses the -c
1371 * option to execute the command.
1372 */
1373 argv[0] = (char *) cp;
1374 argv[1] = "-c";
1375 argv[2] = (char *) command;
1376 argv[3] = NULL;
1377 execve(shell, argv, env);
1378 perror(shell);
1379 exit(1);
1380}
1381
1382Session *
1383session_new(void)
1384{
1385 int i;
1386 static int did_init = 0;
1387 if (!did_init) {
1388 debug("session_new: init");
1389 for(i = 0; i < MAX_SESSIONS; i++) {
1390 sessions[i].used = 0;
1391 sessions[i].self = i;
1392 }
1393 did_init = 1;
1394 }
1395 for(i = 0; i < MAX_SESSIONS; i++) {
1396 Session *s = &sessions[i];
1397 if (! s->used) {
1398 s->pid = 0;
0b242b12 1399 s->extended = 0;
7368a6c8 1400 s->chanid = -1;
1401 s->ptyfd = -1;
1402 s->ttyfd = -1;
1403 s->term = NULL;
1404 s->pw = NULL;
1405 s->display = NULL;
1406 s->screen = 0;
1407 s->auth_data = NULL;
1408 s->auth_proto = NULL;
1409 s->used = 1;
0b242b12 1410 s->pw = NULL;
7368a6c8 1411 debug("session_new: session %d", i);
1412 return s;
1413 }
1414 }
1415 return NULL;
1416}
1417
1418void
1419session_dump(void)
1420{
1421 int i;
1422 for(i = 0; i < MAX_SESSIONS; i++) {
1423 Session *s = &sessions[i];
1424 debug("dump: used %d session %d %p channel %d pid %d",
1425 s->used,
1426 s->self,
1427 s,
1428 s->chanid,
1429 s->pid);
1430 }
1431}
1432
e78a59f5 1433int
1434session_open(int chanid)
1435{
1436 Session *s = session_new();
1437 debug("session_open: channel %d", chanid);
1438 if (s == NULL) {
1439 error("no more sessions");
1440 return 0;
1441 }
e78a59f5 1442 s->pw = auth_get_user();
1443 if (s->pw == NULL)
0b242b12 1444 fatal("no user for session %i", s->self);
1445 debug("session_open: session %d: link with channel %d", s->self, chanid);
1446 s->chanid = chanid;
e78a59f5 1447 return 1;
1448}
1449
1450Session *
1451session_by_channel(int id)
1452{
1453 int i;
1454 for(i = 0; i < MAX_SESSIONS; i++) {
1455 Session *s = &sessions[i];
1456 if (s->used && s->chanid == id) {
1457 debug("session_by_channel: session %d channel %d", i, id);
1458 return s;
1459 }
1460 }
1461 debug("session_by_channel: unknown channel %d", id);
1462 session_dump();
1463 return NULL;
1464}
1465
1466Session *
1467session_by_pid(pid_t pid)
1468{
1469 int i;
1470 debug("session_by_pid: pid %d", pid);
1471 for(i = 0; i < MAX_SESSIONS; i++) {
1472 Session *s = &sessions[i];
1473 if (s->used && s->pid == pid)
1474 return s;
1475 }
1476 error("session_by_pid: unknown pid %d", pid);
1477 session_dump();
1478 return NULL;
1479}
1480
1481int
1482session_window_change_req(Session *s)
1483{
1484 s->col = packet_get_int();
1485 s->row = packet_get_int();
1486 s->xpixel = packet_get_int();
1487 s->ypixel = packet_get_int();
6ae2364d 1488 packet_done();
e78a59f5 1489 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1490 return 1;
1491}
1492
1493int
1494session_pty_req(Session *s)
1495{
1496 unsigned int len;
6ae2364d 1497 char *term_modes; /* encoded terminal modes */
e78a59f5 1498
38c295d6 1499 if (no_pty_flag)
1500 return 0;
e78a59f5 1501 if (s->ttyfd != -1)
6ae2364d 1502 return 0;
e78a59f5 1503 s->term = packet_get_string(&len);
1504 s->col = packet_get_int();
1505 s->row = packet_get_int();
1506 s->xpixel = packet_get_int();
1507 s->ypixel = packet_get_int();
6ae2364d 1508 term_modes = packet_get_string(&len);
1509 packet_done();
e78a59f5 1510
1511 if (strcmp(s->term, "") == 0) {
1512 xfree(s->term);
1513 s->term = NULL;
1514 }
1515 /* Allocate a pty and open it. */
1516 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1517 xfree(s->term);
1518 s->term = NULL;
1519 s->ptyfd = -1;
1520 s->ttyfd = -1;
1521 error("session_pty_req: session %d alloc failed", s->self);
6ae2364d 1522 xfree(term_modes);
1523 return 0;
e78a59f5 1524 }
1525 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1526 /*
1527 * Add a cleanup function to clear the utmp entry and record logout
1528 * time in case we call fatal() (e.g., the connection gets closed).
1529 */
1530 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1531 pty_setowner(s->pw, s->tty);
1532 /* Get window size from the packet. */
1533 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1534
1d1ffb87 1535 session_proctitle(s);
1536
35484284 1537 /* XXX parse and set terminal modes */
1538 xfree(term_modes);
e78a59f5 1539 return 1;
1540}
1541
0b242b12 1542int
1543session_subsystem_req(Session *s)
1544{
1545 unsigned int len;
1546 int success = 0;
1547 char *subsys = packet_get_string(&len);
38c295d6 1548 int i;
0b242b12 1549
1550 packet_done();
1551 log("subsystem request for %s", subsys);
1552
38c295d6 1553 for (i = 0; i < options.num_subsystems; i++) {
1554 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1555 debug("subsystem: exec() %s", options.subsystem_command[i]);
1556 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1557 success = 1;
1558 }
1559 }
1560
1561 if (!success)
1562 log("subsystem request for %s failed, subsystem not found", subsys);
1563
0b242b12 1564 xfree(subsys);
1565 return success;
1566}
1567
1568int
1569session_x11_req(Session *s)
1570{
b5e300c2 1571 int fd;
089fbbd2 1572 if (no_x11_forwarding_flag) {
38c295d6 1573 debug("X11 forwarding disabled in user configuration file.");
1574 return 0;
1575 }
0b242b12 1576 if (!options.x11_forwarding) {
1577 debug("X11 forwarding disabled in server configuration file.");
1578 return 0;
1579 }
1580 if (xauthfile != NULL) {
1581 debug("X11 fwd already started.");
1582 return 0;
1583 }
1584
1585 debug("Received request for X11 forwarding with auth spoofing.");
1586 if (s->display != NULL)
1587 packet_disconnect("Protocol error: X11 display already set.");
1588
1589 s->single_connection = packet_get_char();
1590 s->auth_proto = packet_get_string(NULL);
1591 s->auth_data = packet_get_string(NULL);
1592 s->screen = packet_get_int();
1593 packet_done();
1594
1595 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1596 if (s->display == NULL) {
1597 xfree(s->auth_proto);
1598 xfree(s->auth_data);
1599 return 0;
1600 }
1601 xauthfile = xmalloc(MAXPATHLEN);
1602 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1603 temporarily_use_uid(s->pw->pw_uid);
1604 if (mkdtemp(xauthfile) == NULL) {
1605 restore_uid();
1606 error("private X11 dir: mkdtemp %s failed: %s",
1607 xauthfile, strerror(errno));
1608 xfree(xauthfile);
1609 xauthfile = NULL;
1610 xfree(s->auth_proto);
1611 xfree(s->auth_data);
1612 /* XXXX remove listening channels */
1613 return 0;
1614 }
1615 strlcat(xauthfile, "/cookies", MAXPATHLEN);
b5e300c2 1616 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1617 if (fd >= 0)
1618 close(fd);
0b242b12 1619 restore_uid();
1620 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1621 return 1;
1622}
1623
38c295d6 1624int
1625session_shell_req(Session *s)
1626{
1627 /* if forced_command == NULL, the shell is execed */
1628 char *shell = forced_command;
1629 packet_done();
1630 s->extended = 1;
1631 if (s->ttyfd == -1)
1632 do_exec_no_pty(s, shell, s->pw);
1633 else
1634 do_exec_pty(s, shell, s->pw);
1635 return 1;
1636}
1637
1638int
1639session_exec_req(Session *s)
1640{
1641 unsigned int len;
1642 char *command = packet_get_string(&len);
1643 packet_done();
1644 if (forced_command) {
b5e300c2 1645 original_command = command;
38c295d6 1646 command = forced_command;
1647 debug("Forced command '%.500s'", forced_command);
1648 }
1649 s->extended = 1;
1650 if (s->ttyfd == -1)
1651 do_exec_no_pty(s, command, s->pw);
1652 else
1653 do_exec_pty(s, command, s->pw);
1654 if (forced_command == NULL)
1655 xfree(command);
1656 return 1;
1657}
1658
e78a59f5 1659void
1660session_input_channel_req(int id, void *arg)
1661{
1662 unsigned int len;
1663 int reply;
1664 int success = 0;
1665 char *rtype;
1666 Session *s;
1667 Channel *c;
1668
1669 rtype = packet_get_string(&len);
1670 reply = packet_get_char();
1671
1672 s = session_by_channel(id);
1673 if (s == NULL)
1674 fatal("session_input_channel_req: channel %d: no session", id);
1675 c = channel_lookup(id);
1676 if (c == NULL)
1677 fatal("session_input_channel_req: channel %d: bad channel", id);
1678
1679 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1680 s->self, id, rtype, reply);
1681
1682 /*
1683 * a session is in LARVAL state until a shell
1684 * or programm is executed
1685 */
1686 if (c->type == SSH_CHANNEL_LARVAL) {
1687 if (strcmp(rtype, "shell") == 0) {
38c295d6 1688 success = session_shell_req(s);
e78a59f5 1689 } else if (strcmp(rtype, "exec") == 0) {
38c295d6 1690 success = session_exec_req(s);
e78a59f5 1691 } else if (strcmp(rtype, "pty-req") == 0) {
35484284 1692 success = session_pty_req(s);
0b242b12 1693 } else if (strcmp(rtype, "x11-req") == 0) {
1694 success = session_x11_req(s);
1695 } else if (strcmp(rtype, "subsystem") == 0) {
1696 success = session_subsystem_req(s);
e78a59f5 1697 }
1698 }
1699 if (strcmp(rtype, "window-change") == 0) {
1700 success = session_window_change_req(s);
1701 }
1702
1703 if (reply) {
1704 packet_start(success ?
1705 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1706 packet_put_int(c->remote_id);
1707 packet_send();
1708 }
1709 xfree(rtype);
1710}
1711
1712void
1713session_set_fds(Session *s, int fdin, int fdout, int fderr)
1714{
1715 if (!compat20)
1716 fatal("session_set_fds: called for proto != 2.0");
1717 /*
1718 * now that have a child and a pipe to the child,
1719 * we can activate our channel and register the fd's
1720 */
1721 if (s->chanid == -1)
1722 fatal("no channel for session %d", s->self);
1723 channel_set_fds(s->chanid,
1724 fdout, fdin, fderr,
1725 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1726}
1727
7368a6c8 1728void
1729session_pty_cleanup(Session *s)
1730{
1731 if (s == NULL || s->ttyfd == -1)
1732 return;
1733
1734 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1735
1736 /* Cancel the cleanup function. */
1737 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1738
1739 /* Record that the user has logged out. */
1740 record_logout(s->pid, s->tty);
1741
1742 /* Release the pseudo-tty. */
1743 pty_release(s->tty);
1744
1745 /*
1746 * Close the server side of the socket pairs. We must do this after
1747 * the pty cleanup, so that another process doesn't get this pty
1748 * while we're still cleaning up.
1749 */
1750 if (close(s->ptymaster) < 0)
1751 error("close(s->ptymaster): %s", strerror(errno));
1752}
e78a59f5 1753
1754void
1755session_exit_message(Session *s, int status)
1756{
1757 Channel *c;
1758 if (s == NULL)
1759 fatal("session_close: no session");
1760 c = channel_lookup(s->chanid);
1761 if (c == NULL)
1762 fatal("session_close: session %d: no channel %d",
1763 s->self, s->chanid);
1764 debug("session_exit_message: session %d channel %d pid %d",
1765 s->self, s->chanid, s->pid);
1766
1767 if (WIFEXITED(status)) {
1768 channel_request_start(s->chanid,
1769 "exit-status", 0);
1770 packet_put_int(WEXITSTATUS(status));
1771 packet_send();
1772 } else if (WIFSIGNALED(status)) {
1773 channel_request_start(s->chanid,
1774 "exit-signal", 0);
1775 packet_put_int(WTERMSIG(status));
a64009ad 1776#ifdef WCOREDUMP
e78a59f5 1777 packet_put_char(WCOREDUMP(status));
a64009ad 1778#else /* WCOREDUMP */
1779 packet_put_char(0);
1780#endif /* WCOREDUMP */
e78a59f5 1781 packet_put_cstring("");
1782 packet_put_cstring("");
1783 packet_send();
1784 } else {
1785 /* Some weird exit cause. Just exit. */
1786 packet_disconnect("wait returned status %04x.", status);
1787 }
1788
1789 /* disconnect channel */
1790 debug("session_exit_message: release channel %d", s->chanid);
1791 channel_cancel_cleanup(s->chanid);
9da5c3c9 1792 /*
1793 * emulate a write failure with 'chan_write_failed', nobody will be
1794 * interested in data we write.
1795 * Note that we must not call 'chan_read_failed', since there could
1796 * be some more data waiting in the pipe.
1797 */
0b242b12 1798 if (c->ostate != CHAN_OUTPUT_CLOSED)
1799 chan_write_failed(c);
e78a59f5 1800 s->chanid = -1;
1801}
1802
1803void
1804session_free(Session *s)
1805{
1806 debug("session_free: session %d pid %d", s->self, s->pid);
1807 if (s->term)
1808 xfree(s->term);
1809 if (s->display)
1810 xfree(s->display);
1811 if (s->auth_data)
1812 xfree(s->auth_data);
1813 if (s->auth_proto)
1814 xfree(s->auth_proto);
1815 s->used = 0;
1816}
1817
1818void
1819session_close(Session *s)
1820{
1821 session_pty_cleanup(s);
1822 session_free(s);
1d1ffb87 1823 session_proctitle(s);
e78a59f5 1824}
1825
1826void
1827session_close_by_pid(pid_t pid, int status)
1828{
1829 Session *s = session_by_pid(pid);
1830 if (s == NULL) {
1831 debug("session_close_by_pid: no session for pid %d", s->pid);
1832 return;
1833 }
1834 if (s->chanid != -1)
1835 session_exit_message(s, status);
1836 session_close(s);
1837}
1838
1839/*
1840 * this is called when a channel dies before
1841 * the session 'child' itself dies
1842 */
1843void
1844session_close_by_channel(int id, void *arg)
1845{
1846 Session *s = session_by_channel(id);
1847 if (s == NULL) {
1848 debug("session_close_by_channel: no session for channel %d", id);
1849 return;
1850 }
1851 /* disconnect channel */
1852 channel_cancel_cleanup(s->chanid);
1853 s->chanid = -1;
1854
1855 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1856 if (s->pid == 0) {
1857 /* close session immediately */
1858 session_close(s);
1859 } else {
1860 /* notify child, delay session cleanup */
f528fdf2 1861 if (s->pid <= 1)
512ad3c0 1862 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1863 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
e78a59f5 1864 error("session_close_by_channel: kill %d: %s",
1865 s->pid, strerror(errno));
1866 }
1867}
1868
1d1ffb87 1869char *
1870session_tty_list(void)
1871{
1872 static char buf[1024];
1873 int i;
1874 buf[0] = '\0';
1875 for(i = 0; i < MAX_SESSIONS; i++) {
1876 Session *s = &sessions[i];
1877 if (s->used && s->ttyfd != -1) {
1878 if (buf[0] != '\0')
1879 strlcat(buf, ",", sizeof buf);
1880 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1881 }
1882 }
1883 if (buf[0] == '\0')
1884 strlcpy(buf, "notty", sizeof buf);
1885 return buf;
1886}
1887
1888void
1889session_proctitle(Session *s)
1890{
1891 if (s->pw == NULL)
1892 error("no user for session %d", s->self);
1893 else
1894 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1895}
1896
e78a59f5 1897void
1898do_authenticated2(void)
1899{
0b65b628 1900#ifdef HAVE_LOGIN_CAP
2e73a022 1901 struct passwd *pw;
0b65b628 1902#endif
2e73a022 1903
e78a59f5 1904 /*
1905 * Cancel the alarm we set to limit the time taken for
1906 * authentication.
1907 */
1908 alarm(0);
3f7a7e4a 1909 if (startup_pipe != -1) {
5540ea9b 1910 close(startup_pipe);
3f7a7e4a 1911 startup_pipe = -1;
1912 }
2e73a022 1913#ifdef HAVE_LOGIN_CAP
1914 pw = auth_get_user();
1915 if ((lc = login_getclass(pw->pw_class)) == NULL) {
1916 error("unable to get login class");
1917 return;
1918 }
1919#endif
e78a59f5 1920 server_loop2();
34bce9a5 1921 if (xauthfile)
1922 xauthfile_cleanup_proc(NULL);
e78a59f5 1923}
This page took 3.126372 seconds and 5 git commands to generate.