blob: ca12a4f733e39df6200957112d861e69004cb01b [file] [log] [blame]
Damien Millerb38eff82000-04-01 11:09:21 +10001/*
2 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
3 * All rights reserved
Damien Millere4340be2000-09-16 13:29:08 +11004 *
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 *
Damien Millerefb4afe2000-04-12 18:45:05 +100011 * SSH2 support by Markus Friedl.
12 * Copyright (c) 2000 Markus Friedl. All rights reserved.
Damien Millere4340be2000-09-16 13:29:08 +110013 *
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.
Damien Millerefb4afe2000-04-12 18:45:05 +100033 */
Damien Millerb38eff82000-04-01 11:09:21 +100034
35#include "includes.h"
Damien Millere4340be2000-09-16 13:29:08 +110036RCSID("$OpenBSD: session.c,v 1.37 2000/09/07 20:27:53 deraadt Exp $");
Damien Millerb38eff82000-04-01 11:09:21 +100037
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
Damien Millerefb4afe2000-04-12 18:45:05 +100051#include "bufaux.h"
52#include "ssh2.h"
53#include "auth.h"
Damien Millerf6d9e222000-06-18 14:50:44 +100054#include "auth-options.h"
Damien Millerefb4afe2000-04-12 18:45:05 +100055
Damien Miller91606b12000-06-28 08:22:29 +100056#ifdef WITH_IRIX_PROJECT
57#include <proj.h>
58#endif /* WITH_IRIX_PROJECT */
59
Damien Miller37023962000-07-11 17:31:38 +100060#if defined(HAVE_USERSEC_H)
61#include <usersec.h>
62#endif
63
Damien Millerb8c656e2000-06-28 15:22:41 +100064#ifdef HAVE_OSF_SIA
65# include <sia.h>
66# include <siad.h>
67#endif
68
Damien Millerbac2d8a2000-09-05 16:13:06 +110069#ifdef HAVE_CYGWIN
70#include <windows.h>
71#include <sys/cygwin.h>
72#define is_winnt (GetVersion() < 0x80000000)
73#endif
74
Damien Millerd17b8d52000-08-09 14:42:28 +100075/* AIX limits */
76#if defined(HAVE_GETUSERATTR) && !defined(S_UFSIZE_HARD) && defined(S_UFSIZE)
Damien Miller0da2eaa2000-08-15 11:32:59 +100077# 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"
Damien Millerd17b8d52000-08-09 14:42:28 +100084#endif
85
Damien Millerad833b32000-08-23 10:46:23 +100086#ifdef HAVE_LOGIN_CAP
87#include <login_cap.h>
88#endif
89
Damien Millerb38eff82000-04-01 11:09:21 +100090/* types */
91
92#define TTYSZ 64
93typedef struct Session Session;
94struct Session {
95 int used;
96 int self;
Damien Millerbd483e72000-04-30 10:00:53 +100097 int extended;
Damien Millerb38eff82000-04-01 11:09:21 +100098 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;
Damien Millerbd483e72000-04-30 10:00:53 +1000110 int single_connection;
Damien Millerb38eff82000-04-01 11:09:21 +1000111 /* 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);
Damien Millere247cc42000-05-07 12:03:14 +1000120void session_proctitle(Session *s);
Damien Millerb38eff82000-04-01 11:09:21 +1000121void do_exec_pty(Session *s, const char *command, struct passwd * pw);
122void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
Damien Miller942da032000-08-18 13:59:06 +1000123void do_login(Session *s);
Damien Millerb38eff82000-04-01 11:09:21 +1000124
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;
Damien Miller06d84b72000-04-21 16:13:07 +1000132#ifdef HAVE___PROGNAME
Damien Millerb38eff82000-04-01 11:09:21 +1000133extern char *__progname;
Damien Miller06d84b72000-04-21 16:13:07 +1000134#else /* HAVE___PROGNAME */
Damien Miller70fb6712000-05-01 20:59:50 +1000135static const char *__progname = "sshd";
Damien Miller06d84b72000-04-21 16:13:07 +1000136#endif /* HAVE___PROGNAME */
137
Damien Millerb38eff82000-04-01 11:09:21 +1000138extern int log_stderr;
139extern int debug_flag;
Damien Miller942da032000-08-18 13:59:06 +1000140extern unsigned int utmp_len;
Damien Millerb38eff82000-04-01 11:09:21 +1000141
Damien Miller37023962000-07-11 17:31:38 +1000142extern int startup_pipe;
143
Damien Millerb38eff82000-04-01 11:09:21 +1000144/* Local Xauthority file. */
145static char *xauthfile;
146
Damien Miller7b28dc52000-09-05 13:34:53 +1100147/* original command from peer. */
148char *original_command = NULL;
149
Damien Millerb38eff82000-04-01 11:09:21 +1000150/* data */
151#define MAX_SESSIONS 10
152Session sessions[MAX_SESSIONS];
Damien Miller15e7d4b2000-09-29 10:57:35 +1100153static int num_used_sessions;
154
Damien Millerd2c208a2000-05-17 22:00:02 +1000155#ifdef WITH_AIXAUTHENTICATE
156/* AIX's lastlogin message, set in auth1.c */
157char *aixloginmsg;
158#endif /* WITH_AIXAUTHENTICATE */
Damien Millerb38eff82000-04-01 11:09:21 +1000159
Damien Millerad833b32000-08-23 10:46:23 +1000160#ifdef HAVE_LOGIN_CAP
161static login_cap_t *lc;
162#endif
163
Damien Millerb38eff82000-04-01 11:09:21 +1000164/*
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 */
Damien Miller4af51302000-04-16 11:18:38 +1000189void
Damien Millerb38eff82000-04-01 11:09:21 +1000190pty_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 */
Damien Miller4af51302000-04-16 11:18:38 +1000212void
Damien Millerb38eff82000-04-01 11:09:21 +1000213do_authenticated(struct passwd * pw)
214{
215 Session *s;
Damien Miller7b28dc52000-09-05 13:34:53 +1100216 int type, fd;
Damien Millerb38eff82000-04-01 11:09:21 +1000217 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);
Damien Miller182ee6e2000-07-12 09:45:27 +1000229 if (startup_pipe != -1) {
Damien Miller4d97ba22000-07-11 18:15:50 +1000230 close(startup_pipe);
Damien Miller182ee6e2000-07-12 09:45:27 +1000231 startup_pipe = -1;
232 }
Damien Millerb38eff82000-04-01 11:09:21 +1000233
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();
Damien Millerbd483e72000-04-30 10:00:53 +1000245 s->pw = pw;
Damien Millerb38eff82000-04-01 11:09:21 +1000246
Damien Millerad833b32000-08-23 10:46:23 +1000247#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
Damien Millerb38eff82000-04-01 11:09:21 +1000254 /*
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
Damien Millere247cc42000-05-07 12:03:14 +1000320 session_proctitle(s);
321
Damien Millerb38eff82000-04-01 11:09:21 +1000322 /* 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 }
Damien Miller0c043c12000-06-07 21:22:38 +1000332 if (!options.xauth_location) {
333 packet_send_debug("No xauth program; cannot forward with spoofing.");
334 break;
335 }
Damien Millerb38eff82000-04-01 11:09:21 +1000336 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;
Damien Millerbd483e72000-04-30 10:00:53 +1000367 /* XXXX remove listening channels */
Damien Millerb38eff82000-04-01 11:09:21 +1000368 break;
369 }
370 strlcat(xauthfile, "/cookies", MAXPATHLEN);
Damien Miller7b28dc52000-09-05 13:34:53 +1100371 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
372 if (fd >= 0)
373 close(fd);
Damien Millerb38eff82000-04-01 11:09:21 +1000374 restore_uid();
375 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
376 success = 1;
377 break;
Damien Millerb38eff82000-04-01 11:09:21 +1000378
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.");
Damien Miller0c043c12000-06-07 21:22:38 +1000385 success = auth_input_request_forwarding(pw);
Damien Millerb38eff82000-04-01 11:09:21 +1000386 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.");
Damien Millere247cc42000-05-07 12:03:14 +1000394 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
Damien Millerb38eff82000-04-01 11:09:21 +1000395 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) {
Damien Miller7b28dc52000-09-05 13:34:53 +1100418 original_command = command;
Damien Millerb38eff82000-04-01 11:09:21 +1000419 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 */
Damien Miller4af51302000-04-16 11:18:38 +1000458void
Damien Millerb38eff82000-04-01 11:09:21 +1000459do_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
Damien Millere247cc42000-05-07 12:03:14 +1000480 session_proctitle(s);
Damien Millerb38eff82000-04-01 11:09:21 +1000481
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 }
Damien Millerbac2d8a2000-09-05 16:13:06 +1100539#ifdef HAVE_CYGWIN
540 if (is_winnt)
541 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
542#endif
Damien Millerb38eff82000-04-01 11:09:21 +1000543 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
Damien Millerefb4afe2000-04-12 18:45:05 +1000552 if (compat20) {
Damien Millerbd483e72000-04-30 10:00:53 +1000553 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
Damien Millerefb4afe2000-04-12 18:45:05 +1000554 } 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 }
Damien Millerb38eff82000-04-01 11:09:21 +1000559#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 */
Damien Millerefb4afe2000-04-12 18:45:05 +1000568 if (compat20) {
Damien Millerbd483e72000-04-30 10:00:53 +1000569 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
Damien Millerefb4afe2000-04-12 18:45:05 +1000570 } else {
571 server_loop(pid, inout[1], inout[1], err[1]);
572 /* server_loop has closed inout[1] and err[1]. */
573 }
Damien Millerb38eff82000-04-01 11:09:21 +1000574#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 */
Damien Miller4af51302000-04-16 11:18:38 +1000583void
Damien Millerb38eff82000-04-01 11:09:21 +1000584do_exec_pty(Session *s, const char *command, struct passwd * pw)
585{
Damien Millerb38eff82000-04-01 11:09:21 +1000586 int fdout, ptyfd, ttyfd, ptymaster;
Damien Millerb38eff82000-04-01 11:09:21 +1000587 pid_t pid;
Damien Millerb38eff82000-04-01 11:09:21 +1000588
589 if (s == NULL)
590 fatal("do_exec_pty: no session");
591 ptyfd = s->ptyfd;
592 ttyfd = s->ttyfd;
593
Damien Millerb38eff82000-04-01 11:09:21 +1000594#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) {
Damien Miller942da032000-08-18 13:59:06 +1000601 /* Child. Reinitialize the log because the pid has changed. */
Damien Millerb38eff82000-04-01 11:09:21 +1000602 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
Damien Miller942da032000-08-18 13:59:06 +1000625 /* record login, etc. similar to login(1) */
626 if (command == NULL && !options.use_login)
627 do_login(s);
Damien Millerb38eff82000-04-01 11:09:21 +1000628
Damien Millerb38eff82000-04-01 11:09:21 +1000629 /* Do common processing for the child, such as execing the command. */
Damien Millerb1715dc2000-05-30 13:44:51 +1000630 do_child(command, pw, s->term, s->display, s->auth_proto,
631 s->auth_data, s->tty);
Damien Millerb38eff82000-04-01 11:09:21 +1000632 /* NOTREACHED */
633 }
Damien Millerbac2d8a2000-09-05 16:13:06 +1100634#ifdef HAVE_CYGWIN
635 if (is_winnt)
636 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
637#endif
Damien Millerb38eff82000-04-01 11:09:21 +1000638 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. */
Damien Millerefb4afe2000-04-12 18:45:05 +1000661 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 }
Damien Millerb38eff82000-04-01 11:09:21 +1000668}
669
Damien Miller942da032000-08-18 13:59:06 +1000670const 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];
Damien Miller7b28dc52000-09-05 13:34:53 +1100688 char hostname[MAXHOSTNAMELEN];
Damien Miller942da032000-08-18 13:59:06 +1000689 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
Damien Miller7b28dc52000-09-05 13:34:53 +1100710 /* 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
Damien Millere4340be2000-09-16 13:29:08 +1100714 /* 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
Damien Miller942da032000-08-18 13:59:06 +1000719 /* 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);
Damien Millerad833b32000-08-23 10:46:23 +1000725#ifdef HAVE_LOGIN_CAP
726 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
727#else
Damien Miller942da032000-08-18 13:59:06 +1000728 if (stat(buf, &st) >= 0)
Damien Millerad833b32000-08-23 10:46:23 +1000729#endif
Damien Miller942da032000-08-18 13:59:06 +1000730 return;
731
732#ifdef USE_PAM
733 print_pam_messages();
Damien Miller9d5705a2000-09-16 16:09:27 +1100734 /* If password change is needed, do it now. */
735 do_pam_chauthtok();
Damien Miller942da032000-08-18 13:59:06 +1000736#endif /* USE_PAM */
737#ifdef WITH_AIXAUTHENTICATE
738 if (aixloginmsg && *aixloginmsg)
739 printf("%s\n", aixloginmsg);
740#endif /* WITH_AIXAUTHENTICATE */
741
Damien Miller942da032000-08-18 13:59:06 +1000742 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
Damien Millere4340be2000-09-16 13:29:08 +1100749 printf("Last login: %s from %s\r\n", time_string, hostname);
Damien Miller942da032000-08-18 13:59:06 +1000750 }
751 if (options.print_motd) {
Damien Millerad833b32000-08-23 10:46:23 +1000752#ifdef HAVE_LOGIN_CAP
753 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
754 "/etc/motd"), "r");
755#else
Damien Miller942da032000-08-18 13:59:06 +1000756 f = fopen("/etc/motd", "r");
Damien Millerad833b32000-08-23 10:46:23 +1000757#endif
Damien Miller942da032000-08-18 13:59:06 +1000758 if (f) {
759 while (fgets(buf, sizeof(buf), f))
760 fputs(buf, stdout);
761 fclose(f);
762 }
763 }
764}
765
Damien Millerb38eff82000-04-01 11:09:21 +1000766/*
767 * Sets the value of the given variable in the environment. If the variable
768 * already exists, its value is overriden.
769 */
Damien Miller4af51302000-04-16 11:18:38 +1000770void
Damien Millerb38eff82000-04-01 11:09:21 +1000771child_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 */
Damien Miller4af51302000-04-16 11:18:38 +1000811void
Damien Millerb38eff82000-04-01 11:09:21 +1000812read_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 }
Damien Millerb1715dc2000-05-30 13:44:51 +1000835 /*
836 * Replace the equals sign by nul, and advance value to
837 * the value string.
838 */
Damien Millerb38eff82000-04-01 11:09:21 +1000839 *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
870 debug("PAM environment: %s=%s", var_name, var_val);
871
872 child_set_env(env, envsize, var_name, var_val);
873 }
874 }
875}
876#endif /* USE_PAM */
877
Damien Miller5fc85652000-07-09 23:53:07 +1000878#if defined(HAVE_GETUSERATTR)
879/*
880 * AIX-specific login initialisation
881 */
882void set_limit(char *user, char *soft, char *hard, int resource, int mult)
883{
884 struct rlimit rlim;
Damien Miller65964d62000-07-11 09:16:22 +1000885 int slim, hlim;
Damien Miller5fc85652000-07-09 23:53:07 +1000886
887 getrlimit(resource, &rlim);
888
Damien Miller65964d62000-07-11 09:16:22 +1000889 slim = 0;
890 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
891 if (slim < 0) {
892 rlim.rlim_cur = RLIM_INFINITY;
893 } else if (slim != 0) {
894 /* See the wackiness below */
895 if (rlim.rlim_cur == slim * mult)
896 slim = 0;
897 else
898 rlim.rlim_cur = slim * mult;
899 }
900 }
Damien Miller5fc85652000-07-09 23:53:07 +1000901
Damien Miller65964d62000-07-11 09:16:22 +1000902 hlim = 0;
903 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
904 if (hlim < 0) {
905 rlim.rlim_max = RLIM_INFINITY;
906 } else if (hlim != 0) {
907 rlim.rlim_max = hlim * mult;
908 }
909 }
Damien Miller5fc85652000-07-09 23:53:07 +1000910
Damien Miller65964d62000-07-11 09:16:22 +1000911 /*
912 * XXX For cpu and fsize the soft limit is set to the hard limit
913 * if the hard limit is left at its default value and the soft limit
914 * is changed from its default value, either by requesting it
915 * (slim == 0) or by setting it to the current default. At least
916 * that's how rlogind does it. If you're confused you're not alone.
917 * Bug or feature? AIX 4.3.1.2
918 */
919 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
920 && hlim == 0 && slim != 0)
921 rlim.rlim_max = rlim.rlim_cur;
922 /* A specified hard limit limits the soft limit */
923 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
924 rlim.rlim_cur = rlim.rlim_max;
925 /* A soft limit can increase a hard limit */
926 else if (rlim.rlim_cur > rlim.rlim_max)
Damien Miller5fc85652000-07-09 23:53:07 +1000927 rlim.rlim_max = rlim.rlim_cur;
928
929 if (setrlimit(resource, &rlim) != 0)
Damien Miller65964d62000-07-11 09:16:22 +1000930 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
Damien Miller5fc85652000-07-09 23:53:07 +1000931}
932
933void set_limits_from_userattr(char *user)
934{
935 int mask;
936 char buf[16];
937
938 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
939 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
940 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
941 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
942 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
943 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
944#if defined(S_UNOFILE)
945 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
946#endif
947
948 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
949 /* Convert decimal to octal */
950 (void) snprintf(buf, sizeof(buf), "%d", mask);
951 if (sscanf(buf, "%o", &mask) == 1)
952 umask(mask);
953 }
954}
955#endif /* defined(HAVE_GETUSERATTR) */
956
Damien Millerb38eff82000-04-01 11:09:21 +1000957/*
958 * Performs common processing for the child, such as setting up the
959 * environment, closing extra file descriptors, setting the user and group
960 * ids, and executing the command or shell.
961 */
Damien Miller4af51302000-04-16 11:18:38 +1000962void
Damien Millerb38eff82000-04-01 11:09:21 +1000963do_child(const char *command, struct passwd * pw, const char *term,
964 const char *display, const char *auth_proto,
965 const char *auth_data, const char *ttyname)
966{
Damien Miller7b28dc52000-09-05 13:34:53 +1100967 const char *shell, *hostname = NULL, *cp = NULL;
Damien Millerb38eff82000-04-01 11:09:21 +1000968 char buf[256];
Damien Miller0c043c12000-06-07 21:22:38 +1000969 char cmd[1024];
Damien Millerad833b32000-08-23 10:46:23 +1000970 FILE *f = NULL;
Damien Millerb38eff82000-04-01 11:09:21 +1000971 unsigned int envsize, i;
972 char **env;
973 extern char **environ;
974 struct stat st;
975 char *argv[10];
Damien Miller91606b12000-06-28 08:22:29 +1000976#ifdef WITH_IRIX_PROJECT
977 prid_t projid;
978#endif /* WITH_IRIX_PROJECT */
Damien Millerb38eff82000-04-01 11:09:21 +1000979
Damien Millerd3a18572000-06-07 19:55:44 +1000980 /* login(1) is only called if we execute the login shell */
981 if (options.use_login && command != NULL)
982 options.use_login = 0;
983
Damien Millerb38eff82000-04-01 11:09:21 +1000984#ifndef USE_PAM /* pam_nologin handles this */
Damien Millerad833b32000-08-23 10:46:23 +1000985 if (!options.use_login) {
986# ifdef HAVE_LOGIN_CAP
987 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
988 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
989 _PATH_NOLOGIN), "r");
990# else /* HAVE_LOGIN_CAP */
991 if (pw->pw_uid)
992 f = fopen(_PATH_NOLOGIN, "r");
993# endif /* HAVE_LOGIN_CAP */
994 if (f) {
995 /* /etc/nologin exists. Print its contents and exit. */
996 while (fgets(buf, sizeof(buf), f))
997 fputs(buf, stderr);
998 fclose(f);
Damien Millerb38eff82000-04-01 11:09:21 +1000999 exit(254);
Damien Millerad833b32000-08-23 10:46:23 +10001000 }
Damien Millerb38eff82000-04-01 11:09:21 +10001001 }
1002#endif /* USE_PAM */
1003
Damien Millerad833b32000-08-23 10:46:23 +10001004 /* Set login name, uid, gid, and groups. */
Damien Millerb38eff82000-04-01 11:09:21 +10001005 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1006 switch, so we let login(1) to this for us. */
1007 if (!options.use_login) {
Damien Millerb8c656e2000-06-28 15:22:41 +10001008#ifdef HAVE_OSF_SIA
1009 extern char **saved_argv;
1010 extern int saved_argc;
1011 char *host = get_canonical_hostname ();
1012
1013 if (sia_become_user(NULL, saved_argc, saved_argv, host,
1014 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
1015 SIASUCCESS) {
1016 perror("sia_become_user");
1017 exit(1);
1018 }
1019 if (setreuid(geteuid(), geteuid()) < 0) {
1020 perror("setreuid");
1021 exit(1);
1022 }
1023#else /* HAVE_OSF_SIA */
Damien Millerbac2d8a2000-09-05 16:13:06 +11001024#ifdef HAVE_CYGWIN
1025 if (is_winnt) {
1026#else
Damien Millerb38eff82000-04-01 11:09:21 +10001027 if (getuid() == 0 || geteuid() == 0) {
Damien Millerbac2d8a2000-09-05 16:13:06 +11001028#endif
Damien Millerad833b32000-08-23 10:46:23 +10001029# ifdef HAVE_GETUSERATTR
Damien Miller5fc85652000-07-09 23:53:07 +10001030 set_limits_from_userattr(pw->pw_name);
Damien Millerad833b32000-08-23 10:46:23 +10001031# endif /* HAVE_GETUSERATTR */
1032# ifdef HAVE_LOGIN_CAP
1033 if (setusercontext(lc, pw, pw->pw_uid,
1034 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1035 perror("unable to set user context");
1036 exit(1);
1037 }
1038# else /* HAVE_LOGIN_CAP */
1039 if (setlogin(pw->pw_name) < 0)
1040 error("setlogin failed: %s", strerror(errno));
Damien Millerb38eff82000-04-01 11:09:21 +10001041 if (setgid(pw->pw_gid) < 0) {
1042 perror("setgid");
1043 exit(1);
1044 }
1045 /* Initialize the group list. */
1046 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1047 perror("initgroups");
1048 exit(1);
1049 }
1050 endgrent();
Damien Millerad833b32000-08-23 10:46:23 +10001051# ifdef WITH_IRIX_ARRAY
Damien Miller91606b12000-06-28 08:22:29 +10001052 /* initialize array session */
1053 if (newarraysess() != 0)
1054 fatal("Failed to set up new array session: %.100s",
1055 strerror(errno));
Damien Millerad833b32000-08-23 10:46:23 +10001056# endif /* WITH_IRIX_ARRAY */
1057# ifdef WITH_IRIX_PROJECT
Damien Miller91606b12000-06-28 08:22:29 +10001058 /* initialize irix project info */
1059 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1060 debug("Failed to get project id, using projid 0");
1061 projid = 0;
1062 }
Damien Miller91606b12000-06-28 08:22:29 +10001063 if (setprid(projid))
1064 fatal("Failed to initialize project %d for %s: %.100s",
1065 (int)projid, pw->pw_name, strerror(errno));
Damien Millerad833b32000-08-23 10:46:23 +10001066# endif /* WITH_IRIX_PROJECT */
Damien Millerb38eff82000-04-01 11:09:21 +10001067 /* Permanently switch to the desired uid. */
1068 permanently_set_uid(pw->pw_uid);
Damien Millerad833b32000-08-23 10:46:23 +10001069# endif /* HAVE_LOGIN_CAP */
Damien Millerb38eff82000-04-01 11:09:21 +10001070 }
Damien Millerad833b32000-08-23 10:46:23 +10001071#endif /* HAVE_OSF_SIA */
1072
Damien Millerbac2d8a2000-09-05 16:13:06 +11001073#ifdef HAVE_CYGWIN
1074 if (is_winnt)
1075#endif
Damien Millerb38eff82000-04-01 11:09:21 +10001076 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
Damien Millercaf6dd62000-08-29 11:33:50 +11001077 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
Damien Millerb38eff82000-04-01 11:09:21 +10001078 }
1079 /*
1080 * Get the shell from the password data. An empty shell field is
1081 * legal, and means /bin/sh.
1082 */
1083 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
Damien Millerad833b32000-08-23 10:46:23 +10001084#ifdef HAVE_LOGIN_CAP
1085 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1086#endif
Damien Millerb38eff82000-04-01 11:09:21 +10001087
1088#ifdef AFS
1089 /* Try to get AFS tokens for the local cell. */
1090 if (k_hasafs()) {
1091 char cell[64];
1092
1093 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1094 krb_afslog(cell, 0);
1095
1096 krb_afslog(0, 0);
1097 }
1098#endif /* AFS */
1099
1100 /* Initialize the environment. */
1101 envsize = 100;
1102 env = xmalloc(envsize * sizeof(char *));
1103 env[0] = NULL;
1104
Damien Millerbac2d8a2000-09-05 16:13:06 +11001105#ifdef HAVE_CYGWIN
1106 /*
1107 * The Windows environment contains some setting which are
1108 * important for a running system. They must not be dropped.
1109 */
1110 {
1111 char **ep;
1112 for (ep = environ; *ep; ++ep) {
1113 char *esp = strchr(*ep, '=');
1114 *esp = '\0';
1115 child_set_env(&env, &envsize, *ep, esp + 1);
1116 *esp = '=';
1117 }
1118 }
1119#endif
1120
Damien Millerb38eff82000-04-01 11:09:21 +10001121 if (!options.use_login) {
1122 /* Set basic environment. */
1123 child_set_env(&env, &envsize, "USER", pw->pw_name);
1124 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1125 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
Damien Millerad833b32000-08-23 10:46:23 +10001126#ifdef HAVE_LOGIN_CAP
1127 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1128 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1129#else
Damien Millerbac2d8a2000-09-05 16:13:06 +11001130#ifndef HAVE_CYGWIN
1131 /*
1132 * There's no standard path on Windows. The path contains
1133 * important components pointing to the system directories,
1134 * needed for loading shared libraries. So the path better
1135 * remains intact here.
1136 */
Damien Millerb38eff82000-04-01 11:09:21 +10001137 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
Damien Millerad833b32000-08-23 10:46:23 +10001138#endif
Damien Millerbac2d8a2000-09-05 16:13:06 +11001139#endif
Damien Millerb38eff82000-04-01 11:09:21 +10001140
1141 snprintf(buf, sizeof buf, "%.200s/%.50s",
1142 _PATH_MAILDIR, pw->pw_name);
1143 child_set_env(&env, &envsize, "MAIL", buf);
1144
1145 /* Normal systems set SHELL by default. */
1146 child_set_env(&env, &envsize, "SHELL", shell);
1147 }
1148 if (getenv("TZ"))
1149 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1150
1151 /* Set custom environment options from RSA authentication. */
1152 while (custom_environment) {
1153 struct envstring *ce = custom_environment;
1154 char *s = ce->s;
1155 int i;
1156 for (i = 0; s[i] != '=' && s[i]; i++);
1157 if (s[i] == '=') {
1158 s[i] = 0;
1159 child_set_env(&env, &envsize, s, s + i + 1);
1160 }
1161 custom_environment = ce->next;
1162 xfree(ce->s);
1163 xfree(ce);
1164 }
1165
1166 snprintf(buf, sizeof buf, "%.50s %d %d",
1167 get_remote_ipaddr(), get_remote_port(), get_local_port());
1168 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1169
1170 if (ttyname)
1171 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1172 if (term)
1173 child_set_env(&env, &envsize, "TERM", term);
1174 if (display)
1175 child_set_env(&env, &envsize, "DISPLAY", display);
Damien Miller7b28dc52000-09-05 13:34:53 +11001176 if (original_command)
1177 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1178 original_command);
Damien Millerb38eff82000-04-01 11:09:21 +10001179
1180#ifdef _AIX
1181 {
1182 char *authstate,*krb5cc;
1183
1184 if ((authstate = getenv("AUTHSTATE")) != NULL)
1185 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
1186
1187 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
1188 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
1189 }
1190#endif
1191
1192#ifdef KRB4
1193 {
1194 extern char *ticket;
1195
1196 if (ticket)
1197 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1198 }
1199#endif /* KRB4 */
1200
1201#ifdef USE_PAM
1202 /* Pull in any environment variables that may have been set by PAM. */
1203 do_pam_environment(&env, &envsize);
1204#endif /* USE_PAM */
1205
1206 read_environment_file(&env,&envsize,"/etc/environment");
1207
1208 if (xauthfile)
1209 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1210 if (auth_get_socket_name() != NULL)
1211 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1212 auth_get_socket_name());
1213
1214 /* read $HOME/.ssh/environment. */
1215 if (!options.use_login) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001216 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1217 pw->pw_dir);
Damien Millerb38eff82000-04-01 11:09:21 +10001218 read_environment_file(&env, &envsize, buf);
1219 }
1220 if (debug_flag) {
1221 /* dump the environment */
1222 fprintf(stderr, "Environment:\n");
1223 for (i = 0; env[i]; i++)
1224 fprintf(stderr, " %.200s\n", env[i]);
1225 }
Damien Millerad833b32000-08-23 10:46:23 +10001226 /* we have to stash the hostname before we close our socket. */
1227 if (options.use_login)
1228 hostname = get_remote_name_or_ip();
Damien Millerb38eff82000-04-01 11:09:21 +10001229 /*
1230 * Close the connection descriptors; note that this is the child, and
1231 * the server will still have the socket open, and it is important
1232 * that we do not shutdown it. Note that the descriptors cannot be
1233 * closed before building the environment, as we call
1234 * get_remote_ipaddr there.
1235 */
1236 if (packet_get_connection_in() == packet_get_connection_out())
1237 close(packet_get_connection_in());
1238 else {
1239 close(packet_get_connection_in());
1240 close(packet_get_connection_out());
1241 }
1242 /*
1243 * Close all descriptors related to channels. They will still remain
1244 * open in the parent.
1245 */
1246 /* XXX better use close-on-exec? -markus */
1247 channel_close_all();
1248
1249 /*
1250 * Close any extra file descriptors. Note that there may still be
1251 * descriptors left by system functions. They will be closed later.
1252 */
1253 endpwent();
1254
1255 /*
1256 * Close any extra open file descriptors so that we don\'t have them
1257 * hanging around in clients. Note that we want to do this after
1258 * initgroups, because at least on Solaris 2.3 it leaves file
1259 * descriptors open.
1260 */
1261 for (i = 3; i < 64; i++)
1262 close(i);
1263
1264 /* Change current directory to the user\'s home directory. */
Damien Millerad833b32000-08-23 10:46:23 +10001265 if (chdir(pw->pw_dir) < 0) {
Damien Millerb38eff82000-04-01 11:09:21 +10001266 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1267 pw->pw_dir, strerror(errno));
Damien Millerad833b32000-08-23 10:46:23 +10001268#ifdef HAVE_LOGIN_CAP
1269 if (login_getcapbool(lc, "requirehome", 0))
1270 exit(1);
1271#endif
1272 }
Damien Millerb38eff82000-04-01 11:09:21 +10001273
1274 /*
1275 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1276 * xauth are run in the proper environment.
1277 */
1278 environ = env;
1279
1280 /*
1281 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1282 * in this order).
1283 */
1284 if (!options.use_login) {
1285 if (stat(SSH_USER_RC, &st) >= 0) {
1286 if (debug_flag)
Damien Miller7b413d22000-07-01 13:24:21 +10001287 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_USER_RC);
Damien Millerb38eff82000-04-01 11:09:21 +10001288
Damien Miller7b413d22000-07-01 13:24:21 +10001289 f = popen(_PATH_BSHELL " " SSH_USER_RC, "w");
Damien Millerb38eff82000-04-01 11:09:21 +10001290 if (f) {
1291 if (auth_proto != NULL && auth_data != NULL)
1292 fprintf(f, "%s %s\n", auth_proto, auth_data);
1293 pclose(f);
1294 } else
1295 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1296 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1297 if (debug_flag)
Damien Miller7b413d22000-07-01 13:24:21 +10001298 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_SYSTEM_RC);
Damien Millerb38eff82000-04-01 11:09:21 +10001299
Damien Miller7b413d22000-07-01 13:24:21 +10001300 f = popen(_PATH_BSHELL " " SSH_SYSTEM_RC, "w");
Damien Millerb38eff82000-04-01 11:09:21 +10001301 if (f) {
1302 if (auth_proto != NULL && auth_data != NULL)
1303 fprintf(f, "%s %s\n", auth_proto, auth_data);
1304 pclose(f);
1305 } else
1306 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
Damien Miller0c043c12000-06-07 21:22:38 +10001307 } else if (options.xauth_location != NULL) {
Damien Millerb38eff82000-04-01 11:09:21 +10001308 /* Add authority data to .Xauthority if appropriate. */
1309 if (auth_proto != NULL && auth_data != NULL) {
Damien Millerd999ae22000-05-20 12:49:31 +10001310 char *screen = strchr(display, ':');
1311 if (debug_flag) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001312 fprintf(stderr,
1313 "Running %.100s add %.100s %.100s %.100s\n",
Damien Miller0c043c12000-06-07 21:22:38 +10001314 options.xauth_location, display,
1315 auth_proto, auth_data);
Damien Millerbac2d8a2000-09-05 16:13:06 +11001316#ifndef HAVE_CYGWIN
Damien Millerd999ae22000-05-20 12:49:31 +10001317 if (screen != NULL)
Damien Millerb1715dc2000-05-30 13:44:51 +10001318 fprintf(stderr,
1319 "Adding %.*s/unix%s %s %s\n",
Damien Millercaf6dd62000-08-29 11:33:50 +11001320 (int)(screen-display), display,
Damien Millerb1715dc2000-05-30 13:44:51 +10001321 screen, auth_proto, auth_data);
Damien Millerbac2d8a2000-09-05 16:13:06 +11001322#endif
Damien Millerd999ae22000-05-20 12:49:31 +10001323 }
Damien Miller0c043c12000-06-07 21:22:38 +10001324 snprintf(cmd, sizeof cmd, "%s -q -",
1325 options.xauth_location);
1326 f = popen(cmd, "w");
Damien Millerb38eff82000-04-01 11:09:21 +10001327 if (f) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001328 fprintf(f, "add %s %s %s\n", display,
1329 auth_proto, auth_data);
Damien Millerbac2d8a2000-09-05 16:13:06 +11001330#ifndef HAVE_CYGWIN
Damien Millerd999ae22000-05-20 12:49:31 +10001331 if (screen != NULL)
1332 fprintf(f, "add %.*s/unix%s %s %s\n",
Damien Millercaf6dd62000-08-29 11:33:50 +11001333 (int)(screen-display), display,
Damien Millerb1715dc2000-05-30 13:44:51 +10001334 screen, auth_proto, auth_data);
Damien Millerbac2d8a2000-09-05 16:13:06 +11001335#endif
Damien Millerb38eff82000-04-01 11:09:21 +10001336 pclose(f);
Damien Miller0c043c12000-06-07 21:22:38 +10001337 } else {
1338 fprintf(stderr, "Could not run %s\n",
1339 cmd);
1340 }
Damien Millerb38eff82000-04-01 11:09:21 +10001341 }
1342 }
Damien Millerb38eff82000-04-01 11:09:21 +10001343 /* Get the last component of the shell name. */
1344 cp = strrchr(shell, '/');
1345 if (cp)
1346 cp++;
1347 else
1348 cp = shell;
1349 }
1350 /*
1351 * If we have no command, execute the shell. In this case, the shell
1352 * name to be passed in argv[0] is preceded by '-' to indicate that
1353 * this is a login shell.
1354 */
1355 if (!command) {
1356 if (!options.use_login) {
1357 char buf[256];
1358
1359 /*
1360 * Check for mail if we have a tty and it was enabled
1361 * in server options.
1362 */
1363 if (ttyname && options.check_mail) {
1364 char *mailbox;
1365 struct stat mailstat;
1366 mailbox = getenv("MAIL");
1367 if (mailbox != NULL) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001368 if (stat(mailbox, &mailstat) != 0 ||
1369 mailstat.st_size == 0)
Damien Millerb38eff82000-04-01 11:09:21 +10001370 printf("No mail.\n");
1371 else if (mailstat.st_mtime < mailstat.st_atime)
1372 printf("You have mail.\n");
1373 else
1374 printf("You have new mail.\n");
1375 }
1376 }
1377 /* Start the shell. Set initial character to '-'. */
1378 buf[0] = '-';
1379 strncpy(buf + 1, cp, sizeof(buf) - 1);
1380 buf[sizeof(buf) - 1] = 0;
1381
1382 /* Execute the shell. */
1383 argv[0] = buf;
1384 argv[1] = NULL;
1385 execve(shell, argv, env);
1386
1387 /* Executing the shell failed. */
1388 perror(shell);
1389 exit(1);
1390
1391 } else {
1392 /* Launch login(1). */
1393
Damien Millerad833b32000-08-23 10:46:23 +10001394 execl(LOGIN_PROGRAM, "login", "-h", hostname,
Damien Miller942da032000-08-18 13:59:06 +10001395 "-p", "-f", "--", pw->pw_name, NULL);
Damien Millerb38eff82000-04-01 11:09:21 +10001396
1397 /* Login couldn't be executed, die. */
1398
1399 perror("login");
1400 exit(1);
1401 }
1402 }
1403 /*
1404 * Execute the command using the user's shell. This uses the -c
1405 * option to execute the command.
1406 */
1407 argv[0] = (char *) cp;
1408 argv[1] = "-c";
1409 argv[2] = (char *) command;
1410 argv[3] = NULL;
1411 execve(shell, argv, env);
1412 perror(shell);
1413 exit(1);
1414}
1415
1416Session *
1417session_new(void)
1418{
1419 int i;
1420 static int did_init = 0;
1421 if (!did_init) {
1422 debug("session_new: init");
1423 for(i = 0; i < MAX_SESSIONS; i++) {
1424 sessions[i].used = 0;
1425 sessions[i].self = i;
1426 }
Damien Miller15e7d4b2000-09-29 10:57:35 +11001427 num_used_sessions = 0;
Damien Millerb38eff82000-04-01 11:09:21 +10001428 did_init = 1;
1429 }
1430 for(i = 0; i < MAX_SESSIONS; i++) {
1431 Session *s = &sessions[i];
1432 if (! s->used) {
1433 s->pid = 0;
Damien Millerbd483e72000-04-30 10:00:53 +10001434 s->extended = 0;
Damien Millerb38eff82000-04-01 11:09:21 +10001435 s->chanid = -1;
1436 s->ptyfd = -1;
1437 s->ttyfd = -1;
1438 s->term = NULL;
1439 s->pw = NULL;
1440 s->display = NULL;
1441 s->screen = 0;
1442 s->auth_data = NULL;
1443 s->auth_proto = NULL;
1444 s->used = 1;
Damien Millerbd483e72000-04-30 10:00:53 +10001445 s->pw = NULL;
Damien Miller15e7d4b2000-09-29 10:57:35 +11001446 num_used_sessions++;
1447 debug("session_new: session %d (%d used)", i, num_used_sessions);
Damien Millerb38eff82000-04-01 11:09:21 +10001448 return s;
1449 }
1450 }
1451 return NULL;
1452}
1453
1454void
1455session_dump(void)
1456{
1457 int i;
1458 for(i = 0; i < MAX_SESSIONS; i++) {
1459 Session *s = &sessions[i];
1460 debug("dump: used %d session %d %p channel %d pid %d",
1461 s->used,
1462 s->self,
1463 s,
1464 s->chanid,
1465 s->pid);
1466 }
1467}
1468
Damien Millerefb4afe2000-04-12 18:45:05 +10001469int
1470session_open(int chanid)
1471{
1472 Session *s = session_new();
1473 debug("session_open: channel %d", chanid);
1474 if (s == NULL) {
1475 error("no more sessions");
1476 return 0;
1477 }
Damien Millerefb4afe2000-04-12 18:45:05 +10001478 s->pw = auth_get_user();
1479 if (s->pw == NULL)
Damien Millerbd483e72000-04-30 10:00:53 +10001480 fatal("no user for session %i", s->self);
1481 debug("session_open: session %d: link with channel %d", s->self, chanid);
1482 s->chanid = chanid;
Damien Millerefb4afe2000-04-12 18:45:05 +10001483 return 1;
1484}
1485
1486Session *
1487session_by_channel(int id)
1488{
1489 int i;
1490 for(i = 0; i < MAX_SESSIONS; i++) {
1491 Session *s = &sessions[i];
1492 if (s->used && s->chanid == id) {
1493 debug("session_by_channel: session %d channel %d", i, id);
1494 return s;
1495 }
1496 }
1497 debug("session_by_channel: unknown channel %d", id);
1498 session_dump();
1499 return NULL;
1500}
1501
1502Session *
1503session_by_pid(pid_t pid)
1504{
1505 int i;
1506 debug("session_by_pid: pid %d", pid);
1507 for(i = 0; i < MAX_SESSIONS; i++) {
1508 Session *s = &sessions[i];
1509 if (s->used && s->pid == pid)
1510 return s;
1511 }
1512 error("session_by_pid: unknown pid %d", pid);
1513 session_dump();
1514 return NULL;
1515}
1516
1517int
1518session_window_change_req(Session *s)
1519{
1520 s->col = packet_get_int();
1521 s->row = packet_get_int();
1522 s->xpixel = packet_get_int();
1523 s->ypixel = packet_get_int();
Damien Miller4af51302000-04-16 11:18:38 +10001524 packet_done();
Damien Millerefb4afe2000-04-12 18:45:05 +10001525 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1526 return 1;
1527}
1528
1529int
1530session_pty_req(Session *s)
1531{
1532 unsigned int len;
Damien Miller4af51302000-04-16 11:18:38 +10001533 char *term_modes; /* encoded terminal modes */
Damien Millerefb4afe2000-04-12 18:45:05 +10001534
Damien Millerf6d9e222000-06-18 14:50:44 +10001535 if (no_pty_flag)
1536 return 0;
Damien Millerefb4afe2000-04-12 18:45:05 +10001537 if (s->ttyfd != -1)
Damien Miller4af51302000-04-16 11:18:38 +10001538 return 0;
Damien Millerefb4afe2000-04-12 18:45:05 +10001539 s->term = packet_get_string(&len);
1540 s->col = packet_get_int();
1541 s->row = packet_get_int();
1542 s->xpixel = packet_get_int();
1543 s->ypixel = packet_get_int();
Damien Miller4af51302000-04-16 11:18:38 +10001544 term_modes = packet_get_string(&len);
1545 packet_done();
Damien Millerefb4afe2000-04-12 18:45:05 +10001546
1547 if (strcmp(s->term, "") == 0) {
1548 xfree(s->term);
1549 s->term = NULL;
1550 }
1551 /* Allocate a pty and open it. */
1552 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1553 xfree(s->term);
1554 s->term = NULL;
1555 s->ptyfd = -1;
1556 s->ttyfd = -1;
1557 error("session_pty_req: session %d alloc failed", s->self);
Damien Miller4af51302000-04-16 11:18:38 +10001558 xfree(term_modes);
1559 return 0;
Damien Millerefb4afe2000-04-12 18:45:05 +10001560 }
1561 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1562 /*
1563 * Add a cleanup function to clear the utmp entry and record logout
1564 * time in case we call fatal() (e.g., the connection gets closed).
1565 */
1566 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1567 pty_setowner(s->pw, s->tty);
1568 /* Get window size from the packet. */
1569 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1570
Damien Millere247cc42000-05-07 12:03:14 +10001571 session_proctitle(s);
1572
Damien Miller5f056372000-04-16 12:31:48 +10001573 /* XXX parse and set terminal modes */
1574 xfree(term_modes);
Damien Millerefb4afe2000-04-12 18:45:05 +10001575 return 1;
1576}
1577
Damien Millerbd483e72000-04-30 10:00:53 +10001578int
1579session_subsystem_req(Session *s)
1580{
1581 unsigned int len;
1582 int success = 0;
1583 char *subsys = packet_get_string(&len);
Damien Millerf6d9e222000-06-18 14:50:44 +10001584 int i;
Damien Millerbd483e72000-04-30 10:00:53 +10001585
1586 packet_done();
1587 log("subsystem request for %s", subsys);
1588
Damien Millerf6d9e222000-06-18 14:50:44 +10001589 for (i = 0; i < options.num_subsystems; i++) {
1590 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1591 debug("subsystem: exec() %s", options.subsystem_command[i]);
1592 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1593 success = 1;
1594 }
1595 }
1596
1597 if (!success)
1598 log("subsystem request for %s failed, subsystem not found", subsys);
1599
Damien Millerbd483e72000-04-30 10:00:53 +10001600 xfree(subsys);
1601 return success;
1602}
1603
1604int
1605session_x11_req(Session *s)
1606{
Damien Miller7b28dc52000-09-05 13:34:53 +11001607 int fd;
Damien Miller37023962000-07-11 17:31:38 +10001608 if (no_x11_forwarding_flag) {
Damien Millerf6d9e222000-06-18 14:50:44 +10001609 debug("X11 forwarding disabled in user configuration file.");
1610 return 0;
1611 }
Damien Millerbd483e72000-04-30 10:00:53 +10001612 if (!options.x11_forwarding) {
1613 debug("X11 forwarding disabled in server configuration file.");
1614 return 0;
1615 }
1616 if (xauthfile != NULL) {
1617 debug("X11 fwd already started.");
1618 return 0;
1619 }
1620
1621 debug("Received request for X11 forwarding with auth spoofing.");
1622 if (s->display != NULL)
1623 packet_disconnect("Protocol error: X11 display already set.");
1624
1625 s->single_connection = packet_get_char();
1626 s->auth_proto = packet_get_string(NULL);
1627 s->auth_data = packet_get_string(NULL);
1628 s->screen = packet_get_int();
1629 packet_done();
1630
1631 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1632 if (s->display == NULL) {
1633 xfree(s->auth_proto);
1634 xfree(s->auth_data);
1635 return 0;
1636 }
1637 xauthfile = xmalloc(MAXPATHLEN);
1638 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1639 temporarily_use_uid(s->pw->pw_uid);
1640 if (mkdtemp(xauthfile) == NULL) {
1641 restore_uid();
1642 error("private X11 dir: mkdtemp %s failed: %s",
1643 xauthfile, strerror(errno));
1644 xfree(xauthfile);
1645 xauthfile = NULL;
1646 xfree(s->auth_proto);
1647 xfree(s->auth_data);
1648 /* XXXX remove listening channels */
1649 return 0;
1650 }
1651 strlcat(xauthfile, "/cookies", MAXPATHLEN);
Damien Miller7b28dc52000-09-05 13:34:53 +11001652 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1653 if (fd >= 0)
1654 close(fd);
Damien Millerbd483e72000-04-30 10:00:53 +10001655 restore_uid();
1656 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1657 return 1;
1658}
1659
Damien Millerf6d9e222000-06-18 14:50:44 +10001660int
1661session_shell_req(Session *s)
1662{
1663 /* if forced_command == NULL, the shell is execed */
1664 char *shell = forced_command;
1665 packet_done();
1666 s->extended = 1;
1667 if (s->ttyfd == -1)
1668 do_exec_no_pty(s, shell, s->pw);
1669 else
1670 do_exec_pty(s, shell, s->pw);
1671 return 1;
1672}
1673
1674int
1675session_exec_req(Session *s)
1676{
1677 unsigned int len;
1678 char *command = packet_get_string(&len);
1679 packet_done();
1680 if (forced_command) {
Damien Miller7b28dc52000-09-05 13:34:53 +11001681 original_command = command;
Damien Millerf6d9e222000-06-18 14:50:44 +10001682 command = forced_command;
1683 debug("Forced command '%.500s'", forced_command);
1684 }
1685 s->extended = 1;
1686 if (s->ttyfd == -1)
1687 do_exec_no_pty(s, command, s->pw);
1688 else
1689 do_exec_pty(s, command, s->pw);
1690 if (forced_command == NULL)
1691 xfree(command);
1692 return 1;
1693}
1694
Damien Millerefb4afe2000-04-12 18:45:05 +10001695void
1696session_input_channel_req(int id, void *arg)
1697{
1698 unsigned int len;
1699 int reply;
1700 int success = 0;
1701 char *rtype;
1702 Session *s;
1703 Channel *c;
1704
1705 rtype = packet_get_string(&len);
1706 reply = packet_get_char();
1707
1708 s = session_by_channel(id);
1709 if (s == NULL)
1710 fatal("session_input_channel_req: channel %d: no session", id);
1711 c = channel_lookup(id);
1712 if (c == NULL)
1713 fatal("session_input_channel_req: channel %d: bad channel", id);
1714
1715 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1716 s->self, id, rtype, reply);
1717
1718 /*
1719 * a session is in LARVAL state until a shell
1720 * or programm is executed
1721 */
1722 if (c->type == SSH_CHANNEL_LARVAL) {
1723 if (strcmp(rtype, "shell") == 0) {
Damien Millerf6d9e222000-06-18 14:50:44 +10001724 success = session_shell_req(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001725 } else if (strcmp(rtype, "exec") == 0) {
Damien Millerf6d9e222000-06-18 14:50:44 +10001726 success = session_exec_req(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001727 } else if (strcmp(rtype, "pty-req") == 0) {
Damien Miller5f056372000-04-16 12:31:48 +10001728 success = session_pty_req(s);
Damien Millerbd483e72000-04-30 10:00:53 +10001729 } else if (strcmp(rtype, "x11-req") == 0) {
1730 success = session_x11_req(s);
1731 } else if (strcmp(rtype, "subsystem") == 0) {
1732 success = session_subsystem_req(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001733 }
1734 }
1735 if (strcmp(rtype, "window-change") == 0) {
1736 success = session_window_change_req(s);
1737 }
1738
1739 if (reply) {
1740 packet_start(success ?
1741 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1742 packet_put_int(c->remote_id);
1743 packet_send();
1744 }
1745 xfree(rtype);
1746}
1747
1748void
1749session_set_fds(Session *s, int fdin, int fdout, int fderr)
1750{
1751 if (!compat20)
1752 fatal("session_set_fds: called for proto != 2.0");
1753 /*
1754 * now that have a child and a pipe to the child,
1755 * we can activate our channel and register the fd's
1756 */
1757 if (s->chanid == -1)
1758 fatal("no channel for session %d", s->self);
1759 channel_set_fds(s->chanid,
1760 fdout, fdin, fderr,
1761 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1762}
1763
Damien Millerb38eff82000-04-01 11:09:21 +10001764void
1765session_pty_cleanup(Session *s)
1766{
1767 if (s == NULL || s->ttyfd == -1)
1768 return;
1769
1770 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1771
1772 /* Cancel the cleanup function. */
1773 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1774
1775 /* Record that the user has logged out. */
1776 record_logout(s->pid, s->tty);
1777
1778 /* Release the pseudo-tty. */
1779 pty_release(s->tty);
1780
1781 /*
1782 * Close the server side of the socket pairs. We must do this after
1783 * the pty cleanup, so that another process doesn't get this pty
1784 * while we're still cleaning up.
1785 */
1786 if (close(s->ptymaster) < 0)
1787 error("close(s->ptymaster): %s", strerror(errno));
1788}
Damien Millerefb4afe2000-04-12 18:45:05 +10001789
1790void
1791session_exit_message(Session *s, int status)
1792{
1793 Channel *c;
1794 if (s == NULL)
1795 fatal("session_close: no session");
1796 c = channel_lookup(s->chanid);
1797 if (c == NULL)
1798 fatal("session_close: session %d: no channel %d",
1799 s->self, s->chanid);
1800 debug("session_exit_message: session %d channel %d pid %d",
1801 s->self, s->chanid, s->pid);
1802
1803 if (WIFEXITED(status)) {
1804 channel_request_start(s->chanid,
1805 "exit-status", 0);
1806 packet_put_int(WEXITSTATUS(status));
1807 packet_send();
1808 } else if (WIFSIGNALED(status)) {
1809 channel_request_start(s->chanid,
1810 "exit-signal", 0);
1811 packet_put_int(WTERMSIG(status));
Damien Millerf3c6cf12000-05-17 22:08:29 +10001812#ifdef WCOREDUMP
Damien Millerefb4afe2000-04-12 18:45:05 +10001813 packet_put_char(WCOREDUMP(status));
Damien Millerf3c6cf12000-05-17 22:08:29 +10001814#else /* WCOREDUMP */
1815 packet_put_char(0);
1816#endif /* WCOREDUMP */
Damien Millerefb4afe2000-04-12 18:45:05 +10001817 packet_put_cstring("");
1818 packet_put_cstring("");
1819 packet_send();
1820 } else {
1821 /* Some weird exit cause. Just exit. */
1822 packet_disconnect("wait returned status %04x.", status);
1823 }
1824
1825 /* disconnect channel */
1826 debug("session_exit_message: release channel %d", s->chanid);
1827 channel_cancel_cleanup(s->chanid);
Damien Miller166fca82000-04-20 07:42:21 +10001828 /*
1829 * emulate a write failure with 'chan_write_failed', nobody will be
1830 * interested in data we write.
1831 * Note that we must not call 'chan_read_failed', since there could
1832 * be some more data waiting in the pipe.
1833 */
Damien Millerbd483e72000-04-30 10:00:53 +10001834 if (c->ostate != CHAN_OUTPUT_CLOSED)
1835 chan_write_failed(c);
Damien Millerefb4afe2000-04-12 18:45:05 +10001836 s->chanid = -1;
1837}
1838
1839void
1840session_free(Session *s)
1841{
1842 debug("session_free: session %d pid %d", s->self, s->pid);
1843 if (s->term)
1844 xfree(s->term);
1845 if (s->display)
1846 xfree(s->display);
1847 if (s->auth_data)
1848 xfree(s->auth_data);
1849 if (s->auth_proto)
1850 xfree(s->auth_proto);
1851 s->used = 0;
1852}
1853
1854void
1855session_close(Session *s)
1856{
1857 session_pty_cleanup(s);
1858 session_free(s);
Damien Millere247cc42000-05-07 12:03:14 +10001859 session_proctitle(s);
Damien Miller15e7d4b2000-09-29 10:57:35 +11001860 num_used_sessions--;
Damien Millerefb4afe2000-04-12 18:45:05 +10001861}
1862
1863void
1864session_close_by_pid(pid_t pid, int status)
1865{
1866 Session *s = session_by_pid(pid);
1867 if (s == NULL) {
1868 debug("session_close_by_pid: no session for pid %d", s->pid);
1869 return;
1870 }
1871 if (s->chanid != -1)
1872 session_exit_message(s, status);
1873 session_close(s);
1874}
1875
1876/*
1877 * this is called when a channel dies before
1878 * the session 'child' itself dies
1879 */
1880void
1881session_close_by_channel(int id, void *arg)
1882{
1883 Session *s = session_by_channel(id);
1884 if (s == NULL) {
1885 debug("session_close_by_channel: no session for channel %d", id);
1886 return;
1887 }
1888 /* disconnect channel */
1889 channel_cancel_cleanup(s->chanid);
1890 s->chanid = -1;
1891
1892 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1893 if (s->pid == 0) {
1894 /* close session immediately */
1895 session_close(s);
1896 } else {
1897 /* notify child, delay session cleanup */
Damien Miller099f5052000-06-22 20:57:11 +10001898 if (s->pid <= 1)
Damien Miller7a445bb2000-06-26 13:12:37 +10001899 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1900 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
Damien Millerefb4afe2000-04-12 18:45:05 +10001901 error("session_close_by_channel: kill %d: %s",
1902 s->pid, strerror(errno));
1903 }
1904}
1905
Damien Miller15e7d4b2000-09-29 10:57:35 +11001906int used_sessions(void)
1907{
1908 return(num_used_sessions);
1909}
1910
Damien Millere247cc42000-05-07 12:03:14 +10001911char *
1912session_tty_list(void)
1913{
1914 static char buf[1024];
1915 int i;
1916 buf[0] = '\0';
1917 for(i = 0; i < MAX_SESSIONS; i++) {
1918 Session *s = &sessions[i];
1919 if (s->used && s->ttyfd != -1) {
1920 if (buf[0] != '\0')
1921 strlcat(buf, ",", sizeof buf);
1922 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1923 }
1924 }
1925 if (buf[0] == '\0')
1926 strlcpy(buf, "notty", sizeof buf);
1927 return buf;
1928}
1929
1930void
1931session_proctitle(Session *s)
1932{
1933 if (s->pw == NULL)
1934 error("no user for session %d", s->self);
1935 else
1936 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1937}
1938
Damien Millerefb4afe2000-04-12 18:45:05 +10001939void
1940do_authenticated2(void)
1941{
Damien Miller87d29ed2000-08-30 09:21:22 +11001942#ifdef HAVE_LOGIN_CAP
Damien Millerad833b32000-08-23 10:46:23 +10001943 struct passwd *pw;
Damien Miller87d29ed2000-08-30 09:21:22 +11001944#endif
Damien Millerad833b32000-08-23 10:46:23 +10001945
Damien Millerefb4afe2000-04-12 18:45:05 +10001946 /*
1947 * Cancel the alarm we set to limit the time taken for
1948 * authentication.
1949 */
1950 alarm(0);
Damien Miller182ee6e2000-07-12 09:45:27 +10001951 if (startup_pipe != -1) {
Damien Miller4d97ba22000-07-11 18:15:50 +10001952 close(startup_pipe);
Damien Miller182ee6e2000-07-12 09:45:27 +10001953 startup_pipe = -1;
1954 }
Damien Millerad833b32000-08-23 10:46:23 +10001955#ifdef HAVE_LOGIN_CAP
1956 pw = auth_get_user();
1957 if ((lc = login_getclass(pw->pw_class)) == NULL) {
1958 error("unable to get login class");
1959 return;
1960 }
1961#endif
Damien Millerefb4afe2000-04-12 18:45:05 +10001962 server_loop2();
Damien Miller1b26ab22000-04-30 10:12:49 +10001963 if (xauthfile)
1964 xauthfile_cleanup_proc(NULL);
Damien Millerefb4afe2000-04-12 18:45:05 +10001965}