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