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