blob: 64e240b73a04666f0a7ca5c3a8cabaf93dee1525 [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
4 */
Damien Millerefb4afe2000-04-12 18:45:05 +10005/*
6 * SSH2 support by Markus Friedl.
7 * Copyright (c) 2000 Markus Friedl. All rights reserved.
8 */
Damien Millerb38eff82000-04-01 11:09:21 +10009
10#include "includes.h"
Damien Millerf6d9e222000-06-18 14:50:44 +100011RCSID("$OpenBSD: session.c,v 1.20 2000/06/18 04:42:54 markus Exp $");
Damien Millerb38eff82000-04-01 11:09:21 +100012
13#include "xmalloc.h"
14#include "ssh.h"
15#include "pty.h"
16#include "packet.h"
17#include "buffer.h"
18#include "cipher.h"
19#include "mpaux.h"
20#include "servconf.h"
21#include "uidswap.h"
22#include "compat.h"
23#include "channels.h"
24#include "nchan.h"
25
Damien Millerefb4afe2000-04-12 18:45:05 +100026#include "bufaux.h"
27#include "ssh2.h"
28#include "auth.h"
Damien Millerf6d9e222000-06-18 14:50:44 +100029#include "auth-options.h"
Damien Millerefb4afe2000-04-12 18:45:05 +100030
Damien Millerb38eff82000-04-01 11:09:21 +100031/* types */
32
33#define TTYSZ 64
34typedef struct Session Session;
35struct Session {
36 int used;
37 int self;
Damien Millerbd483e72000-04-30 10:00:53 +100038 int extended;
Damien Millerb38eff82000-04-01 11:09:21 +100039 struct passwd *pw;
40 pid_t pid;
41 /* tty */
42 char *term;
43 int ptyfd, ttyfd, ptymaster;
44 int row, col, xpixel, ypixel;
45 char tty[TTYSZ];
46 /* X11 */
47 char *display;
48 int screen;
49 char *auth_proto;
50 char *auth_data;
Damien Millerbd483e72000-04-30 10:00:53 +100051 int single_connection;
Damien Millerb38eff82000-04-01 11:09:21 +100052 /* proto 2 */
53 int chanid;
54};
55
56/* func */
57
58Session *session_new(void);
59void session_set_fds(Session *s, int fdin, int fdout, int fderr);
60void session_pty_cleanup(Session *s);
Damien Millere247cc42000-05-07 12:03:14 +100061void session_proctitle(Session *s);
Damien Millerb38eff82000-04-01 11:09:21 +100062void do_exec_pty(Session *s, const char *command, struct passwd * pw);
63void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
64
65void
66do_child(const char *command, struct passwd * pw, const char *term,
67 const char *display, const char *auth_proto,
68 const char *auth_data, const char *ttyname);
69
70/* import */
71extern ServerOptions options;
Damien Miller06d84b72000-04-21 16:13:07 +100072#ifdef HAVE___PROGNAME
Damien Millerb38eff82000-04-01 11:09:21 +100073extern char *__progname;
Damien Miller06d84b72000-04-21 16:13:07 +100074#else /* HAVE___PROGNAME */
Damien Miller70fb6712000-05-01 20:59:50 +100075static const char *__progname = "sshd";
Damien Miller06d84b72000-04-21 16:13:07 +100076#endif /* HAVE___PROGNAME */
77
Damien Millerb38eff82000-04-01 11:09:21 +100078extern int log_stderr;
79extern int debug_flag;
80
81/* Local Xauthority file. */
82static char *xauthfile;
83
84/* data */
85#define MAX_SESSIONS 10
86Session sessions[MAX_SESSIONS];
Damien Millerd2c208a2000-05-17 22:00:02 +100087#ifdef WITH_AIXAUTHENTICATE
88/* AIX's lastlogin message, set in auth1.c */
89char *aixloginmsg;
90#endif /* WITH_AIXAUTHENTICATE */
Damien Millerb38eff82000-04-01 11:09:21 +100091
Damien Millerb38eff82000-04-01 11:09:21 +100092/*
93 * Remove local Xauthority file.
94 */
95void
96xauthfile_cleanup_proc(void *ignore)
97{
98 debug("xauthfile_cleanup_proc called");
99
100 if (xauthfile != NULL) {
101 char *p;
102 unlink(xauthfile);
103 p = strrchr(xauthfile, '/');
104 if (p != NULL) {
105 *p = '\0';
106 rmdir(xauthfile);
107 }
108 xfree(xauthfile);
109 xauthfile = NULL;
110 }
111}
112
113/*
114 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
115 * dropped connection).
116 */
Damien Miller4af51302000-04-16 11:18:38 +1000117void
Damien Millerb38eff82000-04-01 11:09:21 +1000118pty_cleanup_proc(void *session)
119{
120 Session *s=session;
121 if (s == NULL)
122 fatal("pty_cleanup_proc: no session");
123 debug("pty_cleanup_proc: %s", s->tty);
124
125 if (s->pid != 0) {
126 /* Record that the user has logged out. */
127 record_logout(s->pid, s->tty);
128 }
129
130 /* Release the pseudo-tty. */
131 pty_release(s->tty);
132}
133
134/*
135 * Prepares for an interactive session. This is called after the user has
136 * been successfully authenticated. During this message exchange, pseudo
137 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
138 * are requested, etc.
139 */
Damien Miller4af51302000-04-16 11:18:38 +1000140void
Damien Millerb38eff82000-04-01 11:09:21 +1000141do_authenticated(struct passwd * pw)
142{
143 Session *s;
144 int type;
145 int compression_level = 0, enable_compression_after_reply = 0;
146 int have_pty = 0;
147 char *command;
148 int n_bytes;
149 int plen;
150 unsigned int proto_len, data_len, dlen;
151
152 /*
153 * Cancel the alarm we set to limit the time taken for
154 * authentication.
155 */
156 alarm(0);
157
158 /*
159 * Inform the channel mechanism that we are the server side and that
160 * the client may request to connect to any port at all. (The user
161 * could do it anyway, and we wouldn\'t know what is permitted except
162 * by the client telling us, so we can equally well trust the client
163 * not to request anything bogus.)
164 */
165 if (!no_port_forwarding_flag)
166 channel_permit_all_opens();
167
168 s = session_new();
Damien Millerbd483e72000-04-30 10:00:53 +1000169 s->pw = pw;
Damien Millerb38eff82000-04-01 11:09:21 +1000170
171 /*
172 * We stay in this loop until the client requests to execute a shell
173 * or a command.
174 */
175 for (;;) {
176 int success = 0;
177
178 /* Get a packet from the client. */
179 type = packet_read(&plen);
180
181 /* Process the packet. */
182 switch (type) {
183 case SSH_CMSG_REQUEST_COMPRESSION:
184 packet_integrity_check(plen, 4, type);
185 compression_level = packet_get_int();
186 if (compression_level < 1 || compression_level > 9) {
187 packet_send_debug("Received illegal compression level %d.",
188 compression_level);
189 break;
190 }
191 /* Enable compression after we have responded with SUCCESS. */
192 enable_compression_after_reply = 1;
193 success = 1;
194 break;
195
196 case SSH_CMSG_REQUEST_PTY:
197 if (no_pty_flag) {
198 debug("Allocating a pty not permitted for this authentication.");
199 break;
200 }
201 if (have_pty)
202 packet_disconnect("Protocol error: you already have a pty.");
203
204 debug("Allocating pty.");
205
206 /* Allocate a pty and open it. */
207 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
208 sizeof(s->tty))) {
209 error("Failed to allocate pty.");
210 break;
211 }
212 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
213 pty_setowner(pw, s->tty);
214
215 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
216 s->term = packet_get_string(&dlen);
217 packet_integrity_check(dlen, strlen(s->term), type);
218 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
219 /* Remaining bytes */
220 n_bytes = plen - (4 + dlen + 4 * 4);
221
222 if (strcmp(s->term, "") == 0) {
223 xfree(s->term);
224 s->term = NULL;
225 }
226 /* Get window size from the packet. */
227 s->row = packet_get_int();
228 s->col = packet_get_int();
229 s->xpixel = packet_get_int();
230 s->ypixel = packet_get_int();
231 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
232
233 /* Get tty modes from the packet. */
234 tty_parse_modes(s->ttyfd, &n_bytes);
235 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
236
Damien Millere247cc42000-05-07 12:03:14 +1000237 session_proctitle(s);
238
Damien Millerb38eff82000-04-01 11:09:21 +1000239 /* Indicate that we now have a pty. */
240 success = 1;
241 have_pty = 1;
242 break;
243
244 case SSH_CMSG_X11_REQUEST_FORWARDING:
245 if (!options.x11_forwarding) {
246 packet_send_debug("X11 forwarding disabled in server configuration file.");
247 break;
248 }
Damien Miller0c043c12000-06-07 21:22:38 +1000249 if (!options.xauth_location) {
250 packet_send_debug("No xauth program; cannot forward with spoofing.");
251 break;
252 }
Damien Millerb38eff82000-04-01 11:09:21 +1000253 if (no_x11_forwarding_flag) {
254 packet_send_debug("X11 forwarding not permitted for this authentication.");
255 break;
256 }
257 debug("Received request for X11 forwarding with auth spoofing.");
258 if (s->display != NULL)
259 packet_disconnect("Protocol error: X11 display already set.");
260
261 s->auth_proto = packet_get_string(&proto_len);
262 s->auth_data = packet_get_string(&data_len);
263 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
264
265 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
266 s->screen = packet_get_int();
267 else
268 s->screen = 0;
269 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
270
271 if (s->display == NULL)
272 break;
273
274 /* Setup to always have a local .Xauthority. */
275 xauthfile = xmalloc(MAXPATHLEN);
276 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
277 temporarily_use_uid(pw->pw_uid);
278 if (mkdtemp(xauthfile) == NULL) {
279 restore_uid();
280 error("private X11 dir: mkdtemp %s failed: %s",
281 xauthfile, strerror(errno));
282 xfree(xauthfile);
283 xauthfile = NULL;
Damien Millerbd483e72000-04-30 10:00:53 +1000284 /* XXXX remove listening channels */
Damien Millerb38eff82000-04-01 11:09:21 +1000285 break;
286 }
287 strlcat(xauthfile, "/cookies", MAXPATHLEN);
288 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
289 restore_uid();
290 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
291 success = 1;
292 break;
Damien Millerb38eff82000-04-01 11:09:21 +1000293
294 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
295 if (no_agent_forwarding_flag || compat13) {
296 debug("Authentication agent forwarding not permitted for this authentication.");
297 break;
298 }
299 debug("Received authentication agent forwarding request.");
Damien Miller0c043c12000-06-07 21:22:38 +1000300 success = auth_input_request_forwarding(pw);
Damien Millerb38eff82000-04-01 11:09:21 +1000301 break;
302
303 case SSH_CMSG_PORT_FORWARD_REQUEST:
304 if (no_port_forwarding_flag) {
305 debug("Port forwarding not permitted for this authentication.");
306 break;
307 }
308 debug("Received TCP/IP port forwarding request.");
Damien Millere247cc42000-05-07 12:03:14 +1000309 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
Damien Millerb38eff82000-04-01 11:09:21 +1000310 success = 1;
311 break;
312
313 case SSH_CMSG_MAX_PACKET_SIZE:
314 if (packet_set_maxsize(packet_get_int()) > 0)
315 success = 1;
316 break;
317
318 case SSH_CMSG_EXEC_SHELL:
319 case SSH_CMSG_EXEC_CMD:
320 /* Set interactive/non-interactive mode. */
321 packet_set_interactive(have_pty || s->display != NULL,
322 options.keepalives);
323
324 if (type == SSH_CMSG_EXEC_CMD) {
325 command = packet_get_string(&dlen);
326 debug("Exec command '%.500s'", command);
327 packet_integrity_check(plen, 4 + dlen, type);
328 } else {
329 command = NULL;
330 packet_integrity_check(plen, 0, type);
331 }
332 if (forced_command != NULL) {
333 command = forced_command;
334 debug("Forced command '%.500s'", forced_command);
335 }
336 if (have_pty)
337 do_exec_pty(s, command, pw);
338 else
339 do_exec_no_pty(s, command, pw);
340
341 if (command != NULL)
342 xfree(command);
343 /* Cleanup user's local Xauthority file. */
344 if (xauthfile)
345 xauthfile_cleanup_proc(NULL);
346 return;
347
348 default:
349 /*
350 * Any unknown messages in this phase are ignored,
351 * and a failure message is returned.
352 */
353 log("Unknown packet type received after authentication: %d", type);
354 }
355 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
356 packet_send();
357 packet_write_wait();
358
359 /* Enable compression now that we have replied if appropriate. */
360 if (enable_compression_after_reply) {
361 enable_compression_after_reply = 0;
362 packet_start_compression(compression_level);
363 }
364 }
365}
366
367/*
368 * This is called to fork and execute a command when we have no tty. This
369 * will call do_child from the child, and server_loop from the parent after
370 * setting up file descriptors and such.
371 */
Damien Miller4af51302000-04-16 11:18:38 +1000372void
Damien Millerb38eff82000-04-01 11:09:21 +1000373do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
374{
375 int pid;
376
377#ifdef USE_PIPES
378 int pin[2], pout[2], perr[2];
379 /* Allocate pipes for communicating with the program. */
380 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
381 packet_disconnect("Could not create pipes: %.100s",
382 strerror(errno));
383#else /* USE_PIPES */
384 int inout[2], err[2];
385 /* Uses socket pairs to communicate with the program. */
386 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
387 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
388 packet_disconnect("Could not create socket pairs: %.100s",
389 strerror(errno));
390#endif /* USE_PIPES */
391 if (s == NULL)
392 fatal("do_exec_no_pty: no session");
393
Damien Millere247cc42000-05-07 12:03:14 +1000394 session_proctitle(s);
Damien Millerb38eff82000-04-01 11:09:21 +1000395
396#ifdef USE_PAM
397 do_pam_setcred();
398#endif /* USE_PAM */
399
400 /* Fork the child. */
401 if ((pid = fork()) == 0) {
402 /* Child. Reinitialize the log since the pid has changed. */
403 log_init(__progname, options.log_level, options.log_facility, log_stderr);
404
405 /*
406 * Create a new session and process group since the 4.4BSD
407 * setlogin() affects the entire process group.
408 */
409 if (setsid() < 0)
410 error("setsid failed: %.100s", strerror(errno));
411
412#ifdef USE_PIPES
413 /*
414 * Redirect stdin. We close the parent side of the socket
415 * pair, and make the child side the standard input.
416 */
417 close(pin[1]);
418 if (dup2(pin[0], 0) < 0)
419 perror("dup2 stdin");
420 close(pin[0]);
421
422 /* Redirect stdout. */
423 close(pout[0]);
424 if (dup2(pout[1], 1) < 0)
425 perror("dup2 stdout");
426 close(pout[1]);
427
428 /* Redirect stderr. */
429 close(perr[0]);
430 if (dup2(perr[1], 2) < 0)
431 perror("dup2 stderr");
432 close(perr[1]);
433#else /* USE_PIPES */
434 /*
435 * Redirect stdin, stdout, and stderr. Stdin and stdout will
436 * use the same socket, as some programs (particularly rdist)
437 * seem to depend on it.
438 */
439 close(inout[1]);
440 close(err[1]);
441 if (dup2(inout[0], 0) < 0) /* stdin */
442 perror("dup2 stdin");
443 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
444 perror("dup2 stdout");
445 if (dup2(err[0], 2) < 0) /* stderr */
446 perror("dup2 stderr");
447#endif /* USE_PIPES */
448
449 /* Do processing for the child (exec command etc). */
450 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
451 /* NOTREACHED */
452 }
453 if (pid < 0)
454 packet_disconnect("fork failed: %.100s", strerror(errno));
455 s->pid = pid;
456#ifdef USE_PIPES
457 /* We are the parent. Close the child sides of the pipes. */
458 close(pin[0]);
459 close(pout[1]);
460 close(perr[1]);
461
Damien Millerefb4afe2000-04-12 18:45:05 +1000462 if (compat20) {
Damien Millerbd483e72000-04-30 10:00:53 +1000463 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
Damien Millerefb4afe2000-04-12 18:45:05 +1000464 } else {
465 /* Enter the interactive session. */
466 server_loop(pid, pin[1], pout[0], perr[0]);
467 /* server_loop has closed pin[1], pout[1], and perr[1]. */
468 }
Damien Millerb38eff82000-04-01 11:09:21 +1000469#else /* USE_PIPES */
470 /* We are the parent. Close the child sides of the socket pairs. */
471 close(inout[0]);
472 close(err[0]);
473
474 /*
475 * Enter the interactive session. Note: server_loop must be able to
476 * handle the case that fdin and fdout are the same.
477 */
Damien Millerefb4afe2000-04-12 18:45:05 +1000478 if (compat20) {
Damien Millerbd483e72000-04-30 10:00:53 +1000479 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
Damien Millerefb4afe2000-04-12 18:45:05 +1000480 } else {
481 server_loop(pid, inout[1], inout[1], err[1]);
482 /* server_loop has closed inout[1] and err[1]. */
483 }
Damien Millerb38eff82000-04-01 11:09:21 +1000484#endif /* USE_PIPES */
485}
486
487/*
488 * This is called to fork and execute a command when we have a tty. This
489 * will call do_child from the child, and server_loop from the parent after
490 * setting up file descriptors, controlling tty, updating wtmp, utmp,
491 * lastlog, and other such operations.
492 */
Damien Miller4af51302000-04-16 11:18:38 +1000493void
Damien Millerb38eff82000-04-01 11:09:21 +1000494do_exec_pty(Session *s, const char *command, struct passwd * pw)
495{
496 FILE *f;
497 char buf[100], *time_string;
498 char line[256];
499 const char *hostname;
500 int fdout, ptyfd, ttyfd, ptymaster;
501 int quiet_login;
502 pid_t pid;
503 socklen_t fromlen;
504 struct sockaddr_storage from;
505 struct stat st;
506 time_t last_login_time;
507
508 if (s == NULL)
509 fatal("do_exec_pty: no session");
510 ptyfd = s->ptyfd;
511 ttyfd = s->ttyfd;
512
513 /* Get remote host name. */
514 hostname = get_canonical_hostname();
515
516 /*
517 * Get the time when the user last logged in. Buf will be set to
518 * contain the hostname the last login was from.
519 */
520 if (!options.use_login) {
521 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
522 buf, sizeof(buf));
523 }
Damien Millerb38eff82000-04-01 11:09:21 +1000524
525#ifdef USE_PAM
526 do_pam_session(pw->pw_name, s->tty);
527 do_pam_setcred();
528#endif /* USE_PAM */
529
530 /* Fork the child. */
531 if ((pid = fork()) == 0) {
532 pid = getpid();
533
534 /* Child. Reinitialize the log because the pid has
535 changed. */
536 log_init(__progname, options.log_level, options.log_facility, log_stderr);
537
538 /* Close the master side of the pseudo tty. */
539 close(ptyfd);
540
541 /* Make the pseudo tty our controlling tty. */
542 pty_make_controlling_tty(&ttyfd, s->tty);
543
544 /* Redirect stdin from the pseudo tty. */
545 if (dup2(ttyfd, fileno(stdin)) < 0)
546 error("dup2 stdin failed: %.100s", strerror(errno));
547
548 /* Redirect stdout to the pseudo tty. */
549 if (dup2(ttyfd, fileno(stdout)) < 0)
550 error("dup2 stdin failed: %.100s", strerror(errno));
551
552 /* Redirect stderr to the pseudo tty. */
553 if (dup2(ttyfd, fileno(stderr)) < 0)
554 error("dup2 stdin failed: %.100s", strerror(errno));
555
556 /* Close the extra descriptor for the pseudo tty. */
557 close(ttyfd);
558
Damien Millere247cc42000-05-07 12:03:14 +1000559/* XXXX ? move to do_child() ??*/
Damien Millerb38eff82000-04-01 11:09:21 +1000560 /*
561 * Get IP address of client. This is needed because we want
562 * to record where the user logged in from. If the
563 * connection is not a socket, let the ip address be 0.0.0.0.
564 */
565 memset(&from, 0, sizeof(from));
566 if (packet_connection_is_on_socket()) {
567 fromlen = sizeof(from);
568 if (getpeername(packet_get_connection_in(),
569 (struct sockaddr *) & from, &fromlen) < 0) {
570 debug("getpeername: %.100s", strerror(errno));
571 fatal_cleanup();
572 }
573 }
574 /* Record that there was a login on that terminal. */
575 record_login(pid, s->tty, pw->pw_name, pw->pw_uid, hostname,
576 (struct sockaddr *)&from);
577
578 /* Check if .hushlogin exists. */
579 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
580 quiet_login = stat(line, &st) >= 0;
581
582#ifdef USE_PAM
583 if (!quiet_login)
584 print_pam_messages();
585#endif /* USE_PAM */
586
587 /*
588 * If the user has logged in before, display the time of last
589 * login. However, don't display anything extra if a command
590 * has been specified (so that ssh can be used to execute
591 * commands on a remote machine without users knowing they
592 * are going to another machine). Login(1) will do this for
593 * us as well, so check if login(1) is used
594 */
595 if (command == NULL && last_login_time != 0 && !quiet_login &&
596 !options.use_login) {
597 /* Convert the date to a string. */
598 time_string = ctime(&last_login_time);
599 /* Remove the trailing newline. */
600 if (strchr(time_string, '\n'))
601 *strchr(time_string, '\n') = 0;
602 /* Display the last login time. Host if displayed
603 if known. */
604 if (strcmp(buf, "") == 0)
605 printf("Last login: %s\r\n", time_string);
606 else
607 printf("Last login: %s from %s\r\n", time_string, buf);
608 }
609 /*
610 * Print /etc/motd unless a command was specified or printing
611 * it was disabled in server options or login(1) will be
612 * used. Note that some machines appear to print it in
613 * /etc/profile or similar.
614 */
615 if (command == NULL && options.print_motd && !quiet_login &&
616 !options.use_login) {
617 /* Print /etc/motd if it exists. */
618 f = fopen("/etc/motd", "r");
619 if (f) {
620 while (fgets(line, sizeof(line), f))
621 fputs(line, stdout);
622 fclose(f);
623 }
624 }
Damien Millerd2c208a2000-05-17 22:00:02 +1000625#if defined(WITH_AIXAUTHENTICATE)
626 /*
627 * AIX handles the lastlog info differently. Display it here.
628 */
629 if (command == NULL && aixloginmsg && *aixloginmsg &&
630 !quiet_login && !options.use_login) {
631 printf("%s\n", aixloginmsg);
632 }
633#endif
Damien Millerb38eff82000-04-01 11:09:21 +1000634 /* Do common processing for the child, such as execing the command. */
Damien Millerb1715dc2000-05-30 13:44:51 +1000635 do_child(command, pw, s->term, s->display, s->auth_proto,
636 s->auth_data, s->tty);
Damien Millerb38eff82000-04-01 11:09:21 +1000637 /* NOTREACHED */
638 }
639 if (pid < 0)
640 packet_disconnect("fork failed: %.100s", strerror(errno));
641 s->pid = pid;
642
643 /* Parent. Close the slave side of the pseudo tty. */
644 close(ttyfd);
645
646 /*
647 * Create another descriptor of the pty master side for use as the
648 * standard input. We could use the original descriptor, but this
649 * simplifies code in server_loop. The descriptor is bidirectional.
650 */
651 fdout = dup(ptyfd);
652 if (fdout < 0)
653 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
654
655 /* we keep a reference to the pty master */
656 ptymaster = dup(ptyfd);
657 if (ptymaster < 0)
658 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
659 s->ptymaster = ptymaster;
660
661 /* Enter interactive session. */
Damien Millerefb4afe2000-04-12 18:45:05 +1000662 if (compat20) {
663 session_set_fds(s, ptyfd, fdout, -1);
664 } else {
665 server_loop(pid, ptyfd, fdout, -1);
666 /* server_loop _has_ closed ptyfd and fdout. */
667 session_pty_cleanup(s);
668 }
Damien Millerb38eff82000-04-01 11:09:21 +1000669}
670
671/*
672 * Sets the value of the given variable in the environment. If the variable
673 * already exists, its value is overriden.
674 */
Damien Miller4af51302000-04-16 11:18:38 +1000675void
Damien Millerb38eff82000-04-01 11:09:21 +1000676child_set_env(char ***envp, unsigned int *envsizep, const char *name,
677 const char *value)
678{
679 unsigned int i, namelen;
680 char **env;
681
682 /*
683 * Find the slot where the value should be stored. If the variable
684 * already exists, we reuse the slot; otherwise we append a new slot
685 * at the end of the array, expanding if necessary.
686 */
687 env = *envp;
688 namelen = strlen(name);
689 for (i = 0; env[i]; i++)
690 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
691 break;
692 if (env[i]) {
693 /* Reuse the slot. */
694 xfree(env[i]);
695 } else {
696 /* New variable. Expand if necessary. */
697 if (i >= (*envsizep) - 1) {
698 (*envsizep) += 50;
699 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
700 }
701 /* Need to set the NULL pointer at end of array beyond the new slot. */
702 env[i + 1] = NULL;
703 }
704
705 /* Allocate space and format the variable in the appropriate slot. */
706 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
707 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
708}
709
710/*
711 * Reads environment variables from the given file and adds/overrides them
712 * into the environment. If the file does not exist, this does nothing.
713 * Otherwise, it must consist of empty lines, comments (line starts with '#')
714 * and assignments of the form name=value. No other forms are allowed.
715 */
Damien Miller4af51302000-04-16 11:18:38 +1000716void
Damien Millerb38eff82000-04-01 11:09:21 +1000717read_environment_file(char ***env, unsigned int *envsize,
718 const char *filename)
719{
720 FILE *f;
721 char buf[4096];
722 char *cp, *value;
723
724 f = fopen(filename, "r");
725 if (!f)
726 return;
727
728 while (fgets(buf, sizeof(buf), f)) {
729 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
730 ;
731 if (!*cp || *cp == '#' || *cp == '\n')
732 continue;
733 if (strchr(cp, '\n'))
734 *strchr(cp, '\n') = '\0';
735 value = strchr(cp, '=');
736 if (value == NULL) {
737 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
738 continue;
739 }
Damien Millerb1715dc2000-05-30 13:44:51 +1000740 /*
741 * Replace the equals sign by nul, and advance value to
742 * the value string.
743 */
Damien Millerb38eff82000-04-01 11:09:21 +1000744 *value = '\0';
745 value++;
746 child_set_env(env, envsize, cp, value);
747 }
748 fclose(f);
749}
750
751#ifdef USE_PAM
752/*
753 * Sets any environment variables which have been specified by PAM
754 */
755void do_pam_environment(char ***env, int *envsize)
756{
757 char *equals, var_name[512], var_val[512];
758 char **pam_env;
759 int i;
760
761 if ((pam_env = fetch_pam_environment()) == NULL)
762 return;
763
764 for(i = 0; pam_env[i] != NULL; i++) {
765 if ((equals = strstr(pam_env[i], "=")) == NULL)
766 continue;
767
768 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
769 memset(var_name, '\0', sizeof(var_name));
770 memset(var_val, '\0', sizeof(var_val));
771
772 strncpy(var_name, pam_env[i], equals - pam_env[i]);
773 strcpy(var_val, equals + 1);
774
775 debug("PAM environment: %s=%s", var_name, var_val);
776
777 child_set_env(env, envsize, var_name, var_val);
778 }
779 }
780}
781#endif /* USE_PAM */
782
783/*
784 * Performs common processing for the child, such as setting up the
785 * environment, closing extra file descriptors, setting the user and group
786 * ids, and executing the command or shell.
787 */
Damien Miller4af51302000-04-16 11:18:38 +1000788void
Damien Millerb38eff82000-04-01 11:09:21 +1000789do_child(const char *command, struct passwd * pw, const char *term,
790 const char *display, const char *auth_proto,
791 const char *auth_data, const char *ttyname)
792{
793 const char *shell, *cp = NULL;
794 char buf[256];
Damien Miller0c043c12000-06-07 21:22:38 +1000795 char cmd[1024];
Damien Millerb38eff82000-04-01 11:09:21 +1000796 FILE *f;
797 unsigned int envsize, i;
798 char **env;
799 extern char **environ;
800 struct stat st;
801 char *argv[10];
802
Damien Millerd3a18572000-06-07 19:55:44 +1000803 /* login(1) is only called if we execute the login shell */
804 if (options.use_login && command != NULL)
805 options.use_login = 0;
806
Damien Millerb38eff82000-04-01 11:09:21 +1000807#ifndef USE_PAM /* pam_nologin handles this */
808 f = fopen("/etc/nologin", "r");
809 if (f) {
810 /* /etc/nologin exists. Print its contents and exit. */
811 while (fgets(buf, sizeof(buf), f))
812 fputs(buf, stderr);
813 fclose(f);
814 if (pw->pw_uid != 0)
815 exit(254);
816 }
817#endif /* USE_PAM */
818
819 /* Set login name in the kernel. */
820 if (setlogin(pw->pw_name) < 0)
821 error("setlogin failed: %s", strerror(errno));
822
823 /* Set uid, gid, and groups. */
824 /* Login(1) does this as well, and it needs uid 0 for the "-h"
825 switch, so we let login(1) to this for us. */
826 if (!options.use_login) {
827 if (getuid() == 0 || geteuid() == 0) {
828 if (setgid(pw->pw_gid) < 0) {
829 perror("setgid");
830 exit(1);
831 }
832 /* Initialize the group list. */
833 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
834 perror("initgroups");
835 exit(1);
836 }
837 endgrent();
838
839 /* Permanently switch to the desired uid. */
840 permanently_set_uid(pw->pw_uid);
841 }
842 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
843 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
844 }
845 /*
846 * Get the shell from the password data. An empty shell field is
847 * legal, and means /bin/sh.
848 */
849 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
850
851#ifdef AFS
852 /* Try to get AFS tokens for the local cell. */
853 if (k_hasafs()) {
854 char cell[64];
855
856 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
857 krb_afslog(cell, 0);
858
859 krb_afslog(0, 0);
860 }
861#endif /* AFS */
862
863 /* Initialize the environment. */
864 envsize = 100;
865 env = xmalloc(envsize * sizeof(char *));
866 env[0] = NULL;
867
868 if (!options.use_login) {
869 /* Set basic environment. */
870 child_set_env(&env, &envsize, "USER", pw->pw_name);
871 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
872 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
873 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
874
875 snprintf(buf, sizeof buf, "%.200s/%.50s",
876 _PATH_MAILDIR, pw->pw_name);
877 child_set_env(&env, &envsize, "MAIL", buf);
878
879 /* Normal systems set SHELL by default. */
880 child_set_env(&env, &envsize, "SHELL", shell);
881 }
882 if (getenv("TZ"))
883 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
884
885 /* Set custom environment options from RSA authentication. */
886 while (custom_environment) {
887 struct envstring *ce = custom_environment;
888 char *s = ce->s;
889 int i;
890 for (i = 0; s[i] != '=' && s[i]; i++);
891 if (s[i] == '=') {
892 s[i] = 0;
893 child_set_env(&env, &envsize, s, s + i + 1);
894 }
895 custom_environment = ce->next;
896 xfree(ce->s);
897 xfree(ce);
898 }
899
900 snprintf(buf, sizeof buf, "%.50s %d %d",
901 get_remote_ipaddr(), get_remote_port(), get_local_port());
902 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
903
904 if (ttyname)
905 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
906 if (term)
907 child_set_env(&env, &envsize, "TERM", term);
908 if (display)
909 child_set_env(&env, &envsize, "DISPLAY", display);
910
911#ifdef _AIX
912 {
913 char *authstate,*krb5cc;
914
915 if ((authstate = getenv("AUTHSTATE")) != NULL)
916 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
917
918 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
919 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
920 }
921#endif
922
923#ifdef KRB4
924 {
925 extern char *ticket;
926
927 if (ticket)
928 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
929 }
930#endif /* KRB4 */
931
932#ifdef USE_PAM
933 /* Pull in any environment variables that may have been set by PAM. */
934 do_pam_environment(&env, &envsize);
935#endif /* USE_PAM */
936
937 read_environment_file(&env,&envsize,"/etc/environment");
938
939 if (xauthfile)
940 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
941 if (auth_get_socket_name() != NULL)
942 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
943 auth_get_socket_name());
944
945 /* read $HOME/.ssh/environment. */
946 if (!options.use_login) {
Damien Millerb1715dc2000-05-30 13:44:51 +1000947 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
948 pw->pw_dir);
Damien Millerb38eff82000-04-01 11:09:21 +1000949 read_environment_file(&env, &envsize, buf);
950 }
951 if (debug_flag) {
952 /* dump the environment */
953 fprintf(stderr, "Environment:\n");
954 for (i = 0; env[i]; i++)
955 fprintf(stderr, " %.200s\n", env[i]);
956 }
957 /*
958 * Close the connection descriptors; note that this is the child, and
959 * the server will still have the socket open, and it is important
960 * that we do not shutdown it. Note that the descriptors cannot be
961 * closed before building the environment, as we call
962 * get_remote_ipaddr there.
963 */
964 if (packet_get_connection_in() == packet_get_connection_out())
965 close(packet_get_connection_in());
966 else {
967 close(packet_get_connection_in());
968 close(packet_get_connection_out());
969 }
970 /*
971 * Close all descriptors related to channels. They will still remain
972 * open in the parent.
973 */
974 /* XXX better use close-on-exec? -markus */
975 channel_close_all();
976
977 /*
978 * Close any extra file descriptors. Note that there may still be
979 * descriptors left by system functions. They will be closed later.
980 */
981 endpwent();
982
983 /*
984 * Close any extra open file descriptors so that we don\'t have them
985 * hanging around in clients. Note that we want to do this after
986 * initgroups, because at least on Solaris 2.3 it leaves file
987 * descriptors open.
988 */
989 for (i = 3; i < 64; i++)
990 close(i);
991
992 /* Change current directory to the user\'s home directory. */
993 if (chdir(pw->pw_dir) < 0)
994 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
995 pw->pw_dir, strerror(errno));
996
997 /*
998 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
999 * xauth are run in the proper environment.
1000 */
1001 environ = env;
1002
1003 /*
1004 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1005 * in this order).
1006 */
1007 if (!options.use_login) {
1008 if (stat(SSH_USER_RC, &st) >= 0) {
1009 if (debug_flag)
1010 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
1011
1012 f = popen("/bin/sh " SSH_USER_RC, "w");
1013 if (f) {
1014 if (auth_proto != NULL && auth_data != NULL)
1015 fprintf(f, "%s %s\n", auth_proto, auth_data);
1016 pclose(f);
1017 } else
1018 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1019 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1020 if (debug_flag)
1021 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
1022
1023 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
1024 if (f) {
1025 if (auth_proto != NULL && auth_data != NULL)
1026 fprintf(f, "%s %s\n", auth_proto, auth_data);
1027 pclose(f);
1028 } else
1029 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
Damien Miller0c043c12000-06-07 21:22:38 +10001030 } else if (options.xauth_location != NULL) {
Damien Millerb38eff82000-04-01 11:09:21 +10001031 /* Add authority data to .Xauthority if appropriate. */
1032 if (auth_proto != NULL && auth_data != NULL) {
Damien Millerd999ae22000-05-20 12:49:31 +10001033 char *screen = strchr(display, ':');
1034 if (debug_flag) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001035 fprintf(stderr,
1036 "Running %.100s add %.100s %.100s %.100s\n",
Damien Miller0c043c12000-06-07 21:22:38 +10001037 options.xauth_location, display,
1038 auth_proto, auth_data);
Damien Millerd999ae22000-05-20 12:49:31 +10001039 if (screen != NULL)
Damien Millerb1715dc2000-05-30 13:44:51 +10001040 fprintf(stderr,
1041 "Adding %.*s/unix%s %s %s\n",
1042 screen-display, display,
1043 screen, auth_proto, auth_data);
Damien Millerd999ae22000-05-20 12:49:31 +10001044 }
Damien Miller0c043c12000-06-07 21:22:38 +10001045 snprintf(cmd, sizeof cmd, "%s -q -",
1046 options.xauth_location);
1047 f = popen(cmd, "w");
Damien Millerb38eff82000-04-01 11:09:21 +10001048 if (f) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001049 fprintf(f, "add %s %s %s\n", display,
1050 auth_proto, auth_data);
Damien Millerd999ae22000-05-20 12:49:31 +10001051 if (screen != NULL)
1052 fprintf(f, "add %.*s/unix%s %s %s\n",
Damien Millerb1715dc2000-05-30 13:44:51 +10001053 screen-display, display,
1054 screen, auth_proto, auth_data);
Damien Millerb38eff82000-04-01 11:09:21 +10001055 pclose(f);
Damien Miller0c043c12000-06-07 21:22:38 +10001056 } else {
1057 fprintf(stderr, "Could not run %s\n",
1058 cmd);
1059 }
Damien Millerb38eff82000-04-01 11:09:21 +10001060 }
1061 }
Damien Millerb38eff82000-04-01 11:09:21 +10001062 /* Get the last component of the shell name. */
1063 cp = strrchr(shell, '/');
1064 if (cp)
1065 cp++;
1066 else
1067 cp = shell;
1068 }
1069 /*
1070 * If we have no command, execute the shell. In this case, the shell
1071 * name to be passed in argv[0] is preceded by '-' to indicate that
1072 * this is a login shell.
1073 */
1074 if (!command) {
1075 if (!options.use_login) {
1076 char buf[256];
1077
1078 /*
1079 * Check for mail if we have a tty and it was enabled
1080 * in server options.
1081 */
1082 if (ttyname && options.check_mail) {
1083 char *mailbox;
1084 struct stat mailstat;
1085 mailbox = getenv("MAIL");
1086 if (mailbox != NULL) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001087 if (stat(mailbox, &mailstat) != 0 ||
1088 mailstat.st_size == 0)
Damien Millerb38eff82000-04-01 11:09:21 +10001089 printf("No mail.\n");
1090 else if (mailstat.st_mtime < mailstat.st_atime)
1091 printf("You have mail.\n");
1092 else
1093 printf("You have new mail.\n");
1094 }
1095 }
1096 /* Start the shell. Set initial character to '-'. */
1097 buf[0] = '-';
1098 strncpy(buf + 1, cp, sizeof(buf) - 1);
1099 buf[sizeof(buf) - 1] = 0;
1100
1101 /* Execute the shell. */
1102 argv[0] = buf;
1103 argv[1] = NULL;
1104 execve(shell, argv, env);
1105
1106 /* Executing the shell failed. */
1107 perror(shell);
1108 exit(1);
1109
1110 } else {
1111 /* Launch login(1). */
1112
1113 execl("/usr/bin/login", "login", "-h", get_remote_ipaddr(),
1114 "-p", "-f", "--", pw->pw_name, NULL);
1115
1116 /* Login couldn't be executed, die. */
1117
1118 perror("login");
1119 exit(1);
1120 }
1121 }
1122 /*
1123 * Execute the command using the user's shell. This uses the -c
1124 * option to execute the command.
1125 */
1126 argv[0] = (char *) cp;
1127 argv[1] = "-c";
1128 argv[2] = (char *) command;
1129 argv[3] = NULL;
1130 execve(shell, argv, env);
1131 perror(shell);
1132 exit(1);
1133}
1134
1135Session *
1136session_new(void)
1137{
1138 int i;
1139 static int did_init = 0;
1140 if (!did_init) {
1141 debug("session_new: init");
1142 for(i = 0; i < MAX_SESSIONS; i++) {
1143 sessions[i].used = 0;
1144 sessions[i].self = i;
1145 }
1146 did_init = 1;
1147 }
1148 for(i = 0; i < MAX_SESSIONS; i++) {
1149 Session *s = &sessions[i];
1150 if (! s->used) {
1151 s->pid = 0;
Damien Millerbd483e72000-04-30 10:00:53 +10001152 s->extended = 0;
Damien Millerb38eff82000-04-01 11:09:21 +10001153 s->chanid = -1;
1154 s->ptyfd = -1;
1155 s->ttyfd = -1;
1156 s->term = NULL;
1157 s->pw = NULL;
1158 s->display = NULL;
1159 s->screen = 0;
1160 s->auth_data = NULL;
1161 s->auth_proto = NULL;
1162 s->used = 1;
Damien Millerbd483e72000-04-30 10:00:53 +10001163 s->pw = NULL;
Damien Millerb38eff82000-04-01 11:09:21 +10001164 debug("session_new: session %d", i);
1165 return s;
1166 }
1167 }
1168 return NULL;
1169}
1170
1171void
1172session_dump(void)
1173{
1174 int i;
1175 for(i = 0; i < MAX_SESSIONS; i++) {
1176 Session *s = &sessions[i];
1177 debug("dump: used %d session %d %p channel %d pid %d",
1178 s->used,
1179 s->self,
1180 s,
1181 s->chanid,
1182 s->pid);
1183 }
1184}
1185
Damien Millerefb4afe2000-04-12 18:45:05 +10001186int
1187session_open(int chanid)
1188{
1189 Session *s = session_new();
1190 debug("session_open: channel %d", chanid);
1191 if (s == NULL) {
1192 error("no more sessions");
1193 return 0;
1194 }
Damien Millerefb4afe2000-04-12 18:45:05 +10001195 s->pw = auth_get_user();
1196 if (s->pw == NULL)
Damien Millerbd483e72000-04-30 10:00:53 +10001197 fatal("no user for session %i", s->self);
1198 debug("session_open: session %d: link with channel %d", s->self, chanid);
1199 s->chanid = chanid;
Damien Millerefb4afe2000-04-12 18:45:05 +10001200 return 1;
1201}
1202
1203Session *
1204session_by_channel(int id)
1205{
1206 int i;
1207 for(i = 0; i < MAX_SESSIONS; i++) {
1208 Session *s = &sessions[i];
1209 if (s->used && s->chanid == id) {
1210 debug("session_by_channel: session %d channel %d", i, id);
1211 return s;
1212 }
1213 }
1214 debug("session_by_channel: unknown channel %d", id);
1215 session_dump();
1216 return NULL;
1217}
1218
1219Session *
1220session_by_pid(pid_t pid)
1221{
1222 int i;
1223 debug("session_by_pid: pid %d", pid);
1224 for(i = 0; i < MAX_SESSIONS; i++) {
1225 Session *s = &sessions[i];
1226 if (s->used && s->pid == pid)
1227 return s;
1228 }
1229 error("session_by_pid: unknown pid %d", pid);
1230 session_dump();
1231 return NULL;
1232}
1233
1234int
1235session_window_change_req(Session *s)
1236{
1237 s->col = packet_get_int();
1238 s->row = packet_get_int();
1239 s->xpixel = packet_get_int();
1240 s->ypixel = packet_get_int();
Damien Miller4af51302000-04-16 11:18:38 +10001241 packet_done();
Damien Millerefb4afe2000-04-12 18:45:05 +10001242 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1243 return 1;
1244}
1245
1246int
1247session_pty_req(Session *s)
1248{
1249 unsigned int len;
Damien Miller4af51302000-04-16 11:18:38 +10001250 char *term_modes; /* encoded terminal modes */
Damien Millerefb4afe2000-04-12 18:45:05 +10001251
Damien Millerf6d9e222000-06-18 14:50:44 +10001252 if (no_pty_flag)
1253 return 0;
Damien Millerefb4afe2000-04-12 18:45:05 +10001254 if (s->ttyfd != -1)
Damien Miller4af51302000-04-16 11:18:38 +10001255 return 0;
Damien Millerefb4afe2000-04-12 18:45:05 +10001256 s->term = packet_get_string(&len);
1257 s->col = packet_get_int();
1258 s->row = packet_get_int();
1259 s->xpixel = packet_get_int();
1260 s->ypixel = packet_get_int();
Damien Miller4af51302000-04-16 11:18:38 +10001261 term_modes = packet_get_string(&len);
1262 packet_done();
Damien Millerefb4afe2000-04-12 18:45:05 +10001263
1264 if (strcmp(s->term, "") == 0) {
1265 xfree(s->term);
1266 s->term = NULL;
1267 }
1268 /* Allocate a pty and open it. */
1269 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1270 xfree(s->term);
1271 s->term = NULL;
1272 s->ptyfd = -1;
1273 s->ttyfd = -1;
1274 error("session_pty_req: session %d alloc failed", s->self);
Damien Miller4af51302000-04-16 11:18:38 +10001275 xfree(term_modes);
1276 return 0;
Damien Millerefb4afe2000-04-12 18:45:05 +10001277 }
1278 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1279 /*
1280 * Add a cleanup function to clear the utmp entry and record logout
1281 * time in case we call fatal() (e.g., the connection gets closed).
1282 */
1283 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1284 pty_setowner(s->pw, s->tty);
1285 /* Get window size from the packet. */
1286 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1287
Damien Millere247cc42000-05-07 12:03:14 +10001288 session_proctitle(s);
1289
Damien Miller5f056372000-04-16 12:31:48 +10001290 /* XXX parse and set terminal modes */
1291 xfree(term_modes);
Damien Millerefb4afe2000-04-12 18:45:05 +10001292 return 1;
1293}
1294
Damien Millerbd483e72000-04-30 10:00:53 +10001295int
1296session_subsystem_req(Session *s)
1297{
1298 unsigned int len;
1299 int success = 0;
1300 char *subsys = packet_get_string(&len);
Damien Millerf6d9e222000-06-18 14:50:44 +10001301 int i;
Damien Millerbd483e72000-04-30 10:00:53 +10001302
1303 packet_done();
1304 log("subsystem request for %s", subsys);
1305
Damien Millerf6d9e222000-06-18 14:50:44 +10001306 for (i = 0; i < options.num_subsystems; i++) {
1307 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1308 debug("subsystem: exec() %s", options.subsystem_command[i]);
1309 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1310 success = 1;
1311 }
1312 }
1313
1314 if (!success)
1315 log("subsystem request for %s failed, subsystem not found", subsys);
1316
Damien Millerbd483e72000-04-30 10:00:53 +10001317 xfree(subsys);
1318 return success;
1319}
1320
1321int
1322session_x11_req(Session *s)
1323{
Damien Millerf6d9e222000-06-18 14:50:44 +10001324 if (!no_port_forwarding_flag) {
1325 debug("X11 forwarding disabled in user configuration file.");
1326 return 0;
1327 }
Damien Millerbd483e72000-04-30 10:00:53 +10001328 if (!options.x11_forwarding) {
1329 debug("X11 forwarding disabled in server configuration file.");
1330 return 0;
1331 }
1332 if (xauthfile != NULL) {
1333 debug("X11 fwd already started.");
1334 return 0;
1335 }
1336
1337 debug("Received request for X11 forwarding with auth spoofing.");
1338 if (s->display != NULL)
1339 packet_disconnect("Protocol error: X11 display already set.");
1340
1341 s->single_connection = packet_get_char();
1342 s->auth_proto = packet_get_string(NULL);
1343 s->auth_data = packet_get_string(NULL);
1344 s->screen = packet_get_int();
1345 packet_done();
1346
1347 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1348 if (s->display == NULL) {
1349 xfree(s->auth_proto);
1350 xfree(s->auth_data);
1351 return 0;
1352 }
1353 xauthfile = xmalloc(MAXPATHLEN);
1354 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1355 temporarily_use_uid(s->pw->pw_uid);
1356 if (mkdtemp(xauthfile) == NULL) {
1357 restore_uid();
1358 error("private X11 dir: mkdtemp %s failed: %s",
1359 xauthfile, strerror(errno));
1360 xfree(xauthfile);
1361 xauthfile = NULL;
1362 xfree(s->auth_proto);
1363 xfree(s->auth_data);
1364 /* XXXX remove listening channels */
1365 return 0;
1366 }
1367 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1368 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1369 restore_uid();
1370 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1371 return 1;
1372}
1373
Damien Millerf6d9e222000-06-18 14:50:44 +10001374int
1375session_shell_req(Session *s)
1376{
1377 /* if forced_command == NULL, the shell is execed */
1378 char *shell = forced_command;
1379 packet_done();
1380 s->extended = 1;
1381 if (s->ttyfd == -1)
1382 do_exec_no_pty(s, shell, s->pw);
1383 else
1384 do_exec_pty(s, shell, s->pw);
1385 return 1;
1386}
1387
1388int
1389session_exec_req(Session *s)
1390{
1391 unsigned int len;
1392 char *command = packet_get_string(&len);
1393 packet_done();
1394 if (forced_command) {
1395 xfree(command);
1396 command = forced_command;
1397 debug("Forced command '%.500s'", forced_command);
1398 }
1399 s->extended = 1;
1400 if (s->ttyfd == -1)
1401 do_exec_no_pty(s, command, s->pw);
1402 else
1403 do_exec_pty(s, command, s->pw);
1404 if (forced_command == NULL)
1405 xfree(command);
1406 return 1;
1407}
1408
Damien Millerefb4afe2000-04-12 18:45:05 +10001409void
1410session_input_channel_req(int id, void *arg)
1411{
1412 unsigned int len;
1413 int reply;
1414 int success = 0;
1415 char *rtype;
1416 Session *s;
1417 Channel *c;
1418
1419 rtype = packet_get_string(&len);
1420 reply = packet_get_char();
1421
1422 s = session_by_channel(id);
1423 if (s == NULL)
1424 fatal("session_input_channel_req: channel %d: no session", id);
1425 c = channel_lookup(id);
1426 if (c == NULL)
1427 fatal("session_input_channel_req: channel %d: bad channel", id);
1428
1429 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1430 s->self, id, rtype, reply);
1431
1432 /*
1433 * a session is in LARVAL state until a shell
1434 * or programm is executed
1435 */
1436 if (c->type == SSH_CHANNEL_LARVAL) {
1437 if (strcmp(rtype, "shell") == 0) {
Damien Millerf6d9e222000-06-18 14:50:44 +10001438 success = session_shell_req(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001439 } else if (strcmp(rtype, "exec") == 0) {
Damien Millerf6d9e222000-06-18 14:50:44 +10001440 success = session_exec_req(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001441 } else if (strcmp(rtype, "pty-req") == 0) {
Damien Miller5f056372000-04-16 12:31:48 +10001442 success = session_pty_req(s);
Damien Millerbd483e72000-04-30 10:00:53 +10001443 } else if (strcmp(rtype, "x11-req") == 0) {
1444 success = session_x11_req(s);
1445 } else if (strcmp(rtype, "subsystem") == 0) {
1446 success = session_subsystem_req(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001447 }
1448 }
1449 if (strcmp(rtype, "window-change") == 0) {
1450 success = session_window_change_req(s);
1451 }
1452
1453 if (reply) {
1454 packet_start(success ?
1455 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1456 packet_put_int(c->remote_id);
1457 packet_send();
1458 }
1459 xfree(rtype);
1460}
1461
1462void
1463session_set_fds(Session *s, int fdin, int fdout, int fderr)
1464{
1465 if (!compat20)
1466 fatal("session_set_fds: called for proto != 2.0");
1467 /*
1468 * now that have a child and a pipe to the child,
1469 * we can activate our channel and register the fd's
1470 */
1471 if (s->chanid == -1)
1472 fatal("no channel for session %d", s->self);
1473 channel_set_fds(s->chanid,
1474 fdout, fdin, fderr,
1475 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1476}
1477
Damien Millerb38eff82000-04-01 11:09:21 +10001478void
1479session_pty_cleanup(Session *s)
1480{
1481 if (s == NULL || s->ttyfd == -1)
1482 return;
1483
1484 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1485
1486 /* Cancel the cleanup function. */
1487 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1488
1489 /* Record that the user has logged out. */
1490 record_logout(s->pid, s->tty);
1491
1492 /* Release the pseudo-tty. */
1493 pty_release(s->tty);
1494
1495 /*
1496 * Close the server side of the socket pairs. We must do this after
1497 * the pty cleanup, so that another process doesn't get this pty
1498 * while we're still cleaning up.
1499 */
1500 if (close(s->ptymaster) < 0)
1501 error("close(s->ptymaster): %s", strerror(errno));
1502}
Damien Millerefb4afe2000-04-12 18:45:05 +10001503
1504void
1505session_exit_message(Session *s, int status)
1506{
1507 Channel *c;
1508 if (s == NULL)
1509 fatal("session_close: no session");
1510 c = channel_lookup(s->chanid);
1511 if (c == NULL)
1512 fatal("session_close: session %d: no channel %d",
1513 s->self, s->chanid);
1514 debug("session_exit_message: session %d channel %d pid %d",
1515 s->self, s->chanid, s->pid);
1516
1517 if (WIFEXITED(status)) {
1518 channel_request_start(s->chanid,
1519 "exit-status", 0);
1520 packet_put_int(WEXITSTATUS(status));
1521 packet_send();
1522 } else if (WIFSIGNALED(status)) {
1523 channel_request_start(s->chanid,
1524 "exit-signal", 0);
1525 packet_put_int(WTERMSIG(status));
Damien Millerf3c6cf12000-05-17 22:08:29 +10001526#ifdef WCOREDUMP
Damien Millerefb4afe2000-04-12 18:45:05 +10001527 packet_put_char(WCOREDUMP(status));
Damien Millerf3c6cf12000-05-17 22:08:29 +10001528#else /* WCOREDUMP */
1529 packet_put_char(0);
1530#endif /* WCOREDUMP */
Damien Millerefb4afe2000-04-12 18:45:05 +10001531 packet_put_cstring("");
1532 packet_put_cstring("");
1533 packet_send();
1534 } else {
1535 /* Some weird exit cause. Just exit. */
1536 packet_disconnect("wait returned status %04x.", status);
1537 }
1538
1539 /* disconnect channel */
1540 debug("session_exit_message: release channel %d", s->chanid);
1541 channel_cancel_cleanup(s->chanid);
Damien Miller166fca82000-04-20 07:42:21 +10001542 /*
1543 * emulate a write failure with 'chan_write_failed', nobody will be
1544 * interested in data we write.
1545 * Note that we must not call 'chan_read_failed', since there could
1546 * be some more data waiting in the pipe.
1547 */
Damien Millerbd483e72000-04-30 10:00:53 +10001548 if (c->ostate != CHAN_OUTPUT_CLOSED)
1549 chan_write_failed(c);
Damien Millerefb4afe2000-04-12 18:45:05 +10001550 s->chanid = -1;
1551}
1552
1553void
1554session_free(Session *s)
1555{
1556 debug("session_free: session %d pid %d", s->self, s->pid);
1557 if (s->term)
1558 xfree(s->term);
1559 if (s->display)
1560 xfree(s->display);
1561 if (s->auth_data)
1562 xfree(s->auth_data);
1563 if (s->auth_proto)
1564 xfree(s->auth_proto);
1565 s->used = 0;
1566}
1567
1568void
1569session_close(Session *s)
1570{
1571 session_pty_cleanup(s);
1572 session_free(s);
Damien Millere247cc42000-05-07 12:03:14 +10001573 session_proctitle(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001574}
1575
1576void
1577session_close_by_pid(pid_t pid, int status)
1578{
1579 Session *s = session_by_pid(pid);
1580 if (s == NULL) {
1581 debug("session_close_by_pid: no session for pid %d", s->pid);
1582 return;
1583 }
1584 if (s->chanid != -1)
1585 session_exit_message(s, status);
1586 session_close(s);
1587}
1588
1589/*
1590 * this is called when a channel dies before
1591 * the session 'child' itself dies
1592 */
1593void
1594session_close_by_channel(int id, void *arg)
1595{
1596 Session *s = session_by_channel(id);
1597 if (s == NULL) {
1598 debug("session_close_by_channel: no session for channel %d", id);
1599 return;
1600 }
1601 /* disconnect channel */
1602 channel_cancel_cleanup(s->chanid);
1603 s->chanid = -1;
1604
1605 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1606 if (s->pid == 0) {
1607 /* close session immediately */
1608 session_close(s);
1609 } else {
1610 /* notify child, delay session cleanup */
1611 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
1612 error("session_close_by_channel: kill %d: %s",
1613 s->pid, strerror(errno));
1614 }
1615}
1616
Damien Millere247cc42000-05-07 12:03:14 +10001617char *
1618session_tty_list(void)
1619{
1620 static char buf[1024];
1621 int i;
1622 buf[0] = '\0';
1623 for(i = 0; i < MAX_SESSIONS; i++) {
1624 Session *s = &sessions[i];
1625 if (s->used && s->ttyfd != -1) {
1626 if (buf[0] != '\0')
1627 strlcat(buf, ",", sizeof buf);
1628 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1629 }
1630 }
1631 if (buf[0] == '\0')
1632 strlcpy(buf, "notty", sizeof buf);
1633 return buf;
1634}
1635
1636void
1637session_proctitle(Session *s)
1638{
1639 if (s->pw == NULL)
1640 error("no user for session %d", s->self);
1641 else
1642 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1643}
1644
Damien Millerefb4afe2000-04-12 18:45:05 +10001645void
1646do_authenticated2(void)
1647{
1648 /*
1649 * Cancel the alarm we set to limit the time taken for
1650 * authentication.
1651 */
1652 alarm(0);
Damien Millerefb4afe2000-04-12 18:45:05 +10001653 server_loop2();
Damien Miller1b26ab22000-04-30 10:12:49 +10001654 if (xauthfile)
1655 xauthfile_cleanup_proc(NULL);
Damien Millerefb4afe2000-04-12 18:45:05 +10001656}