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