blob: 0cc919c6b8183c3eebf13de7f162c3d7a00fcb28 [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 Millerd2c208a2000-05-17 22:00:02 +1000153#ifdef WITH_AIXAUTHENTICATE
154/* AIX's lastlogin message, set in auth1.c */
155char *aixloginmsg;
156#endif /* WITH_AIXAUTHENTICATE */
Damien Millerb38eff82000-04-01 11:09:21 +1000157
Damien Millerad833b32000-08-23 10:46:23 +1000158#ifdef HAVE_LOGIN_CAP
159static login_cap_t *lc;
160#endif
161
Damien Millerb38eff82000-04-01 11:09:21 +1000162/*
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 */
Damien Miller4af51302000-04-16 11:18:38 +1000187void
Damien Millerb38eff82000-04-01 11:09:21 +1000188pty_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 */
Damien Miller4af51302000-04-16 11:18:38 +1000210void
Damien Millerb38eff82000-04-01 11:09:21 +1000211do_authenticated(struct passwd * pw)
212{
213 Session *s;
Damien Miller7b28dc52000-09-05 13:34:53 +1100214 int type, fd;
Damien Millerb38eff82000-04-01 11:09:21 +1000215 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);
Damien Miller182ee6e2000-07-12 09:45:27 +1000227 if (startup_pipe != -1) {
Damien Miller4d97ba22000-07-11 18:15:50 +1000228 close(startup_pipe);
Damien Miller182ee6e2000-07-12 09:45:27 +1000229 startup_pipe = -1;
230 }
Damien Millerb38eff82000-04-01 11:09:21 +1000231
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();
Damien Millerbd483e72000-04-30 10:00:53 +1000243 s->pw = pw;
Damien Millerb38eff82000-04-01 11:09:21 +1000244
Damien Millerad833b32000-08-23 10:46:23 +1000245#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
Damien Millerb38eff82000-04-01 11:09:21 +1000252 /*
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
Damien Millere247cc42000-05-07 12:03:14 +1000318 session_proctitle(s);
319
Damien Millerb38eff82000-04-01 11:09:21 +1000320 /* 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 }
Damien Miller0c043c12000-06-07 21:22:38 +1000330 if (!options.xauth_location) {
331 packet_send_debug("No xauth program; cannot forward with spoofing.");
332 break;
333 }
Damien Millerb38eff82000-04-01 11:09:21 +1000334 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;
Damien Millerbd483e72000-04-30 10:00:53 +1000365 /* XXXX remove listening channels */
Damien Millerb38eff82000-04-01 11:09:21 +1000366 break;
367 }
368 strlcat(xauthfile, "/cookies", MAXPATHLEN);
Damien Miller7b28dc52000-09-05 13:34:53 +1100369 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
370 if (fd >= 0)
371 close(fd);
Damien Millerb38eff82000-04-01 11:09:21 +1000372 restore_uid();
373 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
374 success = 1;
375 break;
Damien Millerb38eff82000-04-01 11:09:21 +1000376
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.");
Damien Miller0c043c12000-06-07 21:22:38 +1000383 success = auth_input_request_forwarding(pw);
Damien Millerb38eff82000-04-01 11:09:21 +1000384 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.");
Damien Millere247cc42000-05-07 12:03:14 +1000392 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
Damien Millerb38eff82000-04-01 11:09:21 +1000393 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) {
Damien Miller7b28dc52000-09-05 13:34:53 +1100416 original_command = command;
Damien Millerb38eff82000-04-01 11:09:21 +1000417 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 */
Damien Miller4af51302000-04-16 11:18:38 +1000456void
Damien Millerb38eff82000-04-01 11:09:21 +1000457do_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
Damien Millere247cc42000-05-07 12:03:14 +1000478 session_proctitle(s);
Damien Millerb38eff82000-04-01 11:09:21 +1000479
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 }
Damien Millerbac2d8a2000-09-05 16:13:06 +1100537#ifdef HAVE_CYGWIN
538 if (is_winnt)
539 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
540#endif
Damien Millerb38eff82000-04-01 11:09:21 +1000541 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
Damien Millerefb4afe2000-04-12 18:45:05 +1000550 if (compat20) {
Damien Millerbd483e72000-04-30 10:00:53 +1000551 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
Damien Millerefb4afe2000-04-12 18:45:05 +1000552 } 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 }
Damien Millerb38eff82000-04-01 11:09:21 +1000557#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 */
Damien Millerefb4afe2000-04-12 18:45:05 +1000566 if (compat20) {
Damien Millerbd483e72000-04-30 10:00:53 +1000567 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
Damien Millerefb4afe2000-04-12 18:45:05 +1000568 } else {
569 server_loop(pid, inout[1], inout[1], err[1]);
570 /* server_loop has closed inout[1] and err[1]. */
571 }
Damien Millerb38eff82000-04-01 11:09:21 +1000572#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 */
Damien Miller4af51302000-04-16 11:18:38 +1000581void
Damien Millerb38eff82000-04-01 11:09:21 +1000582do_exec_pty(Session *s, const char *command, struct passwd * pw)
583{
Damien Millerb38eff82000-04-01 11:09:21 +1000584 int fdout, ptyfd, ttyfd, ptymaster;
Damien Millerb38eff82000-04-01 11:09:21 +1000585 pid_t pid;
Damien Millerb38eff82000-04-01 11:09:21 +1000586
587 if (s == NULL)
588 fatal("do_exec_pty: no session");
589 ptyfd = s->ptyfd;
590 ttyfd = s->ttyfd;
591
Damien Millerb38eff82000-04-01 11:09:21 +1000592#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) {
Damien Miller942da032000-08-18 13:59:06 +1000599 /* Child. Reinitialize the log because the pid has changed. */
Damien Millerb38eff82000-04-01 11:09:21 +1000600 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
Damien Miller942da032000-08-18 13:59:06 +1000623 /* record login, etc. similar to login(1) */
624 if (command == NULL && !options.use_login)
625 do_login(s);
Damien Millerb38eff82000-04-01 11:09:21 +1000626
Damien Millerb38eff82000-04-01 11:09:21 +1000627 /* Do common processing for the child, such as execing the command. */
Damien Millerb1715dc2000-05-30 13:44:51 +1000628 do_child(command, pw, s->term, s->display, s->auth_proto,
629 s->auth_data, s->tty);
Damien Millerb38eff82000-04-01 11:09:21 +1000630 /* NOTREACHED */
631 }
Damien Millerbac2d8a2000-09-05 16:13:06 +1100632#ifdef HAVE_CYGWIN
633 if (is_winnt)
634 cygwin_set_impersonation_token(INVALID_HANDLE_VALUE);
635#endif
Damien Millerb38eff82000-04-01 11:09:21 +1000636 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. */
Damien Millerefb4afe2000-04-12 18:45:05 +1000659 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 }
Damien Millerb38eff82000-04-01 11:09:21 +1000666}
667
Damien Miller942da032000-08-18 13:59:06 +1000668const 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];
Damien Miller7b28dc52000-09-05 13:34:53 +1100686 char hostname[MAXHOSTNAMELEN];
Damien Miller942da032000-08-18 13:59:06 +1000687 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
Damien Miller7b28dc52000-09-05 13:34:53 +1100708 /* 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
Damien Millere4340be2000-09-16 13:29:08 +1100712 /* 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
Damien Miller942da032000-08-18 13:59:06 +1000717 /* 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);
Damien Millerad833b32000-08-23 10:46:23 +1000723#ifdef HAVE_LOGIN_CAP
724 if (login_getcapbool(lc, "hushlogin", 0) || stat(buf, &st) >= 0)
725#else
Damien Miller942da032000-08-18 13:59:06 +1000726 if (stat(buf, &st) >= 0)
Damien Millerad833b32000-08-23 10:46:23 +1000727#endif
Damien Miller942da032000-08-18 13:59:06 +1000728 return;
729
730#ifdef USE_PAM
731 print_pam_messages();
732#endif /* USE_PAM */
733#ifdef WITH_AIXAUTHENTICATE
734 if (aixloginmsg && *aixloginmsg)
735 printf("%s\n", aixloginmsg);
736#endif /* WITH_AIXAUTHENTICATE */
737
Damien Miller942da032000-08-18 13:59:06 +1000738 if (last_login_time != 0) {
739 time_string = ctime(&last_login_time);
740 if (strchr(time_string, '\n'))
741 *strchr(time_string, '\n') = 0;
742 if (strcmp(buf, "") == 0)
743 printf("Last login: %s\r\n", time_string);
744 else
Damien Millere4340be2000-09-16 13:29:08 +1100745 printf("Last login: %s from %s\r\n", time_string, hostname);
Damien Miller942da032000-08-18 13:59:06 +1000746 }
747 if (options.print_motd) {
Damien Millerad833b32000-08-23 10:46:23 +1000748#ifdef HAVE_LOGIN_CAP
749 f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
750 "/etc/motd"), "r");
751#else
Damien Miller942da032000-08-18 13:59:06 +1000752 f = fopen("/etc/motd", "r");
Damien Millerad833b32000-08-23 10:46:23 +1000753#endif
Damien Miller942da032000-08-18 13:59:06 +1000754 if (f) {
755 while (fgets(buf, sizeof(buf), f))
756 fputs(buf, stdout);
757 fclose(f);
758 }
759 }
760}
761
Damien Millerb38eff82000-04-01 11:09:21 +1000762/*
763 * Sets the value of the given variable in the environment. If the variable
764 * already exists, its value is overriden.
765 */
Damien Miller4af51302000-04-16 11:18:38 +1000766void
Damien Millerb38eff82000-04-01 11:09:21 +1000767child_set_env(char ***envp, unsigned int *envsizep, const char *name,
768 const char *value)
769{
770 unsigned int i, namelen;
771 char **env;
772
773 /*
774 * Find the slot where the value should be stored. If the variable
775 * already exists, we reuse the slot; otherwise we append a new slot
776 * at the end of the array, expanding if necessary.
777 */
778 env = *envp;
779 namelen = strlen(name);
780 for (i = 0; env[i]; i++)
781 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
782 break;
783 if (env[i]) {
784 /* Reuse the slot. */
785 xfree(env[i]);
786 } else {
787 /* New variable. Expand if necessary. */
788 if (i >= (*envsizep) - 1) {
789 (*envsizep) += 50;
790 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
791 }
792 /* Need to set the NULL pointer at end of array beyond the new slot. */
793 env[i + 1] = NULL;
794 }
795
796 /* Allocate space and format the variable in the appropriate slot. */
797 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
798 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
799}
800
801/*
802 * Reads environment variables from the given file and adds/overrides them
803 * into the environment. If the file does not exist, this does nothing.
804 * Otherwise, it must consist of empty lines, comments (line starts with '#')
805 * and assignments of the form name=value. No other forms are allowed.
806 */
Damien Miller4af51302000-04-16 11:18:38 +1000807void
Damien Millerb38eff82000-04-01 11:09:21 +1000808read_environment_file(char ***env, unsigned int *envsize,
809 const char *filename)
810{
811 FILE *f;
812 char buf[4096];
813 char *cp, *value;
814
815 f = fopen(filename, "r");
816 if (!f)
817 return;
818
819 while (fgets(buf, sizeof(buf), f)) {
820 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
821 ;
822 if (!*cp || *cp == '#' || *cp == '\n')
823 continue;
824 if (strchr(cp, '\n'))
825 *strchr(cp, '\n') = '\0';
826 value = strchr(cp, '=');
827 if (value == NULL) {
828 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
829 continue;
830 }
Damien Millerb1715dc2000-05-30 13:44:51 +1000831 /*
832 * Replace the equals sign by nul, and advance value to
833 * the value string.
834 */
Damien Millerb38eff82000-04-01 11:09:21 +1000835 *value = '\0';
836 value++;
837 child_set_env(env, envsize, cp, value);
838 }
839 fclose(f);
840}
841
842#ifdef USE_PAM
843/*
844 * Sets any environment variables which have been specified by PAM
845 */
846void do_pam_environment(char ***env, int *envsize)
847{
848 char *equals, var_name[512], var_val[512];
849 char **pam_env;
850 int i;
851
852 if ((pam_env = fetch_pam_environment()) == NULL)
853 return;
854
855 for(i = 0; pam_env[i] != NULL; i++) {
856 if ((equals = strstr(pam_env[i], "=")) == NULL)
857 continue;
858
859 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
860 memset(var_name, '\0', sizeof(var_name));
861 memset(var_val, '\0', sizeof(var_val));
862
863 strncpy(var_name, pam_env[i], equals - pam_env[i]);
864 strcpy(var_val, equals + 1);
865
866 debug("PAM environment: %s=%s", var_name, var_val);
867
868 child_set_env(env, envsize, var_name, var_val);
869 }
870 }
871}
872#endif /* USE_PAM */
873
Damien Miller5fc85652000-07-09 23:53:07 +1000874#if defined(HAVE_GETUSERATTR)
875/*
876 * AIX-specific login initialisation
877 */
878void set_limit(char *user, char *soft, char *hard, int resource, int mult)
879{
880 struct rlimit rlim;
Damien Miller65964d62000-07-11 09:16:22 +1000881 int slim, hlim;
Damien Miller5fc85652000-07-09 23:53:07 +1000882
883 getrlimit(resource, &rlim);
884
Damien Miller65964d62000-07-11 09:16:22 +1000885 slim = 0;
886 if (getuserattr(user, soft, &slim, SEC_INT) != -1) {
887 if (slim < 0) {
888 rlim.rlim_cur = RLIM_INFINITY;
889 } else if (slim != 0) {
890 /* See the wackiness below */
891 if (rlim.rlim_cur == slim * mult)
892 slim = 0;
893 else
894 rlim.rlim_cur = slim * mult;
895 }
896 }
Damien Miller5fc85652000-07-09 23:53:07 +1000897
Damien Miller65964d62000-07-11 09:16:22 +1000898 hlim = 0;
899 if (getuserattr(user, hard, &hlim, SEC_INT) != -1) {
900 if (hlim < 0) {
901 rlim.rlim_max = RLIM_INFINITY;
902 } else if (hlim != 0) {
903 rlim.rlim_max = hlim * mult;
904 }
905 }
Damien Miller5fc85652000-07-09 23:53:07 +1000906
Damien Miller65964d62000-07-11 09:16:22 +1000907 /*
908 * XXX For cpu and fsize the soft limit is set to the hard limit
909 * if the hard limit is left at its default value and the soft limit
910 * is changed from its default value, either by requesting it
911 * (slim == 0) or by setting it to the current default. At least
912 * that's how rlogind does it. If you're confused you're not alone.
913 * Bug or feature? AIX 4.3.1.2
914 */
915 if ((!strcmp(soft, "fsize") || !strcmp(soft, "cpu"))
916 && hlim == 0 && slim != 0)
917 rlim.rlim_max = rlim.rlim_cur;
918 /* A specified hard limit limits the soft limit */
919 else if (hlim > 0 && rlim.rlim_cur > rlim.rlim_max)
920 rlim.rlim_cur = rlim.rlim_max;
921 /* A soft limit can increase a hard limit */
922 else if (rlim.rlim_cur > rlim.rlim_max)
Damien Miller5fc85652000-07-09 23:53:07 +1000923 rlim.rlim_max = rlim.rlim_cur;
924
925 if (setrlimit(resource, &rlim) != 0)
Damien Miller65964d62000-07-11 09:16:22 +1000926 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno));
Damien Miller5fc85652000-07-09 23:53:07 +1000927}
928
929void set_limits_from_userattr(char *user)
930{
931 int mask;
932 char buf[16];
933
934 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
935 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
936 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
937 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
938 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
939 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
940#if defined(S_UNOFILE)
941 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
942#endif
943
944 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
945 /* Convert decimal to octal */
946 (void) snprintf(buf, sizeof(buf), "%d", mask);
947 if (sscanf(buf, "%o", &mask) == 1)
948 umask(mask);
949 }
950}
951#endif /* defined(HAVE_GETUSERATTR) */
952
Damien Millerb38eff82000-04-01 11:09:21 +1000953/*
954 * Performs common processing for the child, such as setting up the
955 * environment, closing extra file descriptors, setting the user and group
956 * ids, and executing the command or shell.
957 */
Damien Miller4af51302000-04-16 11:18:38 +1000958void
Damien Millerb38eff82000-04-01 11:09:21 +1000959do_child(const char *command, struct passwd * pw, const char *term,
960 const char *display, const char *auth_proto,
961 const char *auth_data, const char *ttyname)
962{
Damien Miller7b28dc52000-09-05 13:34:53 +1100963 const char *shell, *hostname = NULL, *cp = NULL;
Damien Millerb38eff82000-04-01 11:09:21 +1000964 char buf[256];
Damien Miller0c043c12000-06-07 21:22:38 +1000965 char cmd[1024];
Damien Millerad833b32000-08-23 10:46:23 +1000966 FILE *f = NULL;
Damien Millerb38eff82000-04-01 11:09:21 +1000967 unsigned int envsize, i;
968 char **env;
969 extern char **environ;
970 struct stat st;
971 char *argv[10];
Damien Miller91606b12000-06-28 08:22:29 +1000972#ifdef WITH_IRIX_PROJECT
973 prid_t projid;
974#endif /* WITH_IRIX_PROJECT */
Damien Millerb38eff82000-04-01 11:09:21 +1000975
Damien Millerd3a18572000-06-07 19:55:44 +1000976 /* login(1) is only called if we execute the login shell */
977 if (options.use_login && command != NULL)
978 options.use_login = 0;
979
Damien Millerb38eff82000-04-01 11:09:21 +1000980#ifndef USE_PAM /* pam_nologin handles this */
Damien Millerad833b32000-08-23 10:46:23 +1000981 if (!options.use_login) {
982# ifdef HAVE_LOGIN_CAP
983 if (!login_getcapbool(lc, "ignorenologin", 0) && pw->pw_uid)
984 f = fopen(login_getcapstr(lc, "nologin", _PATH_NOLOGIN,
985 _PATH_NOLOGIN), "r");
986# else /* HAVE_LOGIN_CAP */
987 if (pw->pw_uid)
988 f = fopen(_PATH_NOLOGIN, "r");
989# endif /* HAVE_LOGIN_CAP */
990 if (f) {
991 /* /etc/nologin exists. Print its contents and exit. */
992 while (fgets(buf, sizeof(buf), f))
993 fputs(buf, stderr);
994 fclose(f);
Damien Millerb38eff82000-04-01 11:09:21 +1000995 exit(254);
Damien Millerad833b32000-08-23 10:46:23 +1000996 }
Damien Millerb38eff82000-04-01 11:09:21 +1000997 }
998#endif /* USE_PAM */
999
Damien Millerad833b32000-08-23 10:46:23 +10001000 /* Set login name, uid, gid, and groups. */
Damien Millerb38eff82000-04-01 11:09:21 +10001001 /* Login(1) does this as well, and it needs uid 0 for the "-h"
1002 switch, so we let login(1) to this for us. */
1003 if (!options.use_login) {
Damien Millerb8c656e2000-06-28 15:22:41 +10001004#ifdef HAVE_OSF_SIA
1005 extern char **saved_argv;
1006 extern int saved_argc;
1007 char *host = get_canonical_hostname ();
1008
1009 if (sia_become_user(NULL, saved_argc, saved_argv, host,
1010 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
1011 SIASUCCESS) {
1012 perror("sia_become_user");
1013 exit(1);
1014 }
1015 if (setreuid(geteuid(), geteuid()) < 0) {
1016 perror("setreuid");
1017 exit(1);
1018 }
1019#else /* HAVE_OSF_SIA */
Damien Millerbac2d8a2000-09-05 16:13:06 +11001020#ifdef HAVE_CYGWIN
1021 if (is_winnt) {
1022#else
Damien Millerb38eff82000-04-01 11:09:21 +10001023 if (getuid() == 0 || geteuid() == 0) {
Damien Millerbac2d8a2000-09-05 16:13:06 +11001024#endif
Damien Millerad833b32000-08-23 10:46:23 +10001025# ifdef HAVE_GETUSERATTR
Damien Miller5fc85652000-07-09 23:53:07 +10001026 set_limits_from_userattr(pw->pw_name);
Damien Millerad833b32000-08-23 10:46:23 +10001027# endif /* HAVE_GETUSERATTR */
1028# ifdef HAVE_LOGIN_CAP
1029 if (setusercontext(lc, pw, pw->pw_uid,
1030 (LOGIN_SETALL & ~LOGIN_SETPATH)) < 0) {
1031 perror("unable to set user context");
1032 exit(1);
1033 }
1034# else /* HAVE_LOGIN_CAP */
1035 if (setlogin(pw->pw_name) < 0)
1036 error("setlogin failed: %s", strerror(errno));
Damien Millerb38eff82000-04-01 11:09:21 +10001037 if (setgid(pw->pw_gid) < 0) {
1038 perror("setgid");
1039 exit(1);
1040 }
1041 /* Initialize the group list. */
1042 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
1043 perror("initgroups");
1044 exit(1);
1045 }
1046 endgrent();
Damien Millerad833b32000-08-23 10:46:23 +10001047# ifdef WITH_IRIX_ARRAY
Damien Miller91606b12000-06-28 08:22:29 +10001048 /* initialize array session */
1049 if (newarraysess() != 0)
1050 fatal("Failed to set up new array session: %.100s",
1051 strerror(errno));
Damien Millerad833b32000-08-23 10:46:23 +10001052# endif /* WITH_IRIX_ARRAY */
1053# ifdef WITH_IRIX_PROJECT
Damien Miller91606b12000-06-28 08:22:29 +10001054 /* initialize irix project info */
1055 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
1056 debug("Failed to get project id, using projid 0");
1057 projid = 0;
1058 }
Damien Miller91606b12000-06-28 08:22:29 +10001059 if (setprid(projid))
1060 fatal("Failed to initialize project %d for %s: %.100s",
1061 (int)projid, pw->pw_name, strerror(errno));
Damien Millerad833b32000-08-23 10:46:23 +10001062# endif /* WITH_IRIX_PROJECT */
Damien Millerb38eff82000-04-01 11:09:21 +10001063 /* Permanently switch to the desired uid. */
1064 permanently_set_uid(pw->pw_uid);
Damien Millerad833b32000-08-23 10:46:23 +10001065# endif /* HAVE_LOGIN_CAP */
Damien Millerb38eff82000-04-01 11:09:21 +10001066 }
Damien Millerad833b32000-08-23 10:46:23 +10001067#endif /* HAVE_OSF_SIA */
1068
Damien Millerbac2d8a2000-09-05 16:13:06 +11001069#ifdef HAVE_CYGWIN
1070 if (is_winnt)
1071#endif
Damien Millerb38eff82000-04-01 11:09:21 +10001072 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
Damien Millercaf6dd62000-08-29 11:33:50 +11001073 fatal("Failed to set uids to %u.", (u_int) pw->pw_uid);
Damien Millerb38eff82000-04-01 11:09:21 +10001074 }
1075 /*
1076 * Get the shell from the password data. An empty shell field is
1077 * legal, and means /bin/sh.
1078 */
1079 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
Damien Millerad833b32000-08-23 10:46:23 +10001080#ifdef HAVE_LOGIN_CAP
1081 shell = login_getcapstr(lc, "shell", (char *)shell, (char *)shell);
1082#endif
Damien Millerb38eff82000-04-01 11:09:21 +10001083
1084#ifdef AFS
1085 /* Try to get AFS tokens for the local cell. */
1086 if (k_hasafs()) {
1087 char cell[64];
1088
1089 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
1090 krb_afslog(cell, 0);
1091
1092 krb_afslog(0, 0);
1093 }
1094#endif /* AFS */
1095
1096 /* Initialize the environment. */
1097 envsize = 100;
1098 env = xmalloc(envsize * sizeof(char *));
1099 env[0] = NULL;
1100
Damien Millerbac2d8a2000-09-05 16:13:06 +11001101#ifdef HAVE_CYGWIN
1102 /*
1103 * The Windows environment contains some setting which are
1104 * important for a running system. They must not be dropped.
1105 */
1106 {
1107 char **ep;
1108 for (ep = environ; *ep; ++ep) {
1109 char *esp = strchr(*ep, '=');
1110 *esp = '\0';
1111 child_set_env(&env, &envsize, *ep, esp + 1);
1112 *esp = '=';
1113 }
1114 }
1115#endif
1116
Damien Millerb38eff82000-04-01 11:09:21 +10001117 if (!options.use_login) {
1118 /* Set basic environment. */
1119 child_set_env(&env, &envsize, "USER", pw->pw_name);
1120 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
1121 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
Damien Millerad833b32000-08-23 10:46:23 +10001122#ifdef HAVE_LOGIN_CAP
1123 (void) setusercontext(lc, pw, pw->pw_uid, LOGIN_SETPATH);
1124 child_set_env(&env, &envsize, "PATH", getenv("PATH"));
1125#else
Damien Millerbac2d8a2000-09-05 16:13:06 +11001126#ifndef HAVE_CYGWIN
1127 /*
1128 * There's no standard path on Windows. The path contains
1129 * important components pointing to the system directories,
1130 * needed for loading shared libraries. So the path better
1131 * remains intact here.
1132 */
Damien Millerb38eff82000-04-01 11:09:21 +10001133 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
Damien Millerad833b32000-08-23 10:46:23 +10001134#endif
Damien Millerbac2d8a2000-09-05 16:13:06 +11001135#endif
Damien Millerb38eff82000-04-01 11:09:21 +10001136
1137 snprintf(buf, sizeof buf, "%.200s/%.50s",
1138 _PATH_MAILDIR, pw->pw_name);
1139 child_set_env(&env, &envsize, "MAIL", buf);
1140
1141 /* Normal systems set SHELL by default. */
1142 child_set_env(&env, &envsize, "SHELL", shell);
1143 }
1144 if (getenv("TZ"))
1145 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
1146
1147 /* Set custom environment options from RSA authentication. */
1148 while (custom_environment) {
1149 struct envstring *ce = custom_environment;
1150 char *s = ce->s;
1151 int i;
1152 for (i = 0; s[i] != '=' && s[i]; i++);
1153 if (s[i] == '=') {
1154 s[i] = 0;
1155 child_set_env(&env, &envsize, s, s + i + 1);
1156 }
1157 custom_environment = ce->next;
1158 xfree(ce->s);
1159 xfree(ce);
1160 }
1161
1162 snprintf(buf, sizeof buf, "%.50s %d %d",
1163 get_remote_ipaddr(), get_remote_port(), get_local_port());
1164 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1165
1166 if (ttyname)
1167 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1168 if (term)
1169 child_set_env(&env, &envsize, "TERM", term);
1170 if (display)
1171 child_set_env(&env, &envsize, "DISPLAY", display);
Damien Miller7b28dc52000-09-05 13:34:53 +11001172 if (original_command)
1173 child_set_env(&env, &envsize, "SSH_ORIGINAL_COMMAND",
1174 original_command);
Damien Millerb38eff82000-04-01 11:09:21 +10001175
1176#ifdef _AIX
1177 {
1178 char *authstate,*krb5cc;
1179
1180 if ((authstate = getenv("AUTHSTATE")) != NULL)
1181 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
1182
1183 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
1184 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
1185 }
1186#endif
1187
1188#ifdef KRB4
1189 {
1190 extern char *ticket;
1191
1192 if (ticket)
1193 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1194 }
1195#endif /* KRB4 */
1196
1197#ifdef USE_PAM
1198 /* Pull in any environment variables that may have been set by PAM. */
1199 do_pam_environment(&env, &envsize);
1200#endif /* USE_PAM */
1201
1202 read_environment_file(&env,&envsize,"/etc/environment");
1203
1204 if (xauthfile)
1205 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1206 if (auth_get_socket_name() != NULL)
1207 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1208 auth_get_socket_name());
1209
1210 /* read $HOME/.ssh/environment. */
1211 if (!options.use_login) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001212 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1213 pw->pw_dir);
Damien Millerb38eff82000-04-01 11:09:21 +10001214 read_environment_file(&env, &envsize, buf);
1215 }
1216 if (debug_flag) {
1217 /* dump the environment */
1218 fprintf(stderr, "Environment:\n");
1219 for (i = 0; env[i]; i++)
1220 fprintf(stderr, " %.200s\n", env[i]);
1221 }
Damien Millerad833b32000-08-23 10:46:23 +10001222 /* we have to stash the hostname before we close our socket. */
1223 if (options.use_login)
1224 hostname = get_remote_name_or_ip();
Damien Millerb38eff82000-04-01 11:09:21 +10001225 /*
1226 * Close the connection descriptors; note that this is the child, and
1227 * the server will still have the socket open, and it is important
1228 * that we do not shutdown it. Note that the descriptors cannot be
1229 * closed before building the environment, as we call
1230 * get_remote_ipaddr there.
1231 */
1232 if (packet_get_connection_in() == packet_get_connection_out())
1233 close(packet_get_connection_in());
1234 else {
1235 close(packet_get_connection_in());
1236 close(packet_get_connection_out());
1237 }
1238 /*
1239 * Close all descriptors related to channels. They will still remain
1240 * open in the parent.
1241 */
1242 /* XXX better use close-on-exec? -markus */
1243 channel_close_all();
1244
1245 /*
1246 * Close any extra file descriptors. Note that there may still be
1247 * descriptors left by system functions. They will be closed later.
1248 */
1249 endpwent();
1250
1251 /*
1252 * Close any extra open file descriptors so that we don\'t have them
1253 * hanging around in clients. Note that we want to do this after
1254 * initgroups, because at least on Solaris 2.3 it leaves file
1255 * descriptors open.
1256 */
1257 for (i = 3; i < 64; i++)
1258 close(i);
1259
1260 /* Change current directory to the user\'s home directory. */
Damien Millerad833b32000-08-23 10:46:23 +10001261 if (chdir(pw->pw_dir) < 0) {
Damien Millerb38eff82000-04-01 11:09:21 +10001262 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1263 pw->pw_dir, strerror(errno));
Damien Millerad833b32000-08-23 10:46:23 +10001264#ifdef HAVE_LOGIN_CAP
1265 if (login_getcapbool(lc, "requirehome", 0))
1266 exit(1);
1267#endif
1268 }
Damien Millerb38eff82000-04-01 11:09:21 +10001269
1270 /*
1271 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1272 * xauth are run in the proper environment.
1273 */
1274 environ = env;
1275
1276 /*
1277 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1278 * in this order).
1279 */
1280 if (!options.use_login) {
1281 if (stat(SSH_USER_RC, &st) >= 0) {
1282 if (debug_flag)
Damien Miller7b413d22000-07-01 13:24:21 +10001283 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_USER_RC);
Damien Millerb38eff82000-04-01 11:09:21 +10001284
Damien Miller7b413d22000-07-01 13:24:21 +10001285 f = popen(_PATH_BSHELL " " SSH_USER_RC, "w");
Damien Millerb38eff82000-04-01 11:09:21 +10001286 if (f) {
1287 if (auth_proto != NULL && auth_data != NULL)
1288 fprintf(f, "%s %s\n", auth_proto, auth_data);
1289 pclose(f);
1290 } else
1291 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1292 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1293 if (debug_flag)
Damien Miller7b413d22000-07-01 13:24:21 +10001294 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_SYSTEM_RC);
Damien Millerb38eff82000-04-01 11:09:21 +10001295
Damien Miller7b413d22000-07-01 13:24:21 +10001296 f = popen(_PATH_BSHELL " " SSH_SYSTEM_RC, "w");
Damien Millerb38eff82000-04-01 11:09:21 +10001297 if (f) {
1298 if (auth_proto != NULL && auth_data != NULL)
1299 fprintf(f, "%s %s\n", auth_proto, auth_data);
1300 pclose(f);
1301 } else
1302 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
Damien Miller0c043c12000-06-07 21:22:38 +10001303 } else if (options.xauth_location != NULL) {
Damien Millerb38eff82000-04-01 11:09:21 +10001304 /* Add authority data to .Xauthority if appropriate. */
1305 if (auth_proto != NULL && auth_data != NULL) {
Damien Millerd999ae22000-05-20 12:49:31 +10001306 char *screen = strchr(display, ':');
1307 if (debug_flag) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001308 fprintf(stderr,
1309 "Running %.100s add %.100s %.100s %.100s\n",
Damien Miller0c043c12000-06-07 21:22:38 +10001310 options.xauth_location, display,
1311 auth_proto, auth_data);
Damien Millerbac2d8a2000-09-05 16:13:06 +11001312#ifndef HAVE_CYGWIN
Damien Millerd999ae22000-05-20 12:49:31 +10001313 if (screen != NULL)
Damien Millerb1715dc2000-05-30 13:44:51 +10001314 fprintf(stderr,
1315 "Adding %.*s/unix%s %s %s\n",
Damien Millercaf6dd62000-08-29 11:33:50 +11001316 (int)(screen-display), display,
Damien Millerb1715dc2000-05-30 13:44:51 +10001317 screen, auth_proto, auth_data);
Damien Millerbac2d8a2000-09-05 16:13:06 +11001318#endif
Damien Millerd999ae22000-05-20 12:49:31 +10001319 }
Damien Miller0c043c12000-06-07 21:22:38 +10001320 snprintf(cmd, sizeof cmd, "%s -q -",
1321 options.xauth_location);
1322 f = popen(cmd, "w");
Damien Millerb38eff82000-04-01 11:09:21 +10001323 if (f) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001324 fprintf(f, "add %s %s %s\n", display,
1325 auth_proto, auth_data);
Damien Millerbac2d8a2000-09-05 16:13:06 +11001326#ifndef HAVE_CYGWIN
Damien Millerd999ae22000-05-20 12:49:31 +10001327 if (screen != NULL)
1328 fprintf(f, "add %.*s/unix%s %s %s\n",
Damien Millercaf6dd62000-08-29 11:33:50 +11001329 (int)(screen-display), display,
Damien Millerb1715dc2000-05-30 13:44:51 +10001330 screen, auth_proto, auth_data);
Damien Millerbac2d8a2000-09-05 16:13:06 +11001331#endif
Damien Millerb38eff82000-04-01 11:09:21 +10001332 pclose(f);
Damien Miller0c043c12000-06-07 21:22:38 +10001333 } else {
1334 fprintf(stderr, "Could not run %s\n",
1335 cmd);
1336 }
Damien Millerb38eff82000-04-01 11:09:21 +10001337 }
1338 }
Damien Millerb38eff82000-04-01 11:09:21 +10001339 /* Get the last component of the shell name. */
1340 cp = strrchr(shell, '/');
1341 if (cp)
1342 cp++;
1343 else
1344 cp = shell;
1345 }
1346 /*
1347 * If we have no command, execute the shell. In this case, the shell
1348 * name to be passed in argv[0] is preceded by '-' to indicate that
1349 * this is a login shell.
1350 */
1351 if (!command) {
1352 if (!options.use_login) {
1353 char buf[256];
1354
1355 /*
1356 * Check for mail if we have a tty and it was enabled
1357 * in server options.
1358 */
1359 if (ttyname && options.check_mail) {
1360 char *mailbox;
1361 struct stat mailstat;
1362 mailbox = getenv("MAIL");
1363 if (mailbox != NULL) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001364 if (stat(mailbox, &mailstat) != 0 ||
1365 mailstat.st_size == 0)
Damien Millerb38eff82000-04-01 11:09:21 +10001366 printf("No mail.\n");
1367 else if (mailstat.st_mtime < mailstat.st_atime)
1368 printf("You have mail.\n");
1369 else
1370 printf("You have new mail.\n");
1371 }
1372 }
1373 /* Start the shell. Set initial character to '-'. */
1374 buf[0] = '-';
1375 strncpy(buf + 1, cp, sizeof(buf) - 1);
1376 buf[sizeof(buf) - 1] = 0;
1377
1378 /* Execute the shell. */
1379 argv[0] = buf;
1380 argv[1] = NULL;
1381 execve(shell, argv, env);
1382
1383 /* Executing the shell failed. */
1384 perror(shell);
1385 exit(1);
1386
1387 } else {
1388 /* Launch login(1). */
1389
Damien Millerad833b32000-08-23 10:46:23 +10001390 execl(LOGIN_PROGRAM, "login", "-h", hostname,
Damien Miller942da032000-08-18 13:59:06 +10001391 "-p", "-f", "--", pw->pw_name, NULL);
Damien Millerb38eff82000-04-01 11:09:21 +10001392
1393 /* Login couldn't be executed, die. */
1394
1395 perror("login");
1396 exit(1);
1397 }
1398 }
1399 /*
1400 * Execute the command using the user's shell. This uses the -c
1401 * option to execute the command.
1402 */
1403 argv[0] = (char *) cp;
1404 argv[1] = "-c";
1405 argv[2] = (char *) command;
1406 argv[3] = NULL;
1407 execve(shell, argv, env);
1408 perror(shell);
1409 exit(1);
1410}
1411
1412Session *
1413session_new(void)
1414{
1415 int i;
1416 static int did_init = 0;
1417 if (!did_init) {
1418 debug("session_new: init");
1419 for(i = 0; i < MAX_SESSIONS; i++) {
1420 sessions[i].used = 0;
1421 sessions[i].self = i;
1422 }
1423 did_init = 1;
1424 }
1425 for(i = 0; i < MAX_SESSIONS; i++) {
1426 Session *s = &sessions[i];
1427 if (! s->used) {
1428 s->pid = 0;
Damien Millerbd483e72000-04-30 10:00:53 +10001429 s->extended = 0;
Damien Millerb38eff82000-04-01 11:09:21 +10001430 s->chanid = -1;
1431 s->ptyfd = -1;
1432 s->ttyfd = -1;
1433 s->term = NULL;
1434 s->pw = NULL;
1435 s->display = NULL;
1436 s->screen = 0;
1437 s->auth_data = NULL;
1438 s->auth_proto = NULL;
1439 s->used = 1;
Damien Millerbd483e72000-04-30 10:00:53 +10001440 s->pw = NULL;
Damien Millerb38eff82000-04-01 11:09:21 +10001441 debug("session_new: session %d", i);
1442 return s;
1443 }
1444 }
1445 return NULL;
1446}
1447
1448void
1449session_dump(void)
1450{
1451 int i;
1452 for(i = 0; i < MAX_SESSIONS; i++) {
1453 Session *s = &sessions[i];
1454 debug("dump: used %d session %d %p channel %d pid %d",
1455 s->used,
1456 s->self,
1457 s,
1458 s->chanid,
1459 s->pid);
1460 }
1461}
1462
Damien Millerefb4afe2000-04-12 18:45:05 +10001463int
1464session_open(int chanid)
1465{
1466 Session *s = session_new();
1467 debug("session_open: channel %d", chanid);
1468 if (s == NULL) {
1469 error("no more sessions");
1470 return 0;
1471 }
Damien Millerefb4afe2000-04-12 18:45:05 +10001472 s->pw = auth_get_user();
1473 if (s->pw == NULL)
Damien Millerbd483e72000-04-30 10:00:53 +10001474 fatal("no user for session %i", s->self);
1475 debug("session_open: session %d: link with channel %d", s->self, chanid);
1476 s->chanid = chanid;
Damien Millerefb4afe2000-04-12 18:45:05 +10001477 return 1;
1478}
1479
1480Session *
1481session_by_channel(int id)
1482{
1483 int i;
1484 for(i = 0; i < MAX_SESSIONS; i++) {
1485 Session *s = &sessions[i];
1486 if (s->used && s->chanid == id) {
1487 debug("session_by_channel: session %d channel %d", i, id);
1488 return s;
1489 }
1490 }
1491 debug("session_by_channel: unknown channel %d", id);
1492 session_dump();
1493 return NULL;
1494}
1495
1496Session *
1497session_by_pid(pid_t pid)
1498{
1499 int i;
1500 debug("session_by_pid: pid %d", pid);
1501 for(i = 0; i < MAX_SESSIONS; i++) {
1502 Session *s = &sessions[i];
1503 if (s->used && s->pid == pid)
1504 return s;
1505 }
1506 error("session_by_pid: unknown pid %d", pid);
1507 session_dump();
1508 return NULL;
1509}
1510
1511int
1512session_window_change_req(Session *s)
1513{
1514 s->col = packet_get_int();
1515 s->row = packet_get_int();
1516 s->xpixel = packet_get_int();
1517 s->ypixel = packet_get_int();
Damien Miller4af51302000-04-16 11:18:38 +10001518 packet_done();
Damien Millerefb4afe2000-04-12 18:45:05 +10001519 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1520 return 1;
1521}
1522
1523int
1524session_pty_req(Session *s)
1525{
1526 unsigned int len;
Damien Miller4af51302000-04-16 11:18:38 +10001527 char *term_modes; /* encoded terminal modes */
Damien Millerefb4afe2000-04-12 18:45:05 +10001528
Damien Millerf6d9e222000-06-18 14:50:44 +10001529 if (no_pty_flag)
1530 return 0;
Damien Millerefb4afe2000-04-12 18:45:05 +10001531 if (s->ttyfd != -1)
Damien Miller4af51302000-04-16 11:18:38 +10001532 return 0;
Damien Millerefb4afe2000-04-12 18:45:05 +10001533 s->term = packet_get_string(&len);
1534 s->col = packet_get_int();
1535 s->row = packet_get_int();
1536 s->xpixel = packet_get_int();
1537 s->ypixel = packet_get_int();
Damien Miller4af51302000-04-16 11:18:38 +10001538 term_modes = packet_get_string(&len);
1539 packet_done();
Damien Millerefb4afe2000-04-12 18:45:05 +10001540
1541 if (strcmp(s->term, "") == 0) {
1542 xfree(s->term);
1543 s->term = NULL;
1544 }
1545 /* Allocate a pty and open it. */
1546 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1547 xfree(s->term);
1548 s->term = NULL;
1549 s->ptyfd = -1;
1550 s->ttyfd = -1;
1551 error("session_pty_req: session %d alloc failed", s->self);
Damien Miller4af51302000-04-16 11:18:38 +10001552 xfree(term_modes);
1553 return 0;
Damien Millerefb4afe2000-04-12 18:45:05 +10001554 }
1555 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1556 /*
1557 * Add a cleanup function to clear the utmp entry and record logout
1558 * time in case we call fatal() (e.g., the connection gets closed).
1559 */
1560 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1561 pty_setowner(s->pw, s->tty);
1562 /* Get window size from the packet. */
1563 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1564
Damien Millere247cc42000-05-07 12:03:14 +10001565 session_proctitle(s);
1566
Damien Miller5f056372000-04-16 12:31:48 +10001567 /* XXX parse and set terminal modes */
1568 xfree(term_modes);
Damien Millerefb4afe2000-04-12 18:45:05 +10001569 return 1;
1570}
1571
Damien Millerbd483e72000-04-30 10:00:53 +10001572int
1573session_subsystem_req(Session *s)
1574{
1575 unsigned int len;
1576 int success = 0;
1577 char *subsys = packet_get_string(&len);
Damien Millerf6d9e222000-06-18 14:50:44 +10001578 int i;
Damien Millerbd483e72000-04-30 10:00:53 +10001579
1580 packet_done();
1581 log("subsystem request for %s", subsys);
1582
Damien Millerf6d9e222000-06-18 14:50:44 +10001583 for (i = 0; i < options.num_subsystems; i++) {
1584 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1585 debug("subsystem: exec() %s", options.subsystem_command[i]);
1586 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1587 success = 1;
1588 }
1589 }
1590
1591 if (!success)
1592 log("subsystem request for %s failed, subsystem not found", subsys);
1593
Damien Millerbd483e72000-04-30 10:00:53 +10001594 xfree(subsys);
1595 return success;
1596}
1597
1598int
1599session_x11_req(Session *s)
1600{
Damien Miller7b28dc52000-09-05 13:34:53 +11001601 int fd;
Damien Miller37023962000-07-11 17:31:38 +10001602 if (no_x11_forwarding_flag) {
Damien Millerf6d9e222000-06-18 14:50:44 +10001603 debug("X11 forwarding disabled in user configuration file.");
1604 return 0;
1605 }
Damien Millerbd483e72000-04-30 10:00:53 +10001606 if (!options.x11_forwarding) {
1607 debug("X11 forwarding disabled in server configuration file.");
1608 return 0;
1609 }
1610 if (xauthfile != NULL) {
1611 debug("X11 fwd already started.");
1612 return 0;
1613 }
1614
1615 debug("Received request for X11 forwarding with auth spoofing.");
1616 if (s->display != NULL)
1617 packet_disconnect("Protocol error: X11 display already set.");
1618
1619 s->single_connection = packet_get_char();
1620 s->auth_proto = packet_get_string(NULL);
1621 s->auth_data = packet_get_string(NULL);
1622 s->screen = packet_get_int();
1623 packet_done();
1624
1625 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1626 if (s->display == NULL) {
1627 xfree(s->auth_proto);
1628 xfree(s->auth_data);
1629 return 0;
1630 }
1631 xauthfile = xmalloc(MAXPATHLEN);
1632 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1633 temporarily_use_uid(s->pw->pw_uid);
1634 if (mkdtemp(xauthfile) == NULL) {
1635 restore_uid();
1636 error("private X11 dir: mkdtemp %s failed: %s",
1637 xauthfile, strerror(errno));
1638 xfree(xauthfile);
1639 xauthfile = NULL;
1640 xfree(s->auth_proto);
1641 xfree(s->auth_data);
1642 /* XXXX remove listening channels */
1643 return 0;
1644 }
1645 strlcat(xauthfile, "/cookies", MAXPATHLEN);
Damien Miller7b28dc52000-09-05 13:34:53 +11001646 fd = open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1647 if (fd >= 0)
1648 close(fd);
Damien Millerbd483e72000-04-30 10:00:53 +10001649 restore_uid();
1650 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1651 return 1;
1652}
1653
Damien Millerf6d9e222000-06-18 14:50:44 +10001654int
1655session_shell_req(Session *s)
1656{
1657 /* if forced_command == NULL, the shell is execed */
1658 char *shell = forced_command;
1659 packet_done();
1660 s->extended = 1;
1661 if (s->ttyfd == -1)
1662 do_exec_no_pty(s, shell, s->pw);
1663 else
1664 do_exec_pty(s, shell, s->pw);
1665 return 1;
1666}
1667
1668int
1669session_exec_req(Session *s)
1670{
1671 unsigned int len;
1672 char *command = packet_get_string(&len);
1673 packet_done();
1674 if (forced_command) {
Damien Miller7b28dc52000-09-05 13:34:53 +11001675 original_command = command;
Damien Millerf6d9e222000-06-18 14:50:44 +10001676 command = forced_command;
1677 debug("Forced command '%.500s'", forced_command);
1678 }
1679 s->extended = 1;
1680 if (s->ttyfd == -1)
1681 do_exec_no_pty(s, command, s->pw);
1682 else
1683 do_exec_pty(s, command, s->pw);
1684 if (forced_command == NULL)
1685 xfree(command);
1686 return 1;
1687}
1688
Damien Millerefb4afe2000-04-12 18:45:05 +10001689void
1690session_input_channel_req(int id, void *arg)
1691{
1692 unsigned int len;
1693 int reply;
1694 int success = 0;
1695 char *rtype;
1696 Session *s;
1697 Channel *c;
1698
1699 rtype = packet_get_string(&len);
1700 reply = packet_get_char();
1701
1702 s = session_by_channel(id);
1703 if (s == NULL)
1704 fatal("session_input_channel_req: channel %d: no session", id);
1705 c = channel_lookup(id);
1706 if (c == NULL)
1707 fatal("session_input_channel_req: channel %d: bad channel", id);
1708
1709 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1710 s->self, id, rtype, reply);
1711
1712 /*
1713 * a session is in LARVAL state until a shell
1714 * or programm is executed
1715 */
1716 if (c->type == SSH_CHANNEL_LARVAL) {
1717 if (strcmp(rtype, "shell") == 0) {
Damien Millerf6d9e222000-06-18 14:50:44 +10001718 success = session_shell_req(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001719 } else if (strcmp(rtype, "exec") == 0) {
Damien Millerf6d9e222000-06-18 14:50:44 +10001720 success = session_exec_req(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001721 } else if (strcmp(rtype, "pty-req") == 0) {
Damien Miller5f056372000-04-16 12:31:48 +10001722 success = session_pty_req(s);
Damien Millerbd483e72000-04-30 10:00:53 +10001723 } else if (strcmp(rtype, "x11-req") == 0) {
1724 success = session_x11_req(s);
1725 } else if (strcmp(rtype, "subsystem") == 0) {
1726 success = session_subsystem_req(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001727 }
1728 }
1729 if (strcmp(rtype, "window-change") == 0) {
1730 success = session_window_change_req(s);
1731 }
1732
1733 if (reply) {
1734 packet_start(success ?
1735 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1736 packet_put_int(c->remote_id);
1737 packet_send();
1738 }
1739 xfree(rtype);
1740}
1741
1742void
1743session_set_fds(Session *s, int fdin, int fdout, int fderr)
1744{
1745 if (!compat20)
1746 fatal("session_set_fds: called for proto != 2.0");
1747 /*
1748 * now that have a child and a pipe to the child,
1749 * we can activate our channel and register the fd's
1750 */
1751 if (s->chanid == -1)
1752 fatal("no channel for session %d", s->self);
1753 channel_set_fds(s->chanid,
1754 fdout, fdin, fderr,
1755 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1756}
1757
Damien Millerb38eff82000-04-01 11:09:21 +10001758void
1759session_pty_cleanup(Session *s)
1760{
1761 if (s == NULL || s->ttyfd == -1)
1762 return;
1763
1764 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1765
1766 /* Cancel the cleanup function. */
1767 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1768
1769 /* Record that the user has logged out. */
1770 record_logout(s->pid, s->tty);
1771
1772 /* Release the pseudo-tty. */
1773 pty_release(s->tty);
1774
1775 /*
1776 * Close the server side of the socket pairs. We must do this after
1777 * the pty cleanup, so that another process doesn't get this pty
1778 * while we're still cleaning up.
1779 */
1780 if (close(s->ptymaster) < 0)
1781 error("close(s->ptymaster): %s", strerror(errno));
1782}
Damien Millerefb4afe2000-04-12 18:45:05 +10001783
1784void
1785session_exit_message(Session *s, int status)
1786{
1787 Channel *c;
1788 if (s == NULL)
1789 fatal("session_close: no session");
1790 c = channel_lookup(s->chanid);
1791 if (c == NULL)
1792 fatal("session_close: session %d: no channel %d",
1793 s->self, s->chanid);
1794 debug("session_exit_message: session %d channel %d pid %d",
1795 s->self, s->chanid, s->pid);
1796
1797 if (WIFEXITED(status)) {
1798 channel_request_start(s->chanid,
1799 "exit-status", 0);
1800 packet_put_int(WEXITSTATUS(status));
1801 packet_send();
1802 } else if (WIFSIGNALED(status)) {
1803 channel_request_start(s->chanid,
1804 "exit-signal", 0);
1805 packet_put_int(WTERMSIG(status));
Damien Millerf3c6cf12000-05-17 22:08:29 +10001806#ifdef WCOREDUMP
Damien Millerefb4afe2000-04-12 18:45:05 +10001807 packet_put_char(WCOREDUMP(status));
Damien Millerf3c6cf12000-05-17 22:08:29 +10001808#else /* WCOREDUMP */
1809 packet_put_char(0);
1810#endif /* WCOREDUMP */
Damien Millerefb4afe2000-04-12 18:45:05 +10001811 packet_put_cstring("");
1812 packet_put_cstring("");
1813 packet_send();
1814 } else {
1815 /* Some weird exit cause. Just exit. */
1816 packet_disconnect("wait returned status %04x.", status);
1817 }
1818
1819 /* disconnect channel */
1820 debug("session_exit_message: release channel %d", s->chanid);
1821 channel_cancel_cleanup(s->chanid);
Damien Miller166fca82000-04-20 07:42:21 +10001822 /*
1823 * emulate a write failure with 'chan_write_failed', nobody will be
1824 * interested in data we write.
1825 * Note that we must not call 'chan_read_failed', since there could
1826 * be some more data waiting in the pipe.
1827 */
Damien Millerbd483e72000-04-30 10:00:53 +10001828 if (c->ostate != CHAN_OUTPUT_CLOSED)
1829 chan_write_failed(c);
Damien Millerefb4afe2000-04-12 18:45:05 +10001830 s->chanid = -1;
1831}
1832
1833void
1834session_free(Session *s)
1835{
1836 debug("session_free: session %d pid %d", s->self, s->pid);
1837 if (s->term)
1838 xfree(s->term);
1839 if (s->display)
1840 xfree(s->display);
1841 if (s->auth_data)
1842 xfree(s->auth_data);
1843 if (s->auth_proto)
1844 xfree(s->auth_proto);
1845 s->used = 0;
1846}
1847
1848void
1849session_close(Session *s)
1850{
1851 session_pty_cleanup(s);
1852 session_free(s);
Damien Millere247cc42000-05-07 12:03:14 +10001853 session_proctitle(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001854}
1855
1856void
1857session_close_by_pid(pid_t pid, int status)
1858{
1859 Session *s = session_by_pid(pid);
1860 if (s == NULL) {
1861 debug("session_close_by_pid: no session for pid %d", s->pid);
1862 return;
1863 }
1864 if (s->chanid != -1)
1865 session_exit_message(s, status);
1866 session_close(s);
1867}
1868
1869/*
1870 * this is called when a channel dies before
1871 * the session 'child' itself dies
1872 */
1873void
1874session_close_by_channel(int id, void *arg)
1875{
1876 Session *s = session_by_channel(id);
1877 if (s == NULL) {
1878 debug("session_close_by_channel: no session for channel %d", id);
1879 return;
1880 }
1881 /* disconnect channel */
1882 channel_cancel_cleanup(s->chanid);
1883 s->chanid = -1;
1884
1885 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1886 if (s->pid == 0) {
1887 /* close session immediately */
1888 session_close(s);
1889 } else {
1890 /* notify child, delay session cleanup */
Damien Miller099f5052000-06-22 20:57:11 +10001891 if (s->pid <= 1)
Damien Miller7a445bb2000-06-26 13:12:37 +10001892 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1893 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
Damien Millerefb4afe2000-04-12 18:45:05 +10001894 error("session_close_by_channel: kill %d: %s",
1895 s->pid, strerror(errno));
1896 }
1897}
1898
Damien Millere247cc42000-05-07 12:03:14 +10001899char *
1900session_tty_list(void)
1901{
1902 static char buf[1024];
1903 int i;
1904 buf[0] = '\0';
1905 for(i = 0; i < MAX_SESSIONS; i++) {
1906 Session *s = &sessions[i];
1907 if (s->used && s->ttyfd != -1) {
1908 if (buf[0] != '\0')
1909 strlcat(buf, ",", sizeof buf);
1910 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1911 }
1912 }
1913 if (buf[0] == '\0')
1914 strlcpy(buf, "notty", sizeof buf);
1915 return buf;
1916}
1917
1918void
1919session_proctitle(Session *s)
1920{
1921 if (s->pw == NULL)
1922 error("no user for session %d", s->self);
1923 else
1924 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1925}
1926
Damien Millerefb4afe2000-04-12 18:45:05 +10001927void
1928do_authenticated2(void)
1929{
Damien Miller87d29ed2000-08-30 09:21:22 +11001930#ifdef HAVE_LOGIN_CAP
Damien Millerad833b32000-08-23 10:46:23 +10001931 struct passwd *pw;
Damien Miller87d29ed2000-08-30 09:21:22 +11001932#endif
Damien Millerad833b32000-08-23 10:46:23 +10001933
Damien Millerefb4afe2000-04-12 18:45:05 +10001934 /*
1935 * Cancel the alarm we set to limit the time taken for
1936 * authentication.
1937 */
1938 alarm(0);
Damien Miller182ee6e2000-07-12 09:45:27 +10001939 if (startup_pipe != -1) {
Damien Miller4d97ba22000-07-11 18:15:50 +10001940 close(startup_pipe);
Damien Miller182ee6e2000-07-12 09:45:27 +10001941 startup_pipe = -1;
1942 }
Damien Millerad833b32000-08-23 10:46:23 +10001943#ifdef HAVE_LOGIN_CAP
1944 pw = auth_get_user();
1945 if ((lc = login_getclass(pw->pw_class)) == NULL) {
1946 error("unable to get login class");
1947 return;
1948 }
1949#endif
Damien Millerefb4afe2000-04-12 18:45:05 +10001950 server_loop2();
Damien Miller1b26ab22000-04-30 10:12:49 +10001951 if (xauthfile)
1952 xauthfile_cleanup_proc(NULL);
Damien Millerefb4afe2000-04-12 18:45:05 +10001953}