blob: 1f0d227d08f117ff1467a6e6453cfea5928b5f10 [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 Miller5fc85652000-07-09 23:53:07 +100012#if defined(HAVE_USERSEC_H)
13#include <usersec.h>
14#endif
Damien Millerb38eff82000-04-01 11:09:21 +100015
16#include "xmalloc.h"
17#include "ssh.h"
18#include "pty.h"
19#include "packet.h"
20#include "buffer.h"
21#include "cipher.h"
22#include "mpaux.h"
23#include "servconf.h"
24#include "uidswap.h"
25#include "compat.h"
26#include "channels.h"
27#include "nchan.h"
28
Damien Millerefb4afe2000-04-12 18:45:05 +100029#include "bufaux.h"
30#include "ssh2.h"
31#include "auth.h"
Damien Millerf6d9e222000-06-18 14:50:44 +100032#include "auth-options.h"
Damien Millerefb4afe2000-04-12 18:45:05 +100033
Damien Miller91606b12000-06-28 08:22:29 +100034#ifdef WITH_IRIX_PROJECT
35#include <proj.h>
36#endif /* WITH_IRIX_PROJECT */
37
Damien Millerb8c656e2000-06-28 15:22:41 +100038#ifdef HAVE_OSF_SIA
39# include <sia.h>
40# include <siad.h>
41#endif
42
Damien Millerb38eff82000-04-01 11:09:21 +100043/* types */
44
45#define TTYSZ 64
46typedef struct Session Session;
47struct Session {
48 int used;
49 int self;
Damien Millerbd483e72000-04-30 10:00:53 +100050 int extended;
Damien Millerb38eff82000-04-01 11:09:21 +100051 struct passwd *pw;
52 pid_t pid;
53 /* tty */
54 char *term;
55 int ptyfd, ttyfd, ptymaster;
56 int row, col, xpixel, ypixel;
57 char tty[TTYSZ];
58 /* X11 */
59 char *display;
60 int screen;
61 char *auth_proto;
62 char *auth_data;
Damien Millerbd483e72000-04-30 10:00:53 +100063 int single_connection;
Damien Millerb38eff82000-04-01 11:09:21 +100064 /* proto 2 */
65 int chanid;
66};
67
68/* func */
69
70Session *session_new(void);
71void session_set_fds(Session *s, int fdin, int fdout, int fderr);
72void session_pty_cleanup(Session *s);
Damien Millere247cc42000-05-07 12:03:14 +100073void session_proctitle(Session *s);
Damien Millerb38eff82000-04-01 11:09:21 +100074void do_exec_pty(Session *s, const char *command, struct passwd * pw);
75void do_exec_no_pty(Session *s, const char *command, struct passwd * pw);
76
77void
78do_child(const char *command, struct passwd * pw, const char *term,
79 const char *display, const char *auth_proto,
80 const char *auth_data, const char *ttyname);
81
82/* import */
83extern ServerOptions options;
Damien Miller06d84b72000-04-21 16:13:07 +100084#ifdef HAVE___PROGNAME
Damien Millerb38eff82000-04-01 11:09:21 +100085extern char *__progname;
Damien Miller06d84b72000-04-21 16:13:07 +100086#else /* HAVE___PROGNAME */
Damien Miller70fb6712000-05-01 20:59:50 +100087static const char *__progname = "sshd";
Damien Miller06d84b72000-04-21 16:13:07 +100088#endif /* HAVE___PROGNAME */
89
Damien Millerb38eff82000-04-01 11:09:21 +100090extern int log_stderr;
91extern int debug_flag;
92
93/* Local Xauthority file. */
94static char *xauthfile;
95
96/* data */
97#define MAX_SESSIONS 10
98Session sessions[MAX_SESSIONS];
Damien Millerd2c208a2000-05-17 22:00:02 +100099#ifdef WITH_AIXAUTHENTICATE
100/* AIX's lastlogin message, set in auth1.c */
101char *aixloginmsg;
102#endif /* WITH_AIXAUTHENTICATE */
Damien Millerb38eff82000-04-01 11:09:21 +1000103
Damien Millerb38eff82000-04-01 11:09:21 +1000104/*
105 * Remove local Xauthority file.
106 */
107void
108xauthfile_cleanup_proc(void *ignore)
109{
110 debug("xauthfile_cleanup_proc called");
111
112 if (xauthfile != NULL) {
113 char *p;
114 unlink(xauthfile);
115 p = strrchr(xauthfile, '/');
116 if (p != NULL) {
117 *p = '\0';
118 rmdir(xauthfile);
119 }
120 xfree(xauthfile);
121 xauthfile = NULL;
122 }
123}
124
125/*
126 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
127 * dropped connection).
128 */
Damien Miller4af51302000-04-16 11:18:38 +1000129void
Damien Millerb38eff82000-04-01 11:09:21 +1000130pty_cleanup_proc(void *session)
131{
132 Session *s=session;
133 if (s == NULL)
134 fatal("pty_cleanup_proc: no session");
135 debug("pty_cleanup_proc: %s", s->tty);
136
137 if (s->pid != 0) {
138 /* Record that the user has logged out. */
139 record_logout(s->pid, s->tty);
140 }
141
142 /* Release the pseudo-tty. */
143 pty_release(s->tty);
144}
145
146/*
147 * Prepares for an interactive session. This is called after the user has
148 * been successfully authenticated. During this message exchange, pseudo
149 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
150 * are requested, etc.
151 */
Damien Miller4af51302000-04-16 11:18:38 +1000152void
Damien Millerb38eff82000-04-01 11:09:21 +1000153do_authenticated(struct passwd * pw)
154{
155 Session *s;
156 int type;
157 int compression_level = 0, enable_compression_after_reply = 0;
158 int have_pty = 0;
159 char *command;
160 int n_bytes;
161 int plen;
162 unsigned int proto_len, data_len, dlen;
163
164 /*
165 * Cancel the alarm we set to limit the time taken for
166 * authentication.
167 */
168 alarm(0);
169
170 /*
171 * Inform the channel mechanism that we are the server side and that
172 * the client may request to connect to any port at all. (The user
173 * could do it anyway, and we wouldn\'t know what is permitted except
174 * by the client telling us, so we can equally well trust the client
175 * not to request anything bogus.)
176 */
177 if (!no_port_forwarding_flag)
178 channel_permit_all_opens();
179
180 s = session_new();
Damien Millerbd483e72000-04-30 10:00:53 +1000181 s->pw = pw;
Damien Millerb38eff82000-04-01 11:09:21 +1000182
183 /*
184 * We stay in this loop until the client requests to execute a shell
185 * or a command.
186 */
187 for (;;) {
188 int success = 0;
189
190 /* Get a packet from the client. */
191 type = packet_read(&plen);
192
193 /* Process the packet. */
194 switch (type) {
195 case SSH_CMSG_REQUEST_COMPRESSION:
196 packet_integrity_check(plen, 4, type);
197 compression_level = packet_get_int();
198 if (compression_level < 1 || compression_level > 9) {
199 packet_send_debug("Received illegal compression level %d.",
200 compression_level);
201 break;
202 }
203 /* Enable compression after we have responded with SUCCESS. */
204 enable_compression_after_reply = 1;
205 success = 1;
206 break;
207
208 case SSH_CMSG_REQUEST_PTY:
209 if (no_pty_flag) {
210 debug("Allocating a pty not permitted for this authentication.");
211 break;
212 }
213 if (have_pty)
214 packet_disconnect("Protocol error: you already have a pty.");
215
216 debug("Allocating pty.");
217
218 /* Allocate a pty and open it. */
219 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty,
220 sizeof(s->tty))) {
221 error("Failed to allocate pty.");
222 break;
223 }
224 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
225 pty_setowner(pw, s->tty);
226
227 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
228 s->term = packet_get_string(&dlen);
229 packet_integrity_check(dlen, strlen(s->term), type);
230 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
231 /* Remaining bytes */
232 n_bytes = plen - (4 + dlen + 4 * 4);
233
234 if (strcmp(s->term, "") == 0) {
235 xfree(s->term);
236 s->term = NULL;
237 }
238 /* Get window size from the packet. */
239 s->row = packet_get_int();
240 s->col = packet_get_int();
241 s->xpixel = packet_get_int();
242 s->ypixel = packet_get_int();
243 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
244
245 /* Get tty modes from the packet. */
246 tty_parse_modes(s->ttyfd, &n_bytes);
247 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
248
Damien Millere247cc42000-05-07 12:03:14 +1000249 session_proctitle(s);
250
Damien Millerb38eff82000-04-01 11:09:21 +1000251 /* Indicate that we now have a pty. */
252 success = 1;
253 have_pty = 1;
254 break;
255
256 case SSH_CMSG_X11_REQUEST_FORWARDING:
257 if (!options.x11_forwarding) {
258 packet_send_debug("X11 forwarding disabled in server configuration file.");
259 break;
260 }
Damien Miller0c043c12000-06-07 21:22:38 +1000261 if (!options.xauth_location) {
262 packet_send_debug("No xauth program; cannot forward with spoofing.");
263 break;
264 }
Damien Millerb38eff82000-04-01 11:09:21 +1000265 if (no_x11_forwarding_flag) {
266 packet_send_debug("X11 forwarding not permitted for this authentication.");
267 break;
268 }
269 debug("Received request for X11 forwarding with auth spoofing.");
270 if (s->display != NULL)
271 packet_disconnect("Protocol error: X11 display already set.");
272
273 s->auth_proto = packet_get_string(&proto_len);
274 s->auth_data = packet_get_string(&data_len);
275 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
276
277 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
278 s->screen = packet_get_int();
279 else
280 s->screen = 0;
281 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
282
283 if (s->display == NULL)
284 break;
285
286 /* Setup to always have a local .Xauthority. */
287 xauthfile = xmalloc(MAXPATHLEN);
288 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
289 temporarily_use_uid(pw->pw_uid);
290 if (mkdtemp(xauthfile) == NULL) {
291 restore_uid();
292 error("private X11 dir: mkdtemp %s failed: %s",
293 xauthfile, strerror(errno));
294 xfree(xauthfile);
295 xauthfile = NULL;
Damien Millerbd483e72000-04-30 10:00:53 +1000296 /* XXXX remove listening channels */
Damien Millerb38eff82000-04-01 11:09:21 +1000297 break;
298 }
299 strlcat(xauthfile, "/cookies", MAXPATHLEN);
300 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
301 restore_uid();
302 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
303 success = 1;
304 break;
Damien Millerb38eff82000-04-01 11:09:21 +1000305
306 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
307 if (no_agent_forwarding_flag || compat13) {
308 debug("Authentication agent forwarding not permitted for this authentication.");
309 break;
310 }
311 debug("Received authentication agent forwarding request.");
Damien Miller0c043c12000-06-07 21:22:38 +1000312 success = auth_input_request_forwarding(pw);
Damien Millerb38eff82000-04-01 11:09:21 +1000313 break;
314
315 case SSH_CMSG_PORT_FORWARD_REQUEST:
316 if (no_port_forwarding_flag) {
317 debug("Port forwarding not permitted for this authentication.");
318 break;
319 }
320 debug("Received TCP/IP port forwarding request.");
Damien Millere247cc42000-05-07 12:03:14 +1000321 channel_input_port_forward_request(pw->pw_uid == 0, options.gateway_ports);
Damien Millerb38eff82000-04-01 11:09:21 +1000322 success = 1;
323 break;
324
325 case SSH_CMSG_MAX_PACKET_SIZE:
326 if (packet_set_maxsize(packet_get_int()) > 0)
327 success = 1;
328 break;
329
330 case SSH_CMSG_EXEC_SHELL:
331 case SSH_CMSG_EXEC_CMD:
332 /* Set interactive/non-interactive mode. */
333 packet_set_interactive(have_pty || s->display != NULL,
334 options.keepalives);
335
336 if (type == SSH_CMSG_EXEC_CMD) {
337 command = packet_get_string(&dlen);
338 debug("Exec command '%.500s'", command);
339 packet_integrity_check(plen, 4 + dlen, type);
340 } else {
341 command = NULL;
342 packet_integrity_check(plen, 0, type);
343 }
344 if (forced_command != NULL) {
345 command = forced_command;
346 debug("Forced command '%.500s'", forced_command);
347 }
348 if (have_pty)
349 do_exec_pty(s, command, pw);
350 else
351 do_exec_no_pty(s, command, pw);
352
353 if (command != NULL)
354 xfree(command);
355 /* Cleanup user's local Xauthority file. */
356 if (xauthfile)
357 xauthfile_cleanup_proc(NULL);
358 return;
359
360 default:
361 /*
362 * Any unknown messages in this phase are ignored,
363 * and a failure message is returned.
364 */
365 log("Unknown packet type received after authentication: %d", type);
366 }
367 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
368 packet_send();
369 packet_write_wait();
370
371 /* Enable compression now that we have replied if appropriate. */
372 if (enable_compression_after_reply) {
373 enable_compression_after_reply = 0;
374 packet_start_compression(compression_level);
375 }
376 }
377}
378
379/*
380 * This is called to fork and execute a command when we have no tty. This
381 * will call do_child from the child, and server_loop from the parent after
382 * setting up file descriptors and such.
383 */
Damien Miller4af51302000-04-16 11:18:38 +1000384void
Damien Millerb38eff82000-04-01 11:09:21 +1000385do_exec_no_pty(Session *s, const char *command, struct passwd * pw)
386{
387 int pid;
388
389#ifdef USE_PIPES
390 int pin[2], pout[2], perr[2];
391 /* Allocate pipes for communicating with the program. */
392 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
393 packet_disconnect("Could not create pipes: %.100s",
394 strerror(errno));
395#else /* USE_PIPES */
396 int inout[2], err[2];
397 /* Uses socket pairs to communicate with the program. */
398 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
399 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
400 packet_disconnect("Could not create socket pairs: %.100s",
401 strerror(errno));
402#endif /* USE_PIPES */
403 if (s == NULL)
404 fatal("do_exec_no_pty: no session");
405
Damien Millere247cc42000-05-07 12:03:14 +1000406 session_proctitle(s);
Damien Millerb38eff82000-04-01 11:09:21 +1000407
408#ifdef USE_PAM
409 do_pam_setcred();
410#endif /* USE_PAM */
411
412 /* Fork the child. */
413 if ((pid = fork()) == 0) {
414 /* Child. Reinitialize the log since the pid has changed. */
415 log_init(__progname, options.log_level, options.log_facility, log_stderr);
416
417 /*
418 * Create a new session and process group since the 4.4BSD
419 * setlogin() affects the entire process group.
420 */
421 if (setsid() < 0)
422 error("setsid failed: %.100s", strerror(errno));
423
424#ifdef USE_PIPES
425 /*
426 * Redirect stdin. We close the parent side of the socket
427 * pair, and make the child side the standard input.
428 */
429 close(pin[1]);
430 if (dup2(pin[0], 0) < 0)
431 perror("dup2 stdin");
432 close(pin[0]);
433
434 /* Redirect stdout. */
435 close(pout[0]);
436 if (dup2(pout[1], 1) < 0)
437 perror("dup2 stdout");
438 close(pout[1]);
439
440 /* Redirect stderr. */
441 close(perr[0]);
442 if (dup2(perr[1], 2) < 0)
443 perror("dup2 stderr");
444 close(perr[1]);
445#else /* USE_PIPES */
446 /*
447 * Redirect stdin, stdout, and stderr. Stdin and stdout will
448 * use the same socket, as some programs (particularly rdist)
449 * seem to depend on it.
450 */
451 close(inout[1]);
452 close(err[1]);
453 if (dup2(inout[0], 0) < 0) /* stdin */
454 perror("dup2 stdin");
455 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
456 perror("dup2 stdout");
457 if (dup2(err[0], 2) < 0) /* stderr */
458 perror("dup2 stderr");
459#endif /* USE_PIPES */
460
461 /* Do processing for the child (exec command etc). */
462 do_child(command, pw, NULL, s->display, s->auth_proto, s->auth_data, NULL);
463 /* NOTREACHED */
464 }
465 if (pid < 0)
466 packet_disconnect("fork failed: %.100s", strerror(errno));
467 s->pid = pid;
468#ifdef USE_PIPES
469 /* We are the parent. Close the child sides of the pipes. */
470 close(pin[0]);
471 close(pout[1]);
472 close(perr[1]);
473
Damien Millerefb4afe2000-04-12 18:45:05 +1000474 if (compat20) {
Damien Millerbd483e72000-04-30 10:00:53 +1000475 session_set_fds(s, pin[1], pout[0], s->extended ? perr[0] : -1);
Damien Millerefb4afe2000-04-12 18:45:05 +1000476 } else {
477 /* Enter the interactive session. */
478 server_loop(pid, pin[1], pout[0], perr[0]);
479 /* server_loop has closed pin[1], pout[1], and perr[1]. */
480 }
Damien Millerb38eff82000-04-01 11:09:21 +1000481#else /* USE_PIPES */
482 /* We are the parent. Close the child sides of the socket pairs. */
483 close(inout[0]);
484 close(err[0]);
485
486 /*
487 * Enter the interactive session. Note: server_loop must be able to
488 * handle the case that fdin and fdout are the same.
489 */
Damien Millerefb4afe2000-04-12 18:45:05 +1000490 if (compat20) {
Damien Millerbd483e72000-04-30 10:00:53 +1000491 session_set_fds(s, inout[1], inout[1], s->extended ? err[1] : -1);
Damien Millerefb4afe2000-04-12 18:45:05 +1000492 } else {
493 server_loop(pid, inout[1], inout[1], err[1]);
494 /* server_loop has closed inout[1] and err[1]. */
495 }
Damien Millerb38eff82000-04-01 11:09:21 +1000496#endif /* USE_PIPES */
497}
498
499/*
500 * This is called to fork and execute a command when we have a tty. This
501 * will call do_child from the child, and server_loop from the parent after
502 * setting up file descriptors, controlling tty, updating wtmp, utmp,
503 * lastlog, and other such operations.
504 */
Damien Miller4af51302000-04-16 11:18:38 +1000505void
Damien Millerb38eff82000-04-01 11:09:21 +1000506do_exec_pty(Session *s, const char *command, struct passwd * pw)
507{
508 FILE *f;
509 char buf[100], *time_string;
510 char line[256];
511 const char *hostname;
512 int fdout, ptyfd, ttyfd, ptymaster;
513 int quiet_login;
514 pid_t pid;
515 socklen_t fromlen;
516 struct sockaddr_storage from;
517 struct stat st;
518 time_t last_login_time;
519
520 if (s == NULL)
521 fatal("do_exec_pty: no session");
522 ptyfd = s->ptyfd;
523 ttyfd = s->ttyfd;
524
525 /* Get remote host name. */
526 hostname = get_canonical_hostname();
527
528 /*
529 * Get the time when the user last logged in. Buf will be set to
530 * contain the hostname the last login was from.
531 */
532 if (!options.use_login) {
533 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
534 buf, sizeof(buf));
535 }
Damien Millerb38eff82000-04-01 11:09:21 +1000536
537#ifdef USE_PAM
538 do_pam_session(pw->pw_name, s->tty);
539 do_pam_setcred();
540#endif /* USE_PAM */
541
542 /* Fork the child. */
543 if ((pid = fork()) == 0) {
544 pid = getpid();
545
546 /* Child. Reinitialize the log because the pid has
547 changed. */
548 log_init(__progname, options.log_level, options.log_facility, log_stderr);
549
550 /* Close the master side of the pseudo tty. */
551 close(ptyfd);
552
553 /* Make the pseudo tty our controlling tty. */
554 pty_make_controlling_tty(&ttyfd, s->tty);
555
556 /* Redirect stdin from the pseudo tty. */
557 if (dup2(ttyfd, fileno(stdin)) < 0)
558 error("dup2 stdin failed: %.100s", strerror(errno));
559
560 /* Redirect stdout to the pseudo tty. */
561 if (dup2(ttyfd, fileno(stdout)) < 0)
562 error("dup2 stdin failed: %.100s", strerror(errno));
563
564 /* Redirect stderr to the pseudo tty. */
565 if (dup2(ttyfd, fileno(stderr)) < 0)
566 error("dup2 stdin failed: %.100s", strerror(errno));
567
568 /* Close the extra descriptor for the pseudo tty. */
569 close(ttyfd);
570
Damien Millere247cc42000-05-07 12:03:14 +1000571/* XXXX ? move to do_child() ??*/
Damien Millerb38eff82000-04-01 11:09:21 +1000572 /*
573 * Get IP address of client. This is needed because we want
574 * to record where the user logged in from. If the
575 * connection is not a socket, let the ip address be 0.0.0.0.
576 */
577 memset(&from, 0, sizeof(from));
578 if (packet_connection_is_on_socket()) {
579 fromlen = sizeof(from);
580 if (getpeername(packet_get_connection_in(),
581 (struct sockaddr *) & from, &fromlen) < 0) {
582 debug("getpeername: %.100s", strerror(errno));
583 fatal_cleanup();
584 }
585 }
586 /* Record that there was a login on that terminal. */
587 record_login(pid, s->tty, pw->pw_name, pw->pw_uid, hostname,
588 (struct sockaddr *)&from);
589
590 /* Check if .hushlogin exists. */
591 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
592 quiet_login = stat(line, &st) >= 0;
593
594#ifdef USE_PAM
595 if (!quiet_login)
596 print_pam_messages();
597#endif /* USE_PAM */
598
599 /*
600 * If the user has logged in before, display the time of last
601 * login. However, don't display anything extra if a command
602 * has been specified (so that ssh can be used to execute
603 * commands on a remote machine without users knowing they
604 * are going to another machine). Login(1) will do this for
605 * us as well, so check if login(1) is used
606 */
607 if (command == NULL && last_login_time != 0 && !quiet_login &&
608 !options.use_login) {
609 /* Convert the date to a string. */
610 time_string = ctime(&last_login_time);
611 /* Remove the trailing newline. */
612 if (strchr(time_string, '\n'))
613 *strchr(time_string, '\n') = 0;
614 /* Display the last login time. Host if displayed
615 if known. */
616 if (strcmp(buf, "") == 0)
617 printf("Last login: %s\r\n", time_string);
618 else
619 printf("Last login: %s from %s\r\n", time_string, buf);
620 }
621 /*
622 * Print /etc/motd unless a command was specified or printing
623 * it was disabled in server options or login(1) will be
624 * used. Note that some machines appear to print it in
625 * /etc/profile or similar.
626 */
627 if (command == NULL && options.print_motd && !quiet_login &&
628 !options.use_login) {
629 /* Print /etc/motd if it exists. */
630 f = fopen("/etc/motd", "r");
631 if (f) {
632 while (fgets(line, sizeof(line), f))
633 fputs(line, stdout);
634 fclose(f);
635 }
636 }
Damien Millerd2c208a2000-05-17 22:00:02 +1000637#if defined(WITH_AIXAUTHENTICATE)
638 /*
639 * AIX handles the lastlog info differently. Display it here.
640 */
641 if (command == NULL && aixloginmsg && *aixloginmsg &&
642 !quiet_login && !options.use_login) {
643 printf("%s\n", aixloginmsg);
644 }
645#endif
Damien Millerb38eff82000-04-01 11:09:21 +1000646 /* Do common processing for the child, such as execing the command. */
Damien Millerb1715dc2000-05-30 13:44:51 +1000647 do_child(command, pw, s->term, s->display, s->auth_proto,
648 s->auth_data, s->tty);
Damien Millerb38eff82000-04-01 11:09:21 +1000649 /* NOTREACHED */
650 }
651 if (pid < 0)
652 packet_disconnect("fork failed: %.100s", strerror(errno));
653 s->pid = pid;
654
655 /* Parent. Close the slave side of the pseudo tty. */
656 close(ttyfd);
657
658 /*
659 * Create another descriptor of the pty master side for use as the
660 * standard input. We could use the original descriptor, but this
661 * simplifies code in server_loop. The descriptor is bidirectional.
662 */
663 fdout = dup(ptyfd);
664 if (fdout < 0)
665 packet_disconnect("dup #1 failed: %.100s", strerror(errno));
666
667 /* we keep a reference to the pty master */
668 ptymaster = dup(ptyfd);
669 if (ptymaster < 0)
670 packet_disconnect("dup #2 failed: %.100s", strerror(errno));
671 s->ptymaster = ptymaster;
672
673 /* Enter interactive session. */
Damien Millerefb4afe2000-04-12 18:45:05 +1000674 if (compat20) {
675 session_set_fds(s, ptyfd, fdout, -1);
676 } else {
677 server_loop(pid, ptyfd, fdout, -1);
678 /* server_loop _has_ closed ptyfd and fdout. */
679 session_pty_cleanup(s);
680 }
Damien Millerb38eff82000-04-01 11:09:21 +1000681}
682
683/*
684 * Sets the value of the given variable in the environment. If the variable
685 * already exists, its value is overriden.
686 */
Damien Miller4af51302000-04-16 11:18:38 +1000687void
Damien Millerb38eff82000-04-01 11:09:21 +1000688child_set_env(char ***envp, unsigned int *envsizep, const char *name,
689 const char *value)
690{
691 unsigned int i, namelen;
692 char **env;
693
694 /*
695 * Find the slot where the value should be stored. If the variable
696 * already exists, we reuse the slot; otherwise we append a new slot
697 * at the end of the array, expanding if necessary.
698 */
699 env = *envp;
700 namelen = strlen(name);
701 for (i = 0; env[i]; i++)
702 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
703 break;
704 if (env[i]) {
705 /* Reuse the slot. */
706 xfree(env[i]);
707 } else {
708 /* New variable. Expand if necessary. */
709 if (i >= (*envsizep) - 1) {
710 (*envsizep) += 50;
711 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
712 }
713 /* Need to set the NULL pointer at end of array beyond the new slot. */
714 env[i + 1] = NULL;
715 }
716
717 /* Allocate space and format the variable in the appropriate slot. */
718 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
719 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
720}
721
722/*
723 * Reads environment variables from the given file and adds/overrides them
724 * into the environment. If the file does not exist, this does nothing.
725 * Otherwise, it must consist of empty lines, comments (line starts with '#')
726 * and assignments of the form name=value. No other forms are allowed.
727 */
Damien Miller4af51302000-04-16 11:18:38 +1000728void
Damien Millerb38eff82000-04-01 11:09:21 +1000729read_environment_file(char ***env, unsigned int *envsize,
730 const char *filename)
731{
732 FILE *f;
733 char buf[4096];
734 char *cp, *value;
735
736 f = fopen(filename, "r");
737 if (!f)
738 return;
739
740 while (fgets(buf, sizeof(buf), f)) {
741 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
742 ;
743 if (!*cp || *cp == '#' || *cp == '\n')
744 continue;
745 if (strchr(cp, '\n'))
746 *strchr(cp, '\n') = '\0';
747 value = strchr(cp, '=');
748 if (value == NULL) {
749 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
750 continue;
751 }
Damien Millerb1715dc2000-05-30 13:44:51 +1000752 /*
753 * Replace the equals sign by nul, and advance value to
754 * the value string.
755 */
Damien Millerb38eff82000-04-01 11:09:21 +1000756 *value = '\0';
757 value++;
758 child_set_env(env, envsize, cp, value);
759 }
760 fclose(f);
761}
762
763#ifdef USE_PAM
764/*
765 * Sets any environment variables which have been specified by PAM
766 */
767void do_pam_environment(char ***env, int *envsize)
768{
769 char *equals, var_name[512], var_val[512];
770 char **pam_env;
771 int i;
772
773 if ((pam_env = fetch_pam_environment()) == NULL)
774 return;
775
776 for(i = 0; pam_env[i] != NULL; i++) {
777 if ((equals = strstr(pam_env[i], "=")) == NULL)
778 continue;
779
780 if (strlen(pam_env[i]) < (sizeof(var_name) - 1)) {
781 memset(var_name, '\0', sizeof(var_name));
782 memset(var_val, '\0', sizeof(var_val));
783
784 strncpy(var_name, pam_env[i], equals - pam_env[i]);
785 strcpy(var_val, equals + 1);
786
787 debug("PAM environment: %s=%s", var_name, var_val);
788
789 child_set_env(env, envsize, var_name, var_val);
790 }
791 }
792}
793#endif /* USE_PAM */
794
Damien Miller5fc85652000-07-09 23:53:07 +1000795#if defined(HAVE_GETUSERATTR)
796/*
797 * AIX-specific login initialisation
798 */
799void set_limit(char *user, char *soft, char *hard, int resource, int mult)
800{
801 struct rlimit rlim;
802 rlim_t tlim;
803 int mask;
804
805 getrlimit(resource, &rlim);
806
807 tlim = (rlim_t) 0;
808 if (getuserattr(user, soft, &tlim, SEC_INT) != -1 && tlim)
809 rlim.rlim_cur = tlim * mult;
810
811 tlim = (rlim_t) 0;
812 if (getuserattr(user, hard, &tlim, SEC_INT) != -1 && tlim)
813 rlim.rlim_max = tlim * mult;
814
815 if (rlim.rlim_cur > rlim.rlim_max)
816 rlim.rlim_max = rlim.rlim_cur;
817
818 if (setrlimit(resource, &rlim) != 0)
819 error("setrlimit(%.10s) failed: %.100s", soft, strerror(errno))
820}
821
822void set_limits_from_userattr(char *user)
823{
824 int mask;
825 char buf[16];
826
827 set_limit(user, S_UFSIZE, S_UFSIZE_HARD, RLIMIT_FSIZE, 512);
828 set_limit(user, S_UCPU, S_UCPU_HARD, RLIMIT_CPU, 1);
829 set_limit(user, S_UDATA, S_UDATA_HARD, RLIMIT_DATA, 512);
830 set_limit(user, S_USTACK, S_USTACK_HARD, RLIMIT_STACK, 512);
831 set_limit(user, S_URSS, S_URSS_HARD, RLIMIT_RSS, 512);
832 set_limit(user, S_UCORE, S_UCORE_HARD, RLIMIT_CORE, 512);
833#if defined(S_UNOFILE)
834 set_limit(user, S_UNOFILE, S_UNOFILE_HARD, RLIMIT_NOFILE, 1);
835#endif
836
837 if (getuserattr(user, S_UMASK, &mask, SEC_INT) != -1) {
838 /* Convert decimal to octal */
839 (void) snprintf(buf, sizeof(buf), "%d", mask);
840 if (sscanf(buf, "%o", &mask) == 1)
841 umask(mask);
842 }
843}
844#endif /* defined(HAVE_GETUSERATTR) */
845
Damien Millerb38eff82000-04-01 11:09:21 +1000846/*
847 * Performs common processing for the child, such as setting up the
848 * environment, closing extra file descriptors, setting the user and group
849 * ids, and executing the command or shell.
850 */
Damien Miller4af51302000-04-16 11:18:38 +1000851void
Damien Millerb38eff82000-04-01 11:09:21 +1000852do_child(const char *command, struct passwd * pw, const char *term,
853 const char *display, const char *auth_proto,
854 const char *auth_data, const char *ttyname)
855{
856 const char *shell, *cp = NULL;
857 char buf[256];
Damien Miller0c043c12000-06-07 21:22:38 +1000858 char cmd[1024];
Damien Millerb38eff82000-04-01 11:09:21 +1000859 FILE *f;
860 unsigned int envsize, i;
861 char **env;
862 extern char **environ;
863 struct stat st;
864 char *argv[10];
Damien Miller91606b12000-06-28 08:22:29 +1000865#ifdef WITH_IRIX_PROJECT
866 prid_t projid;
867#endif /* WITH_IRIX_PROJECT */
Damien Millerb38eff82000-04-01 11:09:21 +1000868
Damien Millerd3a18572000-06-07 19:55:44 +1000869 /* login(1) is only called if we execute the login shell */
870 if (options.use_login && command != NULL)
871 options.use_login = 0;
872
Damien Millerb38eff82000-04-01 11:09:21 +1000873#ifndef USE_PAM /* pam_nologin handles this */
874 f = fopen("/etc/nologin", "r");
875 if (f) {
876 /* /etc/nologin exists. Print its contents and exit. */
877 while (fgets(buf, sizeof(buf), f))
878 fputs(buf, stderr);
879 fclose(f);
880 if (pw->pw_uid != 0)
881 exit(254);
882 }
883#endif /* USE_PAM */
884
Damien Millerb8c656e2000-06-28 15:22:41 +1000885#ifndef HAVE_OSF_SIA
Damien Millerb38eff82000-04-01 11:09:21 +1000886 /* Set login name in the kernel. */
887 if (setlogin(pw->pw_name) < 0)
888 error("setlogin failed: %s", strerror(errno));
Damien Millerb8c656e2000-06-28 15:22:41 +1000889#endif
Damien Millerb38eff82000-04-01 11:09:21 +1000890
891 /* Set uid, gid, and groups. */
892 /* Login(1) does this as well, and it needs uid 0 for the "-h"
893 switch, so we let login(1) to this for us. */
894 if (!options.use_login) {
Damien Millerb8c656e2000-06-28 15:22:41 +1000895#ifdef HAVE_OSF_SIA
896 extern char **saved_argv;
897 extern int saved_argc;
898 char *host = get_canonical_hostname ();
899
900 if (sia_become_user(NULL, saved_argc, saved_argv, host,
901 pw->pw_name, ttyname, 0, NULL, NULL, SIA_BEU_SETLUID) !=
902 SIASUCCESS) {
903 perror("sia_become_user");
904 exit(1);
905 }
906 if (setreuid(geteuid(), geteuid()) < 0) {
907 perror("setreuid");
908 exit(1);
909 }
910#else /* HAVE_OSF_SIA */
Damien Millerb38eff82000-04-01 11:09:21 +1000911 if (getuid() == 0 || geteuid() == 0) {
Damien Miller5fc85652000-07-09 23:53:07 +1000912#if defined(HAVE_GETUSERATTR)
913 set_limits_from_userattr(pw->pw_name);
914#endif /* defined(HAVE_GETUSERATTR) */
915
Damien Millerb38eff82000-04-01 11:09:21 +1000916 if (setgid(pw->pw_gid) < 0) {
917 perror("setgid");
918 exit(1);
919 }
920 /* Initialize the group list. */
921 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
922 perror("initgroups");
923 exit(1);
924 }
925 endgrent();
926
Damien Miller91606b12000-06-28 08:22:29 +1000927#ifdef WITH_IRIX_ARRAY
928 /* initialize array session */
929 if (newarraysess() != 0)
930 fatal("Failed to set up new array session: %.100s",
931 strerror(errno));
932#endif /* WITH_IRIX_ARRAY */
933
934#ifdef WITH_IRIX_PROJECT
935 /* initialize irix project info */
936 if ((projid = getdfltprojuser(pw->pw_name)) == -1) {
937 debug("Failed to get project id, using projid 0");
938 projid = 0;
939 }
940
941 if (setprid(projid))
942 fatal("Failed to initialize project %d for %s: %.100s",
943 (int)projid, pw->pw_name, strerror(errno));
944#endif /* WITH_IRIX_PROJECT */
945
Damien Millerb38eff82000-04-01 11:09:21 +1000946 /* Permanently switch to the desired uid. */
947 permanently_set_uid(pw->pw_uid);
948 }
949 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
950 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
Damien Millerb8c656e2000-06-28 15:22:41 +1000951#endif /* HAVE_OSF_SIA */
Damien Millerb38eff82000-04-01 11:09:21 +1000952 }
953 /*
954 * Get the shell from the password data. An empty shell field is
955 * legal, and means /bin/sh.
956 */
957 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
958
959#ifdef AFS
960 /* Try to get AFS tokens for the local cell. */
961 if (k_hasafs()) {
962 char cell[64];
963
964 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
965 krb_afslog(cell, 0);
966
967 krb_afslog(0, 0);
968 }
969#endif /* AFS */
970
971 /* Initialize the environment. */
972 envsize = 100;
973 env = xmalloc(envsize * sizeof(char *));
974 env[0] = NULL;
975
976 if (!options.use_login) {
977 /* Set basic environment. */
978 child_set_env(&env, &envsize, "USER", pw->pw_name);
979 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
980 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
981 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
982
983 snprintf(buf, sizeof buf, "%.200s/%.50s",
984 _PATH_MAILDIR, pw->pw_name);
985 child_set_env(&env, &envsize, "MAIL", buf);
986
987 /* Normal systems set SHELL by default. */
988 child_set_env(&env, &envsize, "SHELL", shell);
989 }
990 if (getenv("TZ"))
991 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
992
993 /* Set custom environment options from RSA authentication. */
994 while (custom_environment) {
995 struct envstring *ce = custom_environment;
996 char *s = ce->s;
997 int i;
998 for (i = 0; s[i] != '=' && s[i]; i++);
999 if (s[i] == '=') {
1000 s[i] = 0;
1001 child_set_env(&env, &envsize, s, s + i + 1);
1002 }
1003 custom_environment = ce->next;
1004 xfree(ce->s);
1005 xfree(ce);
1006 }
1007
1008 snprintf(buf, sizeof buf, "%.50s %d %d",
1009 get_remote_ipaddr(), get_remote_port(), get_local_port());
1010 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
1011
1012 if (ttyname)
1013 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
1014 if (term)
1015 child_set_env(&env, &envsize, "TERM", term);
1016 if (display)
1017 child_set_env(&env, &envsize, "DISPLAY", display);
1018
1019#ifdef _AIX
1020 {
1021 char *authstate,*krb5cc;
1022
1023 if ((authstate = getenv("AUTHSTATE")) != NULL)
1024 child_set_env(&env,&envsize,"AUTHSTATE",authstate);
1025
1026 if ((krb5cc = getenv("KRB5CCNAME")) != NULL)
1027 child_set_env(&env,&envsize,"KRB5CCNAME",krb5cc);
1028 }
1029#endif
1030
1031#ifdef KRB4
1032 {
1033 extern char *ticket;
1034
1035 if (ticket)
1036 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
1037 }
1038#endif /* KRB4 */
1039
1040#ifdef USE_PAM
1041 /* Pull in any environment variables that may have been set by PAM. */
1042 do_pam_environment(&env, &envsize);
1043#endif /* USE_PAM */
1044
1045 read_environment_file(&env,&envsize,"/etc/environment");
1046
1047 if (xauthfile)
1048 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
1049 if (auth_get_socket_name() != NULL)
1050 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
1051 auth_get_socket_name());
1052
1053 /* read $HOME/.ssh/environment. */
1054 if (!options.use_login) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001055 snprintf(buf, sizeof buf, "%.200s/.ssh/environment",
1056 pw->pw_dir);
Damien Millerb38eff82000-04-01 11:09:21 +10001057 read_environment_file(&env, &envsize, buf);
1058 }
1059 if (debug_flag) {
1060 /* dump the environment */
1061 fprintf(stderr, "Environment:\n");
1062 for (i = 0; env[i]; i++)
1063 fprintf(stderr, " %.200s\n", env[i]);
1064 }
1065 /*
1066 * Close the connection descriptors; note that this is the child, and
1067 * the server will still have the socket open, and it is important
1068 * that we do not shutdown it. Note that the descriptors cannot be
1069 * closed before building the environment, as we call
1070 * get_remote_ipaddr there.
1071 */
1072 if (packet_get_connection_in() == packet_get_connection_out())
1073 close(packet_get_connection_in());
1074 else {
1075 close(packet_get_connection_in());
1076 close(packet_get_connection_out());
1077 }
1078 /*
1079 * Close all descriptors related to channels. They will still remain
1080 * open in the parent.
1081 */
1082 /* XXX better use close-on-exec? -markus */
1083 channel_close_all();
1084
1085 /*
1086 * Close any extra file descriptors. Note that there may still be
1087 * descriptors left by system functions. They will be closed later.
1088 */
1089 endpwent();
1090
1091 /*
1092 * Close any extra open file descriptors so that we don\'t have them
1093 * hanging around in clients. Note that we want to do this after
1094 * initgroups, because at least on Solaris 2.3 it leaves file
1095 * descriptors open.
1096 */
1097 for (i = 3; i < 64; i++)
1098 close(i);
1099
1100 /* Change current directory to the user\'s home directory. */
1101 if (chdir(pw->pw_dir) < 0)
1102 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
1103 pw->pw_dir, strerror(errno));
1104
1105 /*
1106 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
1107 * xauth are run in the proper environment.
1108 */
1109 environ = env;
1110
1111 /*
1112 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
1113 * in this order).
1114 */
1115 if (!options.use_login) {
1116 if (stat(SSH_USER_RC, &st) >= 0) {
1117 if (debug_flag)
Damien Miller7b413d22000-07-01 13:24:21 +10001118 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_USER_RC);
Damien Millerb38eff82000-04-01 11:09:21 +10001119
Damien Miller7b413d22000-07-01 13:24:21 +10001120 f = popen(_PATH_BSHELL " " SSH_USER_RC, "w");
Damien Millerb38eff82000-04-01 11:09:21 +10001121 if (f) {
1122 if (auth_proto != NULL && auth_data != NULL)
1123 fprintf(f, "%s %s\n", auth_proto, auth_data);
1124 pclose(f);
1125 } else
1126 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
1127 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
1128 if (debug_flag)
Damien Miller7b413d22000-07-01 13:24:21 +10001129 fprintf(stderr, "Running "_PATH_BSHELL" %s\n", SSH_SYSTEM_RC);
Damien Millerb38eff82000-04-01 11:09:21 +10001130
Damien Miller7b413d22000-07-01 13:24:21 +10001131 f = popen(_PATH_BSHELL " " SSH_SYSTEM_RC, "w");
Damien Millerb38eff82000-04-01 11:09:21 +10001132 if (f) {
1133 if (auth_proto != NULL && auth_data != NULL)
1134 fprintf(f, "%s %s\n", auth_proto, auth_data);
1135 pclose(f);
1136 } else
1137 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
Damien Miller0c043c12000-06-07 21:22:38 +10001138 } else if (options.xauth_location != NULL) {
Damien Millerb38eff82000-04-01 11:09:21 +10001139 /* Add authority data to .Xauthority if appropriate. */
1140 if (auth_proto != NULL && auth_data != NULL) {
Damien Millerd999ae22000-05-20 12:49:31 +10001141 char *screen = strchr(display, ':');
1142 if (debug_flag) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001143 fprintf(stderr,
1144 "Running %.100s add %.100s %.100s %.100s\n",
Damien Miller0c043c12000-06-07 21:22:38 +10001145 options.xauth_location, display,
1146 auth_proto, auth_data);
Damien Millerd999ae22000-05-20 12:49:31 +10001147 if (screen != NULL)
Damien Millerb1715dc2000-05-30 13:44:51 +10001148 fprintf(stderr,
1149 "Adding %.*s/unix%s %s %s\n",
1150 screen-display, display,
1151 screen, auth_proto, auth_data);
Damien Millerd999ae22000-05-20 12:49:31 +10001152 }
Damien Miller0c043c12000-06-07 21:22:38 +10001153 snprintf(cmd, sizeof cmd, "%s -q -",
1154 options.xauth_location);
1155 f = popen(cmd, "w");
Damien Millerb38eff82000-04-01 11:09:21 +10001156 if (f) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001157 fprintf(f, "add %s %s %s\n", display,
1158 auth_proto, auth_data);
Damien Millerd999ae22000-05-20 12:49:31 +10001159 if (screen != NULL)
1160 fprintf(f, "add %.*s/unix%s %s %s\n",
Damien Millerb1715dc2000-05-30 13:44:51 +10001161 screen-display, display,
1162 screen, auth_proto, auth_data);
Damien Millerb38eff82000-04-01 11:09:21 +10001163 pclose(f);
Damien Miller0c043c12000-06-07 21:22:38 +10001164 } else {
1165 fprintf(stderr, "Could not run %s\n",
1166 cmd);
1167 }
Damien Millerb38eff82000-04-01 11:09:21 +10001168 }
1169 }
Damien Millerb38eff82000-04-01 11:09:21 +10001170 /* Get the last component of the shell name. */
1171 cp = strrchr(shell, '/');
1172 if (cp)
1173 cp++;
1174 else
1175 cp = shell;
1176 }
1177 /*
1178 * If we have no command, execute the shell. In this case, the shell
1179 * name to be passed in argv[0] is preceded by '-' to indicate that
1180 * this is a login shell.
1181 */
1182 if (!command) {
1183 if (!options.use_login) {
1184 char buf[256];
1185
1186 /*
1187 * Check for mail if we have a tty and it was enabled
1188 * in server options.
1189 */
1190 if (ttyname && options.check_mail) {
1191 char *mailbox;
1192 struct stat mailstat;
1193 mailbox = getenv("MAIL");
1194 if (mailbox != NULL) {
Damien Millerb1715dc2000-05-30 13:44:51 +10001195 if (stat(mailbox, &mailstat) != 0 ||
1196 mailstat.st_size == 0)
Damien Millerb38eff82000-04-01 11:09:21 +10001197 printf("No mail.\n");
1198 else if (mailstat.st_mtime < mailstat.st_atime)
1199 printf("You have mail.\n");
1200 else
1201 printf("You have new mail.\n");
1202 }
1203 }
1204 /* Start the shell. Set initial character to '-'. */
1205 buf[0] = '-';
1206 strncpy(buf + 1, cp, sizeof(buf) - 1);
1207 buf[sizeof(buf) - 1] = 0;
1208
1209 /* Execute the shell. */
1210 argv[0] = buf;
1211 argv[1] = NULL;
1212 execve(shell, argv, env);
1213
1214 /* Executing the shell failed. */
1215 perror(shell);
1216 exit(1);
1217
1218 } else {
1219 /* Launch login(1). */
1220
Damien Miller7b413d22000-07-01 13:24:21 +10001221 execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(),
Damien Millerb38eff82000-04-01 11:09:21 +10001222 "-p", "-f", "--", pw->pw_name, NULL);
1223
1224 /* Login couldn't be executed, die. */
1225
1226 perror("login");
1227 exit(1);
1228 }
1229 }
1230 /*
1231 * Execute the command using the user's shell. This uses the -c
1232 * option to execute the command.
1233 */
1234 argv[0] = (char *) cp;
1235 argv[1] = "-c";
1236 argv[2] = (char *) command;
1237 argv[3] = NULL;
1238 execve(shell, argv, env);
1239 perror(shell);
1240 exit(1);
1241}
1242
1243Session *
1244session_new(void)
1245{
1246 int i;
1247 static int did_init = 0;
1248 if (!did_init) {
1249 debug("session_new: init");
1250 for(i = 0; i < MAX_SESSIONS; i++) {
1251 sessions[i].used = 0;
1252 sessions[i].self = i;
1253 }
1254 did_init = 1;
1255 }
1256 for(i = 0; i < MAX_SESSIONS; i++) {
1257 Session *s = &sessions[i];
1258 if (! s->used) {
1259 s->pid = 0;
Damien Millerbd483e72000-04-30 10:00:53 +10001260 s->extended = 0;
Damien Millerb38eff82000-04-01 11:09:21 +10001261 s->chanid = -1;
1262 s->ptyfd = -1;
1263 s->ttyfd = -1;
1264 s->term = NULL;
1265 s->pw = NULL;
1266 s->display = NULL;
1267 s->screen = 0;
1268 s->auth_data = NULL;
1269 s->auth_proto = NULL;
1270 s->used = 1;
Damien Millerbd483e72000-04-30 10:00:53 +10001271 s->pw = NULL;
Damien Millerb38eff82000-04-01 11:09:21 +10001272 debug("session_new: session %d", i);
1273 return s;
1274 }
1275 }
1276 return NULL;
1277}
1278
1279void
1280session_dump(void)
1281{
1282 int i;
1283 for(i = 0; i < MAX_SESSIONS; i++) {
1284 Session *s = &sessions[i];
1285 debug("dump: used %d session %d %p channel %d pid %d",
1286 s->used,
1287 s->self,
1288 s,
1289 s->chanid,
1290 s->pid);
1291 }
1292}
1293
Damien Millerefb4afe2000-04-12 18:45:05 +10001294int
1295session_open(int chanid)
1296{
1297 Session *s = session_new();
1298 debug("session_open: channel %d", chanid);
1299 if (s == NULL) {
1300 error("no more sessions");
1301 return 0;
1302 }
Damien Millerefb4afe2000-04-12 18:45:05 +10001303 s->pw = auth_get_user();
1304 if (s->pw == NULL)
Damien Millerbd483e72000-04-30 10:00:53 +10001305 fatal("no user for session %i", s->self);
1306 debug("session_open: session %d: link with channel %d", s->self, chanid);
1307 s->chanid = chanid;
Damien Millerefb4afe2000-04-12 18:45:05 +10001308 return 1;
1309}
1310
1311Session *
1312session_by_channel(int id)
1313{
1314 int i;
1315 for(i = 0; i < MAX_SESSIONS; i++) {
1316 Session *s = &sessions[i];
1317 if (s->used && s->chanid == id) {
1318 debug("session_by_channel: session %d channel %d", i, id);
1319 return s;
1320 }
1321 }
1322 debug("session_by_channel: unknown channel %d", id);
1323 session_dump();
1324 return NULL;
1325}
1326
1327Session *
1328session_by_pid(pid_t pid)
1329{
1330 int i;
1331 debug("session_by_pid: pid %d", pid);
1332 for(i = 0; i < MAX_SESSIONS; i++) {
1333 Session *s = &sessions[i];
1334 if (s->used && s->pid == pid)
1335 return s;
1336 }
1337 error("session_by_pid: unknown pid %d", pid);
1338 session_dump();
1339 return NULL;
1340}
1341
1342int
1343session_window_change_req(Session *s)
1344{
1345 s->col = packet_get_int();
1346 s->row = packet_get_int();
1347 s->xpixel = packet_get_int();
1348 s->ypixel = packet_get_int();
Damien Miller4af51302000-04-16 11:18:38 +10001349 packet_done();
Damien Millerefb4afe2000-04-12 18:45:05 +10001350 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1351 return 1;
1352}
1353
1354int
1355session_pty_req(Session *s)
1356{
1357 unsigned int len;
Damien Miller4af51302000-04-16 11:18:38 +10001358 char *term_modes; /* encoded terminal modes */
Damien Millerefb4afe2000-04-12 18:45:05 +10001359
Damien Millerf6d9e222000-06-18 14:50:44 +10001360 if (no_pty_flag)
1361 return 0;
Damien Millerefb4afe2000-04-12 18:45:05 +10001362 if (s->ttyfd != -1)
Damien Miller4af51302000-04-16 11:18:38 +10001363 return 0;
Damien Millerefb4afe2000-04-12 18:45:05 +10001364 s->term = packet_get_string(&len);
1365 s->col = packet_get_int();
1366 s->row = packet_get_int();
1367 s->xpixel = packet_get_int();
1368 s->ypixel = packet_get_int();
Damien Miller4af51302000-04-16 11:18:38 +10001369 term_modes = packet_get_string(&len);
1370 packet_done();
Damien Millerefb4afe2000-04-12 18:45:05 +10001371
1372 if (strcmp(s->term, "") == 0) {
1373 xfree(s->term);
1374 s->term = NULL;
1375 }
1376 /* Allocate a pty and open it. */
1377 if (!pty_allocate(&s->ptyfd, &s->ttyfd, s->tty, sizeof(s->tty))) {
1378 xfree(s->term);
1379 s->term = NULL;
1380 s->ptyfd = -1;
1381 s->ttyfd = -1;
1382 error("session_pty_req: session %d alloc failed", s->self);
Damien Miller4af51302000-04-16 11:18:38 +10001383 xfree(term_modes);
1384 return 0;
Damien Millerefb4afe2000-04-12 18:45:05 +10001385 }
1386 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
1387 /*
1388 * Add a cleanup function to clear the utmp entry and record logout
1389 * time in case we call fatal() (e.g., the connection gets closed).
1390 */
1391 fatal_add_cleanup(pty_cleanup_proc, (void *)s);
1392 pty_setowner(s->pw, s->tty);
1393 /* Get window size from the packet. */
1394 pty_change_window_size(s->ptyfd, s->row, s->col, s->xpixel, s->ypixel);
1395
Damien Millere247cc42000-05-07 12:03:14 +10001396 session_proctitle(s);
1397
Damien Miller5f056372000-04-16 12:31:48 +10001398 /* XXX parse and set terminal modes */
1399 xfree(term_modes);
Damien Millerefb4afe2000-04-12 18:45:05 +10001400 return 1;
1401}
1402
Damien Millerbd483e72000-04-30 10:00:53 +10001403int
1404session_subsystem_req(Session *s)
1405{
1406 unsigned int len;
1407 int success = 0;
1408 char *subsys = packet_get_string(&len);
Damien Millerf6d9e222000-06-18 14:50:44 +10001409 int i;
Damien Millerbd483e72000-04-30 10:00:53 +10001410
1411 packet_done();
1412 log("subsystem request for %s", subsys);
1413
Damien Millerf6d9e222000-06-18 14:50:44 +10001414 for (i = 0; i < options.num_subsystems; i++) {
1415 if(strcmp(subsys, options.subsystem_name[i]) == 0) {
1416 debug("subsystem: exec() %s", options.subsystem_command[i]);
1417 do_exec_no_pty(s, options.subsystem_command[i], s->pw);
1418 success = 1;
1419 }
1420 }
1421
1422 if (!success)
1423 log("subsystem request for %s failed, subsystem not found", subsys);
1424
Damien Millerbd483e72000-04-30 10:00:53 +10001425 xfree(subsys);
1426 return success;
1427}
1428
1429int
1430session_x11_req(Session *s)
1431{
Damien Millerf6d9e222000-06-18 14:50:44 +10001432 if (!no_port_forwarding_flag) {
1433 debug("X11 forwarding disabled in user configuration file.");
1434 return 0;
1435 }
Damien Millerbd483e72000-04-30 10:00:53 +10001436 if (!options.x11_forwarding) {
1437 debug("X11 forwarding disabled in server configuration file.");
1438 return 0;
1439 }
1440 if (xauthfile != NULL) {
1441 debug("X11 fwd already started.");
1442 return 0;
1443 }
1444
1445 debug("Received request for X11 forwarding with auth spoofing.");
1446 if (s->display != NULL)
1447 packet_disconnect("Protocol error: X11 display already set.");
1448
1449 s->single_connection = packet_get_char();
1450 s->auth_proto = packet_get_string(NULL);
1451 s->auth_data = packet_get_string(NULL);
1452 s->screen = packet_get_int();
1453 packet_done();
1454
1455 s->display = x11_create_display_inet(s->screen, options.x11_display_offset);
1456 if (s->display == NULL) {
1457 xfree(s->auth_proto);
1458 xfree(s->auth_data);
1459 return 0;
1460 }
1461 xauthfile = xmalloc(MAXPATHLEN);
1462 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN);
1463 temporarily_use_uid(s->pw->pw_uid);
1464 if (mkdtemp(xauthfile) == NULL) {
1465 restore_uid();
1466 error("private X11 dir: mkdtemp %s failed: %s",
1467 xauthfile, strerror(errno));
1468 xfree(xauthfile);
1469 xauthfile = NULL;
1470 xfree(s->auth_proto);
1471 xfree(s->auth_data);
1472 /* XXXX remove listening channels */
1473 return 0;
1474 }
1475 strlcat(xauthfile, "/cookies", MAXPATHLEN);
1476 open(xauthfile, O_RDWR|O_CREAT|O_EXCL, 0600);
1477 restore_uid();
1478 fatal_add_cleanup(xauthfile_cleanup_proc, s);
1479 return 1;
1480}
1481
Damien Millerf6d9e222000-06-18 14:50:44 +10001482int
1483session_shell_req(Session *s)
1484{
1485 /* if forced_command == NULL, the shell is execed */
1486 char *shell = forced_command;
1487 packet_done();
1488 s->extended = 1;
1489 if (s->ttyfd == -1)
1490 do_exec_no_pty(s, shell, s->pw);
1491 else
1492 do_exec_pty(s, shell, s->pw);
1493 return 1;
1494}
1495
1496int
1497session_exec_req(Session *s)
1498{
1499 unsigned int len;
1500 char *command = packet_get_string(&len);
1501 packet_done();
1502 if (forced_command) {
1503 xfree(command);
1504 command = forced_command;
1505 debug("Forced command '%.500s'", forced_command);
1506 }
1507 s->extended = 1;
1508 if (s->ttyfd == -1)
1509 do_exec_no_pty(s, command, s->pw);
1510 else
1511 do_exec_pty(s, command, s->pw);
1512 if (forced_command == NULL)
1513 xfree(command);
1514 return 1;
1515}
1516
Damien Millerefb4afe2000-04-12 18:45:05 +10001517void
1518session_input_channel_req(int id, void *arg)
1519{
1520 unsigned int len;
1521 int reply;
1522 int success = 0;
1523 char *rtype;
1524 Session *s;
1525 Channel *c;
1526
1527 rtype = packet_get_string(&len);
1528 reply = packet_get_char();
1529
1530 s = session_by_channel(id);
1531 if (s == NULL)
1532 fatal("session_input_channel_req: channel %d: no session", id);
1533 c = channel_lookup(id);
1534 if (c == NULL)
1535 fatal("session_input_channel_req: channel %d: bad channel", id);
1536
1537 debug("session_input_channel_req: session %d channel %d request %s reply %d",
1538 s->self, id, rtype, reply);
1539
1540 /*
1541 * a session is in LARVAL state until a shell
1542 * or programm is executed
1543 */
1544 if (c->type == SSH_CHANNEL_LARVAL) {
1545 if (strcmp(rtype, "shell") == 0) {
Damien Millerf6d9e222000-06-18 14:50:44 +10001546 success = session_shell_req(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001547 } else if (strcmp(rtype, "exec") == 0) {
Damien Millerf6d9e222000-06-18 14:50:44 +10001548 success = session_exec_req(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001549 } else if (strcmp(rtype, "pty-req") == 0) {
Damien Miller5f056372000-04-16 12:31:48 +10001550 success = session_pty_req(s);
Damien Millerbd483e72000-04-30 10:00:53 +10001551 } else if (strcmp(rtype, "x11-req") == 0) {
1552 success = session_x11_req(s);
1553 } else if (strcmp(rtype, "subsystem") == 0) {
1554 success = session_subsystem_req(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001555 }
1556 }
1557 if (strcmp(rtype, "window-change") == 0) {
1558 success = session_window_change_req(s);
1559 }
1560
1561 if (reply) {
1562 packet_start(success ?
1563 SSH2_MSG_CHANNEL_SUCCESS : SSH2_MSG_CHANNEL_FAILURE);
1564 packet_put_int(c->remote_id);
1565 packet_send();
1566 }
1567 xfree(rtype);
1568}
1569
1570void
1571session_set_fds(Session *s, int fdin, int fdout, int fderr)
1572{
1573 if (!compat20)
1574 fatal("session_set_fds: called for proto != 2.0");
1575 /*
1576 * now that have a child and a pipe to the child,
1577 * we can activate our channel and register the fd's
1578 */
1579 if (s->chanid == -1)
1580 fatal("no channel for session %d", s->self);
1581 channel_set_fds(s->chanid,
1582 fdout, fdin, fderr,
1583 fderr == -1 ? CHAN_EXTENDED_IGNORE : CHAN_EXTENDED_READ);
1584}
1585
Damien Millerb38eff82000-04-01 11:09:21 +10001586void
1587session_pty_cleanup(Session *s)
1588{
1589 if (s == NULL || s->ttyfd == -1)
1590 return;
1591
1592 debug("session_pty_cleanup: session %i release %s", s->self, s->tty);
1593
1594 /* Cancel the cleanup function. */
1595 fatal_remove_cleanup(pty_cleanup_proc, (void *)s);
1596
1597 /* Record that the user has logged out. */
1598 record_logout(s->pid, s->tty);
1599
1600 /* Release the pseudo-tty. */
1601 pty_release(s->tty);
1602
1603 /*
1604 * Close the server side of the socket pairs. We must do this after
1605 * the pty cleanup, so that another process doesn't get this pty
1606 * while we're still cleaning up.
1607 */
1608 if (close(s->ptymaster) < 0)
1609 error("close(s->ptymaster): %s", strerror(errno));
1610}
Damien Millerefb4afe2000-04-12 18:45:05 +10001611
1612void
1613session_exit_message(Session *s, int status)
1614{
1615 Channel *c;
1616 if (s == NULL)
1617 fatal("session_close: no session");
1618 c = channel_lookup(s->chanid);
1619 if (c == NULL)
1620 fatal("session_close: session %d: no channel %d",
1621 s->self, s->chanid);
1622 debug("session_exit_message: session %d channel %d pid %d",
1623 s->self, s->chanid, s->pid);
1624
1625 if (WIFEXITED(status)) {
1626 channel_request_start(s->chanid,
1627 "exit-status", 0);
1628 packet_put_int(WEXITSTATUS(status));
1629 packet_send();
1630 } else if (WIFSIGNALED(status)) {
1631 channel_request_start(s->chanid,
1632 "exit-signal", 0);
1633 packet_put_int(WTERMSIG(status));
Damien Millerf3c6cf12000-05-17 22:08:29 +10001634#ifdef WCOREDUMP
Damien Millerefb4afe2000-04-12 18:45:05 +10001635 packet_put_char(WCOREDUMP(status));
Damien Millerf3c6cf12000-05-17 22:08:29 +10001636#else /* WCOREDUMP */
1637 packet_put_char(0);
1638#endif /* WCOREDUMP */
Damien Millerefb4afe2000-04-12 18:45:05 +10001639 packet_put_cstring("");
1640 packet_put_cstring("");
1641 packet_send();
1642 } else {
1643 /* Some weird exit cause. Just exit. */
1644 packet_disconnect("wait returned status %04x.", status);
1645 }
1646
1647 /* disconnect channel */
1648 debug("session_exit_message: release channel %d", s->chanid);
1649 channel_cancel_cleanup(s->chanid);
Damien Miller166fca82000-04-20 07:42:21 +10001650 /*
1651 * emulate a write failure with 'chan_write_failed', nobody will be
1652 * interested in data we write.
1653 * Note that we must not call 'chan_read_failed', since there could
1654 * be some more data waiting in the pipe.
1655 */
Damien Millerbd483e72000-04-30 10:00:53 +10001656 if (c->ostate != CHAN_OUTPUT_CLOSED)
1657 chan_write_failed(c);
Damien Millerefb4afe2000-04-12 18:45:05 +10001658 s->chanid = -1;
1659}
1660
1661void
1662session_free(Session *s)
1663{
1664 debug("session_free: session %d pid %d", s->self, s->pid);
1665 if (s->term)
1666 xfree(s->term);
1667 if (s->display)
1668 xfree(s->display);
1669 if (s->auth_data)
1670 xfree(s->auth_data);
1671 if (s->auth_proto)
1672 xfree(s->auth_proto);
1673 s->used = 0;
1674}
1675
1676void
1677session_close(Session *s)
1678{
1679 session_pty_cleanup(s);
1680 session_free(s);
Damien Millere247cc42000-05-07 12:03:14 +10001681 session_proctitle(s);
Damien Millerefb4afe2000-04-12 18:45:05 +10001682}
1683
1684void
1685session_close_by_pid(pid_t pid, int status)
1686{
1687 Session *s = session_by_pid(pid);
1688 if (s == NULL) {
1689 debug("session_close_by_pid: no session for pid %d", s->pid);
1690 return;
1691 }
1692 if (s->chanid != -1)
1693 session_exit_message(s, status);
1694 session_close(s);
1695}
1696
1697/*
1698 * this is called when a channel dies before
1699 * the session 'child' itself dies
1700 */
1701void
1702session_close_by_channel(int id, void *arg)
1703{
1704 Session *s = session_by_channel(id);
1705 if (s == NULL) {
1706 debug("session_close_by_channel: no session for channel %d", id);
1707 return;
1708 }
1709 /* disconnect channel */
1710 channel_cancel_cleanup(s->chanid);
1711 s->chanid = -1;
1712
1713 debug("session_close_by_channel: channel %d kill %d", id, s->pid);
1714 if (s->pid == 0) {
1715 /* close session immediately */
1716 session_close(s);
1717 } else {
1718 /* notify child, delay session cleanup */
Damien Miller099f5052000-06-22 20:57:11 +10001719 if (s->pid <= 1)
Damien Miller7a445bb2000-06-26 13:12:37 +10001720 fatal("session_close_by_channel: Unsafe s->pid = %d", s->pid);
1721 if (kill(s->pid, (s->ttyfd == -1) ? SIGTERM : SIGHUP) < 0)
Damien Millerefb4afe2000-04-12 18:45:05 +10001722 error("session_close_by_channel: kill %d: %s",
1723 s->pid, strerror(errno));
1724 }
1725}
1726
Damien Millere247cc42000-05-07 12:03:14 +10001727char *
1728session_tty_list(void)
1729{
1730 static char buf[1024];
1731 int i;
1732 buf[0] = '\0';
1733 for(i = 0; i < MAX_SESSIONS; i++) {
1734 Session *s = &sessions[i];
1735 if (s->used && s->ttyfd != -1) {
1736 if (buf[0] != '\0')
1737 strlcat(buf, ",", sizeof buf);
1738 strlcat(buf, strrchr(s->tty, '/') + 1, sizeof buf);
1739 }
1740 }
1741 if (buf[0] == '\0')
1742 strlcpy(buf, "notty", sizeof buf);
1743 return buf;
1744}
1745
1746void
1747session_proctitle(Session *s)
1748{
1749 if (s->pw == NULL)
1750 error("no user for session %d", s->self);
1751 else
1752 setproctitle("%s@%s", s->pw->pw_name, session_tty_list());
1753}
1754
Damien Millerefb4afe2000-04-12 18:45:05 +10001755void
1756do_authenticated2(void)
1757{
1758 /*
1759 * Cancel the alarm we set to limit the time taken for
1760 * authentication.
1761 */
1762 alarm(0);
Damien Millerefb4afe2000-04-12 18:45:05 +10001763 server_loop2();
Damien Miller1b26ab22000-04-30 10:12:49 +10001764 if (xauthfile)
1765 xauthfile_cleanup_proc(NULL);
Damien Millerefb4afe2000-04-12 18:45:05 +10001766}