blob: 316723a83f67862c87a839381efd03547f230cd0 [file] [log] [blame]
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001/*
Damien Miller95def091999-11-25 00:26:21 +11002 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 * All rights reserved
5 * Created: Fri Mar 17 17:09:28 1995 ylo
6 * This program is the ssh daemon. It listens for connections from clients, and
7 * performs authentication, executes use commands or shell, and forwards
8 * information to/from the application to the user client over an encrypted
9 * connection. This can also handle forwarding of X11, TCP/IP, and authentication
10 * agent connections.
11 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100012
13#include "includes.h"
Damien Miller34132e52000-01-14 15:45:46 +110014RCSID("$Id: sshd.c,v 1.50 2000/01/14 04:45:52 damien Exp $");
Damien Millerd4a8b7e1999-10-27 13:42:43 +100015
16#include "xmalloc.h"
17#include "rsa.h"
18#include "ssh.h"
19#include "pty.h"
20#include "packet.h"
21#include "buffer.h"
22#include "cipher.h"
23#include "mpaux.h"
24#include "servconf.h"
25#include "uidswap.h"
26#include "compat.h"
27
28#ifdef LIBWRAP
29#include <tcpd.h>
30#include <syslog.h>
31int allow_severity = LOG_INFO;
32int deny_severity = LOG_WARNING;
33#endif /* LIBWRAP */
34
35#ifndef O_NOCTTY
36#define O_NOCTTY 0
37#endif
38
Damien Millerd4a8b7e1999-10-27 13:42:43 +100039/* Local Xauthority file. */
Damien Miller5ce662a1999-11-11 17:57:39 +110040static char *xauthfile = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +100041
42/* Server configuration options. */
43ServerOptions options;
44
45/* Name of the server configuration file. */
46char *config_file_name = SERVER_CONFIG_FILE;
47
Damien Miller34132e52000-01-14 15:45:46 +110048/*
49 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
50 * Default value is AF_UNSPEC means both IPv4 and IPv6.
51 */
52int IPv4or6 = AF_UNSPEC;
53
Damien Miller95def091999-11-25 00:26:21 +110054/*
55 * Debug mode flag. This can be set on the command line. If debug
56 * mode is enabled, extra debugging output will be sent to the system
57 * log, the daemon will not go to background, and will exit after processing
58 * the first connection.
59 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100060int debug_flag = 0;
61
62/* Flag indicating that the daemon is being started from inetd. */
63int inetd_flag = 0;
64
Damien Miller5ce662a1999-11-11 17:57:39 +110065/* debug goes to stderr unless inetd_flag is set */
66int log_stderr = 0;
67
Damien Millerd4a8b7e1999-10-27 13:42:43 +100068/* argv[0] without path. */
69char *av0;
70
71/* Saved arguments to main(). */
72char **saved_argv;
73
Damien Miller5428f641999-11-25 11:54:57 +110074/*
Damien Miller34132e52000-01-14 15:45:46 +110075 * The sockets that the server is listening; this is used in the SIGHUP
76 * signal handler.
Damien Miller5428f641999-11-25 11:54:57 +110077 */
Damien Miller34132e52000-01-14 15:45:46 +110078#define MAX_LISTEN_SOCKS 16
79int listen_socks[MAX_LISTEN_SOCKS];
80int num_listen_socks = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +100081
Damien Miller5428f641999-11-25 11:54:57 +110082/*
83 * the client's version string, passed by sshd2 in compat mode. if != NULL,
84 * sshd will skip the version-number exchange
85 */
Damien Miller95def091999-11-25 00:26:21 +110086char *client_version_string = NULL;
87
88/* Flags set in auth-rsa from authorized_keys flags. These are set in auth-rsa.c. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100089int no_port_forwarding_flag = 0;
90int no_agent_forwarding_flag = 0;
91int no_x11_forwarding_flag = 0;
92int no_pty_flag = 0;
Damien Miller95def091999-11-25 00:26:21 +110093
94/* RSA authentication "command=" option. */
95char *forced_command = NULL;
96
97/* RSA authentication "environment=" options. */
98struct envstring *custom_environment = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +100099
100/* Session id for the current session. */
101unsigned char session_id[16];
102
Damien Miller5428f641999-11-25 11:54:57 +1100103/*
104 * Any really sensitive data in the application is contained in this
105 * structure. The idea is that this structure could be locked into memory so
106 * that the pages do not get written into swap. However, there are some
107 * problems. The private key contains BIGNUMs, and we do not (in principle)
108 * have access to the internals of them, and locking just the structure is
109 * not very useful. Currently, memory locking is not implemented.
110 */
Damien Miller95def091999-11-25 00:26:21 +1100111struct {
112 RSA *private_key; /* Private part of server key. */
113 RSA *host_key; /* Private part of host key. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000114} sensitive_data;
115
Damien Miller5428f641999-11-25 11:54:57 +1100116/*
117 * Flag indicating whether the current session key has been used. This flag
118 * is set whenever the key is used, and cleared when the key is regenerated.
119 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000120int key_used = 0;
121
122/* This is set to true when SIGHUP is received. */
123int received_sighup = 0;
124
125/* Public side of the server key. This value is regenerated regularly with
126 the private key. */
127RSA *public_key;
128
129/* Prototypes for various functions defined later in this file. */
Damien Miller2ccf6611999-11-15 15:25:10 +1100130void do_connection();
131void do_authentication(char *user);
Damien Miller95def091999-11-25 00:26:21 +1100132void do_authloop(struct passwd * pw);
Damien Miller2ccf6611999-11-15 15:25:10 +1100133void do_fake_authloop(char *user);
Damien Miller95def091999-11-25 00:26:21 +1100134void do_authenticated(struct passwd * pw);
135void do_exec_pty(const char *command, int ptyfd, int ttyfd,
136 const char *ttyname, struct passwd * pw, const char *term,
137 const char *display, const char *auth_proto,
138 const char *auth_data);
139void do_exec_no_pty(const char *command, struct passwd * pw,
140 const char *display, const char *auth_proto,
141 const char *auth_data);
142void do_child(const char *command, struct passwd * pw, const char *term,
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000143 const char *display, const char *auth_proto,
144 const char *auth_data, const char *ttyname);
Damien Miller2ccf6611999-11-15 15:25:10 +1100145
Damien Miller95def091999-11-25 00:26:21 +1100146/*
Damien Miller34132e52000-01-14 15:45:46 +1100147 * Close all listening sockets
148 */
149void
150close_listen_socks(void)
151{
152 int i;
153 for (i = 0; i < num_listen_socks; i++)
154 close(listen_socks[i]);
155 num_listen_socks = -1;
156}
157
158/*
Damien Miller95def091999-11-25 00:26:21 +1100159 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
160 * the effect is to reread the configuration file (and to regenerate
161 * the server key).
162 */
163void
164sighup_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000165{
Damien Miller95def091999-11-25 00:26:21 +1100166 received_sighup = 1;
167 signal(SIGHUP, sighup_handler);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000168}
169
Damien Miller95def091999-11-25 00:26:21 +1100170/*
171 * Called from the main program after receiving SIGHUP.
172 * Restarts the server.
173 */
174void
175sighup_restart()
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000176{
Damien Miller95def091999-11-25 00:26:21 +1100177 log("Received SIGHUP; restarting.");
Damien Miller34132e52000-01-14 15:45:46 +1100178 close_listen_socks();
Damien Miller95def091999-11-25 00:26:21 +1100179 execv(saved_argv[0], saved_argv);
180 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
181 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000182}
183
Damien Miller95def091999-11-25 00:26:21 +1100184/*
185 * Generic signal handler for terminating signals in the master daemon.
186 * These close the listen socket; not closing it seems to cause "Address
187 * already in use" problems on some machines, which is inconvenient.
188 */
189void
190sigterm_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000191{
Damien Miller95def091999-11-25 00:26:21 +1100192 log("Received signal %d; terminating.", sig);
Damien Miller34132e52000-01-14 15:45:46 +1100193 close_listen_socks();
Damien Miller95def091999-11-25 00:26:21 +1100194 exit(255);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000195}
196
Damien Miller95def091999-11-25 00:26:21 +1100197/*
198 * SIGCHLD handler. This is called whenever a child dies. This will then
199 * reap any zombies left by exited c.
200 */
201void
202main_sigchld_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000203{
Damien Miller95def091999-11-25 00:26:21 +1100204 int save_errno = errno;
205 int status;
Damien Miller431f66b1999-11-21 18:31:57 +1100206
Damien Miller95def091999-11-25 00:26:21 +1100207 while (waitpid(-1, &status, WNOHANG) > 0)
208 ;
Damien Miller431f66b1999-11-21 18:31:57 +1100209
Damien Miller95def091999-11-25 00:26:21 +1100210 signal(SIGCHLD, main_sigchld_handler);
211 errno = save_errno;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000212}
213
Damien Miller95def091999-11-25 00:26:21 +1100214/*
215 * Signal handler for the alarm after the login grace period has expired.
216 */
217void
218grace_alarm_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000219{
Damien Miller95def091999-11-25 00:26:21 +1100220 /* Close the connection. */
221 packet_close();
222
223 /* Log error and exit. */
224 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000225}
226
Damien Miller95def091999-11-25 00:26:21 +1100227/*
228 * convert ssh auth msg type into description
229 */
230char *
231get_authname(int type)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000232{
Damien Miller95def091999-11-25 00:26:21 +1100233 switch (type) {
234 case SSH_CMSG_AUTH_PASSWORD:
235 return "password";
236 case SSH_CMSG_AUTH_RSA:
237 return "rsa";
238 case SSH_CMSG_AUTH_RHOSTS_RSA:
239 return "rhosts-rsa";
240 case SSH_CMSG_AUTH_RHOSTS:
241 return "rhosts";
242#ifdef KRB4
243 case SSH_CMSG_AUTH_KERBEROS:
244 return "kerberos";
245#endif
246#ifdef SKEY
247 case SSH_CMSG_AUTH_TIS_RESPONSE:
248 return "s/key";
249#endif
250 }
251 fatal("get_authname: unknown auth %d: internal error", type);
252 return NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000253}
254
Damien Miller95def091999-11-25 00:26:21 +1100255/*
256 * Signal handler for the key regeneration alarm. Note that this
257 * alarm only occurs in the daemon waiting for connections, and it does not
258 * do anything with the private key or random state before forking.
259 * Thus there should be no concurrency control/asynchronous execution
260 * problems.
261 */
262void
263key_regeneration_alarm(int sig)
264{
265 int save_errno = errno;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000266
Damien Miller95def091999-11-25 00:26:21 +1100267 /* Check if we should generate a new key. */
268 if (key_used) {
269 /* This should really be done in the background. */
270 log("Generating new %d bit RSA key.", options.server_key_bits);
271
272 if (sensitive_data.private_key != NULL)
273 RSA_free(sensitive_data.private_key);
274 sensitive_data.private_key = RSA_new();
275
276 if (public_key != NULL)
277 RSA_free(public_key);
278 public_key = RSA_new();
279
280 rsa_generate_key(sensitive_data.private_key, public_key,
281 options.server_key_bits);
282 arc4random_stir();
283 key_used = 0;
284 log("RSA key generation complete.");
285 }
286 /* Reschedule the alarm. */
287 signal(SIGALRM, key_regeneration_alarm);
288 alarm(options.key_regeneration_time);
289 errno = save_errno;
290}
291
292/*
293 * Main program for the daemon.
294 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000295int
296main(int ac, char **av)
297{
Damien Miller95def091999-11-25 00:26:21 +1100298 extern char *optarg;
299 extern int optind;
Damien Miller34132e52000-01-14 15:45:46 +1100300 int opt, sock_in = 0, sock_out = 0, newsock, i, fdsetsz, pid, on = 1;
301 socklen_t fromlen;
Damien Miller95def091999-11-25 00:26:21 +1100302 int remote_major, remote_minor;
303 int silentrsa = 0;
Damien Miller34132e52000-01-14 15:45:46 +1100304 fd_set *fdset;
305 struct sockaddr_storage from;
Damien Miller95def091999-11-25 00:26:21 +1100306 char buf[100]; /* Must not be larger than remote_version. */
307 char remote_version[100]; /* Must be at least as big as buf. */
308 const char *remote_ip;
309 int remote_port;
310 char *comment;
311 FILE *f;
312 struct linger linger;
Damien Miller34132e52000-01-14 15:45:46 +1100313 struct addrinfo *ai;
314 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
315 int listen_sock, maxfd;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000316
Damien Miller95def091999-11-25 00:26:21 +1100317 /* Save argv[0]. */
318 saved_argv = av;
319 if (strchr(av[0], '/'))
320 av0 = strrchr(av[0], '/') + 1;
321 else
322 av0 = av[0];
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000323
Damien Miller95def091999-11-25 00:26:21 +1100324 /* Initialize configuration options to their default values. */
325 initialize_server_options(&options);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000326
Damien Miller95def091999-11-25 00:26:21 +1100327 /* Parse command-line arguments. */
Damien Miller34132e52000-01-14 15:45:46 +1100328 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ46")) != EOF) {
Damien Miller95def091999-11-25 00:26:21 +1100329 switch (opt) {
Damien Miller34132e52000-01-14 15:45:46 +1100330 case '4':
331 IPv4or6 = AF_INET;
332 break;
333 case '6':
334 IPv4or6 = AF_INET6;
335 break;
Damien Miller95def091999-11-25 00:26:21 +1100336 case 'f':
337 config_file_name = optarg;
338 break;
339 case 'd':
340 debug_flag = 1;
341 options.log_level = SYSLOG_LEVEL_DEBUG;
342 break;
343 case 'i':
344 inetd_flag = 1;
345 break;
346 case 'Q':
347 silentrsa = 1;
348 break;
349 case 'q':
350 options.log_level = SYSLOG_LEVEL_QUIET;
351 break;
352 case 'b':
353 options.server_key_bits = atoi(optarg);
354 break;
355 case 'p':
Damien Miller34132e52000-01-14 15:45:46 +1100356 options.ports_from_cmdline = 1;
357 if (options.num_ports >= MAX_PORTS)
358 fatal("too many ports.\n");
359 options.ports[options.num_ports++] = atoi(optarg);
Damien Miller95def091999-11-25 00:26:21 +1100360 break;
361 case 'g':
362 options.login_grace_time = atoi(optarg);
363 break;
364 case 'k':
365 options.key_regeneration_time = atoi(optarg);
366 break;
367 case 'h':
368 options.host_key_file = optarg;
369 break;
370 case 'V':
371 client_version_string = optarg;
372 /* only makes sense with inetd_flag, i.e. no listen() */
373 inetd_flag = 1;
374 break;
375 case '?':
376 default:
377 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
Damien Millerd00d1611999-12-29 10:17:09 +1100378#ifdef RSAREF
379 fprintf(stderr, "Compiled with RSAref.\n");
380#endif
Damien Miller95def091999-11-25 00:26:21 +1100381 fprintf(stderr, "Usage: %s [options]\n", av0);
382 fprintf(stderr, "Options:\n");
Damien Miller5428f641999-11-25 11:54:57 +1100383 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE);
Damien Miller95def091999-11-25 00:26:21 +1100384 fprintf(stderr, " -d Debugging mode\n");
385 fprintf(stderr, " -i Started from inetd\n");
386 fprintf(stderr, " -q Quiet (no logging)\n");
387 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
388 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
389 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
390 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
391 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
Damien Miller34132e52000-01-14 15:45:46 +1100392 HOST_KEY_FILE);
393 fprintf(stderr, " -4 Use IPv4 only\n");
394 fprintf(stderr, " -6 Use IPv6 only\n");
Damien Miller95def091999-11-25 00:26:21 +1100395 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000396 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000397 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000398
Damien Miller34132e52000-01-14 15:45:46 +1100399 /*
400 * Force logging to stderr until we have loaded the private host
401 * key (unless started from inetd)
402 */
403 log_init(av0,
404 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
405 options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
406 !inetd_flag);
407
Damien Miller95def091999-11-25 00:26:21 +1100408 /* check if RSA support exists */
409 if (rsa_alive() == 0) {
410 if (silentrsa == 0)
411 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
412 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
413 exit(1);
414 }
415 /* Read server configuration options from the configuration file. */
416 read_server_config(&options, config_file_name);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000417
Damien Miller95def091999-11-25 00:26:21 +1100418 /* Fill in default values for those options not explicitly set. */
419 fill_default_server_options(&options);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000420
Damien Miller95def091999-11-25 00:26:21 +1100421 /* Check certain values for sanity. */
422 if (options.server_key_bits < 512 ||
423 options.server_key_bits > 32768) {
424 fprintf(stderr, "Bad server key size.\n");
425 exit(1);
426 }
Damien Miller95def091999-11-25 00:26:21 +1100427 /* Check that there are no remaining arguments. */
428 if (optind < ac) {
429 fprintf(stderr, "Extra argument %s.\n", av[optind]);
430 exit(1);
431 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000432
Damien Miller95def091999-11-25 00:26:21 +1100433 debug("sshd version %.100s", SSH_VERSION);
Damien Miller2ccf6611999-11-15 15:25:10 +1100434
Damien Miller95def091999-11-25 00:26:21 +1100435 sensitive_data.host_key = RSA_new();
436 errno = 0;
437 /* Load the host key. It must have empty passphrase. */
438 if (!load_private_key(options.host_key_file, "",
439 sensitive_data.host_key, &comment)) {
440 error("Could not load host key: %.200s: %.100s",
441 options.host_key_file, strerror(errno));
442 exit(1);
443 }
444 xfree(comment);
445
446 /* Initialize the log (it is reinitialized below in case we
447 forked). */
448 if (debug_flag && !inetd_flag)
449 log_stderr = 1;
450 log_init(av0, options.log_level, options.log_facility, log_stderr);
451
452 /* If not in debugging mode, and not started from inetd,
453 disconnect from the controlling terminal, and fork. The
454 original process exits. */
455 if (!debug_flag && !inetd_flag) {
456#ifdef TIOCNOTTY
457 int fd;
458#endif /* TIOCNOTTY */
459 if (daemon(0, 0) < 0)
460 fatal("daemon() failed: %.200s", strerror(errno));
461
462 /* Disconnect from the controlling tty. */
463#ifdef TIOCNOTTY
464 fd = open("/dev/tty", O_RDWR | O_NOCTTY);
465 if (fd >= 0) {
466 (void) ioctl(fd, TIOCNOTTY, NULL);
467 close(fd);
468 }
469#endif /* TIOCNOTTY */
470 }
471 /* Reinitialize the log (because of the fork above). */
472 log_init(av0, options.log_level, options.log_facility, log_stderr);
473
474 /* Check that server and host key lengths differ sufficiently.
475 This is necessary to make double encryption work with rsaref.
476 Oh, I hate software patents. I dont know if this can go? Niels */
477 if (options.server_key_bits >
478 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
479 options.server_key_bits <
480 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
481 options.server_key_bits =
482 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
483 debug("Forcing server key to %d bits to make it differ from host key.",
484 options.server_key_bits);
485 }
486 /* Do not display messages to stdout in RSA code. */
487 rsa_set_verbose(0);
488
489 /* Initialize the random number generator. */
490 arc4random_stir();
491
492 /* Chdir to the root directory so that the current disk can be
493 unmounted if desired. */
494 chdir("/");
495
496 /* Close connection cleanly after attack. */
497 cipher_attack_detected = packet_disconnect;
498
499 /* Start listening for a socket, unless started from inetd. */
500 if (inetd_flag) {
501 int s1, s2;
502 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
503 s2 = dup(s1);
504 sock_in = dup(0);
505 sock_out = dup(1);
506 /* We intentionally do not close the descriptors 0, 1, and 2
507 as our code for setting the descriptors won\'t work
508 if ttyfd happens to be one of those. */
509 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
510
511 public_key = RSA_new();
512 sensitive_data.private_key = RSA_new();
513
514 log("Generating %d bit RSA key.", options.server_key_bits);
515 rsa_generate_key(sensitive_data.private_key, public_key,
516 options.server_key_bits);
517 arc4random_stir();
518 log("RSA key generation complete.");
519 } else {
Damien Miller34132e52000-01-14 15:45:46 +1100520 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
521 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
522 continue;
523 if (num_listen_socks >= MAX_LISTEN_SOCKS)
524 fatal("Too many listen sockets. "
525 "Enlarge MAX_LISTEN_SOCKS");
526 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
527 ntop, sizeof(ntop), strport, sizeof(strport),
528 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
529 error("getnameinfo failed");
530 continue;
531 }
532 /* Create socket for listening. */
533 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
534 if (listen_sock < 0) {
535 /* kernel may not support ipv6 */
536 verbose("socket: %.100s", strerror(errno));
537 continue;
538 }
539 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
540 error("listen_sock O_NONBLOCK: %s", strerror(errno));
541 close(listen_sock);
542 continue;
543 }
544 /*
545 * Set socket options. We try to make the port
546 * reusable and have it close as fast as possible
547 * without waiting in unnecessary wait states on
548 * close.
549 */
550 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
551 (void *) &on, sizeof(on));
552 linger.l_onoff = 1;
553 linger.l_linger = 5;
554 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
555 (void *) &linger, sizeof(linger));
Damien Miller95def091999-11-25 00:26:21 +1100556
Damien Miller34132e52000-01-14 15:45:46 +1100557 debug("Bind to port %s on %s.", strport, ntop);
Damien Miller95def091999-11-25 00:26:21 +1100558
Damien Miller34132e52000-01-14 15:45:46 +1100559 /* Bind the socket to the desired port. */
560 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
561 error("Bind to port %s on %s failed: %.200s.",
562 strport, ntop, strerror(errno));
563 close(listen_sock);
564 continue;
565 }
566 listen_socks[num_listen_socks] = listen_sock;
567 num_listen_socks++;
Damien Miller95def091999-11-25 00:26:21 +1100568
Damien Miller34132e52000-01-14 15:45:46 +1100569 /* Start listening on the port. */
570 log("Server listening on %s port %s.", ntop, strport);
571 if (listen(listen_sock, 5) < 0)
572 fatal("listen: %.100s", strerror(errno));
573
Damien Miller95def091999-11-25 00:26:21 +1100574 }
Damien Miller34132e52000-01-14 15:45:46 +1100575 freeaddrinfo(options.listen_addrs);
576
577 if (!num_listen_socks)
578 fatal("Cannot bind any address.");
579
Damien Miller95def091999-11-25 00:26:21 +1100580 if (!debug_flag) {
Damien Miller5428f641999-11-25 11:54:57 +1100581 /*
582 * Record our pid in /etc/sshd_pid to make it easier
583 * to kill the correct sshd. We don\'t want to do
584 * this before the bind above because the bind will
585 * fail if there already is a daemon, and this will
586 * overwrite any old pid in the file.
587 */
Damien Miller95def091999-11-25 00:26:21 +1100588 f = fopen(SSH_DAEMON_PID_FILE, "w");
589 if (f) {
590 fprintf(f, "%u\n", (unsigned int) getpid());
591 fclose(f);
592 }
593 }
594
Damien Miller95def091999-11-25 00:26:21 +1100595 public_key = RSA_new();
596 sensitive_data.private_key = RSA_new();
597
598 log("Generating %d bit RSA key.", options.server_key_bits);
599 rsa_generate_key(sensitive_data.private_key, public_key,
600 options.server_key_bits);
601 arc4random_stir();
602 log("RSA key generation complete.");
603
604 /* Schedule server key regeneration alarm. */
605 signal(SIGALRM, key_regeneration_alarm);
606 alarm(options.key_regeneration_time);
607
608 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
609 signal(SIGHUP, sighup_handler);
610 signal(SIGTERM, sigterm_handler);
611 signal(SIGQUIT, sigterm_handler);
612
613 /* Arrange SIGCHLD to be caught. */
614 signal(SIGCHLD, main_sigchld_handler);
615
Damien Miller34132e52000-01-14 15:45:46 +1100616 /* setup fd set for listen */
617 maxfd = 0;
618 for (i = 0; i < num_listen_socks; i++)
619 if (listen_socks[i] > maxfd)
620 maxfd = listen_socks[i];
621 fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
622 fdset = (fd_set *)xmalloc(fdsetsz);
623
Damien Miller5428f641999-11-25 11:54:57 +1100624 /*
625 * Stay listening for connections until the system crashes or
626 * the daemon is killed with a signal.
627 */
Damien Miller95def091999-11-25 00:26:21 +1100628 for (;;) {
629 if (received_sighup)
630 sighup_restart();
Damien Miller34132e52000-01-14 15:45:46 +1100631 /* Wait in select until there is a connection. */
632 memset(fdset, 0, fdsetsz);
633 for (i = 0; i < num_listen_socks; i++)
634 FD_SET(listen_socks[i], fdset);
635 if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) {
636 if (errno != EINTR)
637 error("select: %.100s", strerror(errno));
Damien Miller50945fa1999-12-09 10:31:37 +1100638 continue;
Damien Miller34132e52000-01-14 15:45:46 +1100639 }
640 for (i = 0; i < num_listen_socks; i++) {
641 if (!FD_ISSET(listen_socks[i], fdset))
Damien Miller95def091999-11-25 00:26:21 +1100642 continue;
Damien Miller34132e52000-01-14 15:45:46 +1100643 fromlen = sizeof(from);
644 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
645 &fromlen);
646 if (newsock < 0) {
647 if (errno != EINTR && errno != EWOULDBLOCK)
648 error("accept: %.100s", strerror(errno));
649 continue;
650 }
651 if (fcntl(newsock, F_SETFL, 0) < 0) {
652 error("newsock del O_NONBLOCK: %s", strerror(errno));
Damien Miller95def091999-11-25 00:26:21 +1100653 continue;
654 }
Damien Miller5428f641999-11-25 11:54:57 +1100655 /*
656 * Got connection. Fork a child to handle it, unless
657 * we are in debugging mode.
658 */
Damien Miller95def091999-11-25 00:26:21 +1100659 if (debug_flag) {
Damien Miller5428f641999-11-25 11:54:57 +1100660 /*
661 * In debugging mode. Close the listening
662 * socket, and start processing the
663 * connection without forking.
664 */
Damien Miller95def091999-11-25 00:26:21 +1100665 debug("Server will not fork when running in debugging mode.");
Damien Miller34132e52000-01-14 15:45:46 +1100666 close_listen_socks();
Damien Miller95def091999-11-25 00:26:21 +1100667 sock_in = newsock;
668 sock_out = newsock;
669 pid = getpid();
670 break;
671 } else {
Damien Miller5428f641999-11-25 11:54:57 +1100672 /*
673 * Normal production daemon. Fork, and have
674 * the child process the connection. The
675 * parent continues listening.
676 */
Damien Miller95def091999-11-25 00:26:21 +1100677 if ((pid = fork()) == 0) {
Damien Miller5428f641999-11-25 11:54:57 +1100678 /*
679 * Child. Close the listening socket, and start using the
680 * accepted socket. Reinitialize logging (since our pid has
681 * changed). We break out of the loop to handle the connection.
682 */
Damien Miller34132e52000-01-14 15:45:46 +1100683 close_listen_socks();
Damien Miller95def091999-11-25 00:26:21 +1100684 sock_in = newsock;
685 sock_out = newsock;
686 log_init(av0, options.log_level, options.log_facility, log_stderr);
687 break;
688 }
689 }
690
691 /* Parent. Stay in the loop. */
692 if (pid < 0)
693 error("fork: %.100s", strerror(errno));
694 else
695 debug("Forked child %d.", pid);
696
697 /* Mark that the key has been used (it was "given" to the child). */
698 key_used = 1;
699
700 arc4random_stir();
701
702 /* Close the new socket (the child is now taking care of it). */
703 close(newsock);
Damien Miller34132e52000-01-14 15:45:46 +1100704 } /* for (i = 0; i < num_listen_socks; i++) */
705 /* child process check (or debug mode) */
706 if (num_listen_socks < 0)
707 break;
Damien Miller95def091999-11-25 00:26:21 +1100708 }
709 }
710
711 /* This is the child processing a new connection. */
712
Damien Miller5428f641999-11-25 11:54:57 +1100713 /*
714 * Disable the key regeneration alarm. We will not regenerate the
715 * key since we are no longer in a position to give it to anyone. We
716 * will not restart on SIGHUP since it no longer makes sense.
717 */
Damien Miller95def091999-11-25 00:26:21 +1100718 alarm(0);
719 signal(SIGALRM, SIG_DFL);
720 signal(SIGHUP, SIG_DFL);
721 signal(SIGTERM, SIG_DFL);
722 signal(SIGQUIT, SIG_DFL);
723 signal(SIGCHLD, SIG_DFL);
724
Damien Miller5428f641999-11-25 11:54:57 +1100725 /*
726 * Set socket options for the connection. We want the socket to
727 * close as fast as possible without waiting for anything. If the
728 * connection is not a socket, these will do nothing.
729 */
730 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
Damien Miller95def091999-11-25 00:26:21 +1100731 linger.l_onoff = 1;
732 linger.l_linger = 5;
733 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
734
Damien Miller5428f641999-11-25 11:54:57 +1100735 /*
736 * Register our connection. This turns encryption off because we do
737 * not have a key.
738 */
Damien Miller95def091999-11-25 00:26:21 +1100739 packet_set_connection(sock_in, sock_out);
740
741 remote_port = get_remote_port();
742 remote_ip = get_remote_ipaddr();
743
744 /* Check whether logins are denied from this host. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000745#ifdef LIBWRAP
Damien Miller34132e52000-01-14 15:45:46 +1100746 /* XXX LIBWRAP noes not know about IPv6 */
Damien Miller95def091999-11-25 00:26:21 +1100747 {
748 struct request_info req;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000749
Damien Miller95def091999-11-25 00:26:21 +1100750 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
751 fromhost(&req);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000752
Damien Miller95def091999-11-25 00:26:21 +1100753 if (!hosts_access(&req)) {
754 close(sock_in);
755 close(sock_out);
756 refuse(&req);
757 }
Damien Miller34132e52000-01-14 15:45:46 +1100758/*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
Damien Miller95def091999-11-25 00:26:21 +1100759 }
Damien Miller34132e52000-01-14 15:45:46 +1100760#endif /* LIBWRAP */
Damien Miller95def091999-11-25 00:26:21 +1100761 /* Log the connection. */
762 verbose("Connection from %.500s port %d", remote_ip, remote_port);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000763
Damien Miller5428f641999-11-25 11:54:57 +1100764 /*
765 * We don\'t want to listen forever unless the other side
766 * successfully authenticates itself. So we set up an alarm which is
767 * cleared after successful authentication. A limit of zero
768 * indicates no limit. Note that we don\'t set the alarm in debugging
769 * mode; it is just annoying to have the server exit just when you
770 * are about to discover the bug.
771 */
Damien Miller95def091999-11-25 00:26:21 +1100772 signal(SIGALRM, grace_alarm_handler);
773 if (!debug_flag)
774 alarm(options.login_grace_time);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000775
Damien Miller95def091999-11-25 00:26:21 +1100776 if (client_version_string != NULL) {
777 /* we are exec'ed by sshd2, so skip exchange of protocol version */
778 strlcpy(buf, client_version_string, sizeof(buf));
779 } else {
780 /* Send our protocol version identification. */
781 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
782 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
Damien Miller037a0dc1999-12-07 15:38:31 +1100783 if (atomicio(write, sock_out, buf, strlen(buf)) != strlen(buf))
Damien Miller34132e52000-01-14 15:45:46 +1100784 fatal("Could not write ident string to %s.", remote_ip);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000785
Damien Miller95def091999-11-25 00:26:21 +1100786 /* Read other side\'s version identification. */
787 for (i = 0; i < sizeof(buf) - 1; i++) {
788 if (read(sock_in, &buf[i], 1) != 1)
Damien Miller34132e52000-01-14 15:45:46 +1100789 fatal("Did not receive ident string from %s.", remote_ip);
Damien Miller95def091999-11-25 00:26:21 +1100790 if (buf[i] == '\r') {
791 buf[i] = '\n';
792 buf[i + 1] = 0;
793 break;
794 }
795 if (buf[i] == '\n') {
796 /* buf[i] == '\n' */
797 buf[i + 1] = 0;
798 break;
799 }
800 }
801 buf[sizeof(buf) - 1] = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000802 }
Damien Miller95def091999-11-25 00:26:21 +1100803
Damien Miller5428f641999-11-25 11:54:57 +1100804 /*
805 * Check that the versions match. In future this might accept
806 * several versions and set appropriate flags to handle them.
807 */
Damien Miller95def091999-11-25 00:26:21 +1100808 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
Damien Miller037a0dc1999-12-07 15:38:31 +1100809 remote_version) != 3) {
810 char *s = "Protocol mismatch.\n";
811
812 (void) atomicio(write, sock_out, s, strlen(s));
Damien Miller95def091999-11-25 00:26:21 +1100813 close(sock_in);
814 close(sock_out);
815 fatal("Bad protocol version identification '%.100s' from %s",
Damien Miller34132e52000-01-14 15:45:46 +1100816 buf, remote_ip);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000817 }
Damien Miller95def091999-11-25 00:26:21 +1100818 debug("Client protocol version %d.%d; client software version %.100s",
819 remote_major, remote_minor, remote_version);
820 if (remote_major != PROTOCOL_MAJOR) {
Damien Miller037a0dc1999-12-07 15:38:31 +1100821 char *s = "Protocol major versions differ.\n";
822
823 (void) atomicio(write, sock_out, s, strlen(s));
Damien Miller95def091999-11-25 00:26:21 +1100824 close(sock_in);
825 close(sock_out);
826 fatal("Protocol major versions differ for %s: %d vs. %d",
Damien Miller34132e52000-01-14 15:45:46 +1100827 remote_ip, PROTOCOL_MAJOR, remote_major);
Damien Miller95def091999-11-25 00:26:21 +1100828 }
829 /* Check that the client has sufficiently high software version. */
830 if (remote_major == 1 && remote_minor < 3)
831 packet_disconnect("Your ssh version is too old and is no longer supported. Please install a newer version.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000832
Damien Miller95def091999-11-25 00:26:21 +1100833 if (remote_major == 1 && remote_minor == 3) {
834 enable_compat13();
835 if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
836 debug("Agent forwarding disabled, remote version is not compatible.");
837 no_agent_forwarding_flag = 1;
838 }
839 }
Damien Miller5428f641999-11-25 11:54:57 +1100840 /*
841 * Check that the connection comes from a privileged port. Rhosts-
842 * and Rhosts-RSA-Authentication only make sense from priviledged
843 * programs. Of course, if the intruder has root access on his local
844 * machine, he can connect from any port. So do not use these
845 * authentication methods from machines that you do not trust.
846 */
Damien Miller95def091999-11-25 00:26:21 +1100847 if (remote_port >= IPPORT_RESERVED ||
848 remote_port < IPPORT_RESERVED / 2) {
849 options.rhosts_authentication = 0;
850 options.rhosts_rsa_authentication = 0;
851 }
Damien Miller34132e52000-01-14 15:45:46 +1100852#ifdef KRB4
853 if (!packet_connection_is_ipv4() &&
854 options.kerberos_authentication) {
855 debug("Kerberos Authentication disabled, only available for IPv4.");
856 options.kerberos_authentication = 0;
857 }
858#endif /* KRB4 */
859
Damien Miller95def091999-11-25 00:26:21 +1100860 packet_set_nonblocking();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000861
Damien Miller95def091999-11-25 00:26:21 +1100862 /* Handle the connection. */
863 do_connection();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000864
865#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +1100866 /* Cleanup user's ticket cache file. */
867 if (options.kerberos_ticket_cleanup)
868 (void) dest_tkt();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000869#endif /* KRB4 */
870
Damien Miller95def091999-11-25 00:26:21 +1100871 /* Cleanup user's local Xauthority file. */
872 if (xauthfile)
873 unlink(xauthfile);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000874
Damien Miller95def091999-11-25 00:26:21 +1100875 /* The connection has been terminated. */
876 verbose("Closing connection to %.100s", remote_ip);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000877
Damien Millerbeb4ba51999-12-28 15:09:35 +1100878#ifdef USE_PAM
Damien Millere72b7af1999-12-30 15:08:44 +1100879 finish_pam();
Damien Millerbeb4ba51999-12-28 15:09:35 +1100880#endif /* USE_PAM */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000881
Damien Miller95def091999-11-25 00:26:21 +1100882 packet_close();
883 exit(0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000884}
885
Damien Miller95def091999-11-25 00:26:21 +1100886/*
887 * Process an incoming connection. Protocol version identifiers have already
888 * been exchanged. This sends server key and performs the key exchange.
889 * Server and host keys will no longer be needed after this functions.
890 */
Damien Miller2ccf6611999-11-15 15:25:10 +1100891void
892do_connection()
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000893{
Damien Miller95def091999-11-25 00:26:21 +1100894 int i, len;
895 BIGNUM *session_key_int;
896 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
897 unsigned char check_bytes[8];
898 char *user;
899 unsigned int cipher_type, auth_mask, protocol_flags;
Damien Millera34a28b1999-12-14 10:47:15 +1100900 int plen, slen, ulen;
Damien Miller95def091999-11-25 00:26:21 +1100901 u_int32_t rand = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000902
Damien Miller5428f641999-11-25 11:54:57 +1100903 /*
904 * Generate check bytes that the client must send back in the user
905 * packet in order for it to be accepted; this is used to defy ip
906 * spoofing attacks. Note that this only works against somebody
907 * doing IP spoofing from a remote machine; any machine on the local
908 * network can still see outgoing packets and catch the random
909 * cookie. This only affects rhosts authentication, and this is one
910 * of the reasons why it is inherently insecure.
911 */
Damien Miller95def091999-11-25 00:26:21 +1100912 for (i = 0; i < 8; i++) {
913 if (i % 4 == 0)
914 rand = arc4random();
915 check_bytes[i] = rand & 0xff;
916 rand >>= 8;
917 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000918
Damien Miller5428f641999-11-25 11:54:57 +1100919 /*
920 * Send our public key. We include in the packet 64 bits of random
921 * data that must be matched in the reply in order to prevent IP
922 * spoofing.
923 */
Damien Miller95def091999-11-25 00:26:21 +1100924 packet_start(SSH_SMSG_PUBLIC_KEY);
925 for (i = 0; i < 8; i++)
926 packet_put_char(check_bytes[i]);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000927
Damien Miller95def091999-11-25 00:26:21 +1100928 /* Store our public server RSA key. */
929 packet_put_int(BN_num_bits(public_key->n));
930 packet_put_bignum(public_key->e);
931 packet_put_bignum(public_key->n);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000932
Damien Miller95def091999-11-25 00:26:21 +1100933 /* Store our public host RSA key. */
934 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
935 packet_put_bignum(sensitive_data.host_key->e);
936 packet_put_bignum(sensitive_data.host_key->n);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000937
Damien Miller95def091999-11-25 00:26:21 +1100938 /* Put protocol flags. */
939 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000940
Damien Miller95def091999-11-25 00:26:21 +1100941 /* Declare which ciphers we support. */
942 packet_put_int(cipher_mask());
943
944 /* Declare supported authentication types. */
945 auth_mask = 0;
946 if (options.rhosts_authentication)
947 auth_mask |= 1 << SSH_AUTH_RHOSTS;
948 if (options.rhosts_rsa_authentication)
949 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
950 if (options.rsa_authentication)
951 auth_mask |= 1 << SSH_AUTH_RSA;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000952#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +1100953 if (options.kerberos_authentication)
954 auth_mask |= 1 << SSH_AUTH_KERBEROS;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000955#endif
956#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +1100957 if (options.kerberos_tgt_passing)
958 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
959 if (options.afs_token_passing)
960 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000961#endif
Damien Miller95def091999-11-25 00:26:21 +1100962#ifdef SKEY
963 if (options.skey_authentication == 1)
964 auth_mask |= 1 << SSH_AUTH_TIS;
965#endif
966 if (options.password_authentication)
967 auth_mask |= 1 << SSH_AUTH_PASSWORD;
968 packet_put_int(auth_mask);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000969
Damien Miller95def091999-11-25 00:26:21 +1100970 /* Send the packet and wait for it to be sent. */
971 packet_send();
972 packet_write_wait();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000973
Damien Miller95def091999-11-25 00:26:21 +1100974 debug("Sent %d bit public key and %d bit host key.",
975 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000976
Damien Miller95def091999-11-25 00:26:21 +1100977 /* Read clients reply (cipher type and session key). */
978 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000979
Damien Miller50945fa1999-12-09 10:31:37 +1100980 /* Get cipher type and check whether we accept this. */
Damien Miller95def091999-11-25 00:26:21 +1100981 cipher_type = packet_get_char();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000982
Damien Miller50945fa1999-12-09 10:31:37 +1100983 if (!(cipher_mask() & (1 << cipher_type)))
984 packet_disconnect("Warning: client selects unsupported cipher.");
985
Damien Miller95def091999-11-25 00:26:21 +1100986 /* Get check bytes from the packet. These must match those we
987 sent earlier with the public key packet. */
988 for (i = 0; i < 8; i++)
989 if (check_bytes[i] != packet_get_char())
990 packet_disconnect("IP Spoofing check bytes do not match.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000991
Damien Miller95def091999-11-25 00:26:21 +1100992 debug("Encryption type: %.200s", cipher_name(cipher_type));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000993
Damien Miller95def091999-11-25 00:26:21 +1100994 /* Get the encrypted integer. */
995 session_key_int = BN_new();
996 packet_get_bignum(session_key_int, &slen);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000997
Damien Miller95def091999-11-25 00:26:21 +1100998 protocol_flags = packet_get_int();
999 packet_set_protocol_flags(protocol_flags);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001000
Damien Miller95def091999-11-25 00:26:21 +11001001 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001002
Damien Miller5428f641999-11-25 11:54:57 +11001003 /*
1004 * Decrypt it using our private server key and private host key (key
1005 * with larger modulus first).
1006 */
Damien Miller95def091999-11-25 00:26:21 +11001007 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1008 /* Private key has bigger modulus. */
1009 if (BN_num_bits(sensitive_data.private_key->n) <
1010 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1011 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1012 get_remote_ipaddr(),
1013 BN_num_bits(sensitive_data.private_key->n),
1014 BN_num_bits(sensitive_data.host_key->n),
1015 SSH_KEY_BITS_RESERVED);
1016 }
1017 rsa_private_decrypt(session_key_int, session_key_int,
1018 sensitive_data.private_key);
1019 rsa_private_decrypt(session_key_int, session_key_int,
1020 sensitive_data.host_key);
1021 } else {
1022 /* Host key has bigger modulus (or they are equal). */
1023 if (BN_num_bits(sensitive_data.host_key->n) <
1024 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1025 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1026 get_remote_ipaddr(),
1027 BN_num_bits(sensitive_data.host_key->n),
1028 BN_num_bits(sensitive_data.private_key->n),
1029 SSH_KEY_BITS_RESERVED);
1030 }
1031 rsa_private_decrypt(session_key_int, session_key_int,
1032 sensitive_data.host_key);
1033 rsa_private_decrypt(session_key_int, session_key_int,
1034 sensitive_data.private_key);
1035 }
Damien Miller356a0b01999-11-08 15:30:59 +11001036
Damien Miller95def091999-11-25 00:26:21 +11001037 compute_session_id(session_id, check_bytes,
1038 sensitive_data.host_key->n,
1039 sensitive_data.private_key->n);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001040
Damien Miller5428f641999-11-25 11:54:57 +11001041 /*
1042 * Extract session key from the decrypted integer. The key is in the
1043 * least significant 256 bits of the integer; the first byte of the
1044 * key is in the highest bits.
1045 */
Damien Miller95def091999-11-25 00:26:21 +11001046 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1047 len = BN_num_bytes(session_key_int);
1048 if (len < 0 || len > sizeof(session_key))
1049 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1050 get_remote_ipaddr(),
1051 len, sizeof(session_key));
1052 memset(session_key, 0, sizeof(session_key));
1053 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001054
Damien Miller95def091999-11-25 00:26:21 +11001055 /* Xor the first 16 bytes of the session key with the session id. */
1056 for (i = 0; i < 16; i++)
1057 session_key[i] ^= session_id[i];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001058
Damien Miller95def091999-11-25 00:26:21 +11001059 /* Destroy the decrypted integer. It is no longer needed. */
1060 BN_clear_free(session_key_int);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001061
Damien Miller95def091999-11-25 00:26:21 +11001062 /* Set the session key. From this on all communications will be encrypted. */
1063 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001064
Damien Miller95def091999-11-25 00:26:21 +11001065 /* Destroy our copy of the session key. It is no longer needed. */
1066 memset(session_key, 0, sizeof(session_key));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001067
Damien Miller95def091999-11-25 00:26:21 +11001068 debug("Received session key; encryption turned on.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001069
Damien Miller95def091999-11-25 00:26:21 +11001070 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1071 packet_start(SSH_SMSG_SUCCESS);
1072 packet_send();
1073 packet_write_wait();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001074
Damien Miller95def091999-11-25 00:26:21 +11001075 /* Get the name of the user that we wish to log in as. */
1076 packet_read_expect(&plen, SSH_CMSG_USER);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001077
Damien Miller95def091999-11-25 00:26:21 +11001078 /* Get the user name. */
Damien Millera34a28b1999-12-14 10:47:15 +11001079 user = packet_get_string(&ulen);
1080 packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
Damien Miller95def091999-11-25 00:26:21 +11001081
1082 /* Destroy the private and public keys. They will no longer be needed. */
1083 RSA_free(public_key);
1084 RSA_free(sensitive_data.private_key);
1085 RSA_free(sensitive_data.host_key);
1086
1087 setproctitle("%s", user);
1088 /* Do the authentication. */
1089 do_authentication(user);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001090}
1091
Damien Miller95def091999-11-25 00:26:21 +11001092/*
1093 * Check if the user is allowed to log in via ssh. If user is listed in
1094 * DenyUsers or user's primary group is listed in DenyGroups, false will
1095 * be returned. If AllowUsers isn't empty and user isn't listed there, or
1096 * if AllowGroups isn't empty and user isn't listed there, false will be
1097 * returned. Otherwise true is returned.
1098 * XXX This function should also check if user has a valid shell
1099 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001100static int
Damien Miller95def091999-11-25 00:26:21 +11001101allowed_user(struct passwd * pw)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001102{
Damien Miller95def091999-11-25 00:26:21 +11001103 struct group *grp;
1104 int i;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001105
Damien Miller95def091999-11-25 00:26:21 +11001106 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1107 if (!pw)
1108 return 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001109
Damien Miller95def091999-11-25 00:26:21 +11001110 /* XXX Should check for valid login shell */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001111
Damien Miller95def091999-11-25 00:26:21 +11001112 /* Return false if user is listed in DenyUsers */
1113 if (options.num_deny_users > 0) {
1114 if (!pw->pw_name)
1115 return 0;
1116 for (i = 0; i < options.num_deny_users; i++)
1117 if (match_pattern(pw->pw_name, options.deny_users[i]))
1118 return 0;
1119 }
Damien Miller5428f641999-11-25 11:54:57 +11001120 /* Return false if AllowUsers isn't empty and user isn't listed there */
Damien Miller95def091999-11-25 00:26:21 +11001121 if (options.num_allow_users > 0) {
1122 if (!pw->pw_name)
1123 return 0;
1124 for (i = 0; i < options.num_allow_users; i++)
1125 if (match_pattern(pw->pw_name, options.allow_users[i]))
1126 break;
1127 /* i < options.num_allow_users iff we break for loop */
1128 if (i >= options.num_allow_users)
1129 return 0;
1130 }
1131 /* Get the primary group name if we need it. Return false if it fails */
1132 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
1133 grp = getgrgid(pw->pw_gid);
1134 if (!grp)
1135 return 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001136
Damien Miller95def091999-11-25 00:26:21 +11001137 /* Return false if user's group is listed in DenyGroups */
1138 if (options.num_deny_groups > 0) {
1139 if (!grp->gr_name)
1140 return 0;
1141 for (i = 0; i < options.num_deny_groups; i++)
1142 if (match_pattern(grp->gr_name, options.deny_groups[i]))
1143 return 0;
1144 }
Damien Miller5428f641999-11-25 11:54:57 +11001145 /*
1146 * Return false if AllowGroups isn't empty and user's group
1147 * isn't listed there
1148 */
Damien Miller95def091999-11-25 00:26:21 +11001149 if (options.num_allow_groups > 0) {
1150 if (!grp->gr_name)
1151 return 0;
1152 for (i = 0; i < options.num_allow_groups; i++)
1153 if (match_pattern(grp->gr_name, options.allow_groups[i]))
1154 break;
1155 /* i < options.num_allow_groups iff we break for
1156 loop */
1157 if (i >= options.num_allow_groups)
1158 return 0;
1159 }
1160 }
1161 /* We found no reason not to let this user try to log on... */
1162 return 1;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001163}
1164
Damien Miller95def091999-11-25 00:26:21 +11001165/*
1166 * Performs authentication of an incoming connection. Session key has already
1167 * been exchanged and encryption is enabled. User is the user name to log
1168 * in as (received from the client).
1169 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001170void
Damien Miller2ccf6611999-11-15 15:25:10 +11001171do_authentication(char *user)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001172{
Damien Miller95def091999-11-25 00:26:21 +11001173 struct passwd *pw, pwcopy;
Damien Miller2ccf6611999-11-15 15:25:10 +11001174
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001175#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11001176 /* If machine has AFS, set process authentication group. */
1177 if (k_hasafs()) {
1178 k_setpag();
1179 k_unlog();
1180 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001181#endif /* AFS */
Damien Miller95def091999-11-25 00:26:21 +11001182
1183 /* Verify that the user is a valid user. */
1184 pw = getpwnam(user);
1185 if (!pw || !allowed_user(pw))
1186 do_fake_authloop(user);
1187
1188 /* Take a copy of the returned structure. */
1189 memset(&pwcopy, 0, sizeof(pwcopy));
1190 pwcopy.pw_name = xstrdup(pw->pw_name);
1191 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1192 pwcopy.pw_uid = pw->pw_uid;
1193 pwcopy.pw_gid = pw->pw_gid;
1194 pwcopy.pw_dir = xstrdup(pw->pw_dir);
1195 pwcopy.pw_shell = xstrdup(pw->pw_shell);
1196 pw = &pwcopy;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001197
Damien Millerbeb4ba51999-12-28 15:09:35 +11001198#ifdef USE_PAM
Damien Millere72b7af1999-12-30 15:08:44 +11001199 start_pam(pw);
Damien Miller06230761999-10-28 14:03:14 +10001200#endif
Damien Miller3d112ef1999-10-28 13:20:30 +10001201
Damien Miller5428f641999-11-25 11:54:57 +11001202 /*
1203 * If we are not running as root, the user must have the same uid as
1204 * the server.
1205 */
Damien Miller95def091999-11-25 00:26:21 +11001206 if (getuid() != 0 && pw->pw_uid != getuid())
1207 packet_disconnect("Cannot change user when server not running as root.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001208
Damien Miller95def091999-11-25 00:26:21 +11001209 debug("Attempting authentication for %.100s.", user);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001210
Damien Miller95def091999-11-25 00:26:21 +11001211 /* If the user has no password, accept authentication immediately. */
1212 if (options.password_authentication &&
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001213#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11001214 (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001215#endif /* KRB4 */
Damien Millerbeb4ba51999-12-28 15:09:35 +11001216#ifdef USE_PAM
Damien Millere72b7af1999-12-30 15:08:44 +11001217 auth_pam_password(pw, "")) {
Damien Millerbeb4ba51999-12-28 15:09:35 +11001218#else /* USE_PAM */
Damien Miller95def091999-11-25 00:26:21 +11001219 auth_password(pw, "")) {
Damien Millerbeb4ba51999-12-28 15:09:35 +11001220#endif /* USE_PAM */
Damien Miller95def091999-11-25 00:26:21 +11001221 /* Authentication with empty password succeeded. */
1222 log("Login for user %s from %.100s, accepted without authentication.",
1223 pw->pw_name, get_remote_ipaddr());
1224 } else {
1225 /* Loop until the user has been authenticated or the
1226 connection is closed, do_authloop() returns only if
1227 authentication is successfull */
1228 do_authloop(pw);
1229 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001230
Damien Miller95def091999-11-25 00:26:21 +11001231 /* Check if the user is logging in as root and root logins are disallowed. */
1232 if (pw->pw_uid == 0 && !options.permit_root_login) {
1233 if (forced_command)
1234 log("Root login accepted for forced command.");
1235 else
1236 packet_disconnect("ROOT LOGIN REFUSED FROM %.200s",
1237 get_canonical_hostname());
1238 }
1239 /* The user has been authenticated and accepted. */
1240 packet_start(SSH_SMSG_SUCCESS);
1241 packet_send();
1242 packet_write_wait();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001243
Damien Miller95def091999-11-25 00:26:21 +11001244 /* Perform session preparation. */
1245 do_authenticated(pw);
Damien Miller2ccf6611999-11-15 15:25:10 +11001246}
1247
Damien Miller95def091999-11-25 00:26:21 +11001248#define AUTH_FAIL_MAX 6
1249#define AUTH_FAIL_LOG (AUTH_FAIL_MAX/2)
1250#define AUTH_FAIL_MSG "Too many authentication failures for %.100s"
Damien Miller2ccf6611999-11-15 15:25:10 +11001251
Damien Miller95def091999-11-25 00:26:21 +11001252/*
1253 * read packets and try to authenticate local user *pw.
1254 * return if authentication is successfull
1255 */
Damien Miller2ccf6611999-11-15 15:25:10 +11001256void
Damien Miller95def091999-11-25 00:26:21 +11001257do_authloop(struct passwd * pw)
Damien Miller2ccf6611999-11-15 15:25:10 +11001258{
Damien Miller95def091999-11-25 00:26:21 +11001259 int attempt = 0;
1260 unsigned int bits;
1261 BIGNUM *client_host_key_e, *client_host_key_n;
1262 BIGNUM *n;
1263 char *client_user = NULL, *password = NULL;
1264 char user[1024];
1265 int plen, dlen, nlen, ulen, elen;
1266 int type = 0;
1267 void (*authlog) (const char *fmt,...) = verbose;
Damien Miller2ccf6611999-11-15 15:25:10 +11001268
Damien Miller95def091999-11-25 00:26:21 +11001269 /* Indicate that authentication is needed. */
1270 packet_start(SSH_SMSG_FAILURE);
1271 packet_send();
1272 packet_write_wait();
Damien Miller2ccf6611999-11-15 15:25:10 +11001273
Damien Miller95def091999-11-25 00:26:21 +11001274 for (attempt = 1;; attempt++) {
1275 int authenticated = 0;
1276 strlcpy(user, "", sizeof user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001277
Damien Miller95def091999-11-25 00:26:21 +11001278 /* Get a packet from the client. */
1279 type = packet_read(&plen);
1280
1281 /* Process the packet. */
1282 switch (type) {
Damien Miller2ccf6611999-11-15 15:25:10 +11001283#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11001284 case SSH_CMSG_HAVE_KERBEROS_TGT:
1285 if (!options.kerberos_tgt_passing) {
1286 /* packet_get_all(); */
1287 verbose("Kerberos tgt passing disabled.");
1288 break;
1289 } else {
1290 /* Accept Kerberos tgt. */
1291 char *tgt = packet_get_string(&dlen);
1292 packet_integrity_check(plen, 4 + dlen, type);
1293 if (!auth_kerberos_tgt(pw, tgt))
1294 verbose("Kerberos tgt REFUSED for %s", pw->pw_name);
1295 xfree(tgt);
1296 }
1297 continue;
1298
1299 case SSH_CMSG_HAVE_AFS_TOKEN:
1300 if (!options.afs_token_passing || !k_hasafs()) {
1301 /* packet_get_all(); */
1302 verbose("AFS token passing disabled.");
1303 break;
1304 } else {
1305 /* Accept AFS token. */
1306 char *token_string = packet_get_string(&dlen);
1307 packet_integrity_check(plen, 4 + dlen, type);
1308 if (!auth_afs_token(pw, token_string))
1309 verbose("AFS token REFUSED for %s", pw->pw_name);
1310 xfree(token_string);
1311 }
1312 continue;
Damien Miller2ccf6611999-11-15 15:25:10 +11001313#endif /* AFS */
Damien Miller2ccf6611999-11-15 15:25:10 +11001314#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11001315 case SSH_CMSG_AUTH_KERBEROS:
1316 if (!options.kerberos_authentication) {
1317 /* packet_get_all(); */
1318 verbose("Kerberos authentication disabled.");
1319 break;
1320 } else {
1321 /* Try Kerberos v4 authentication. */
1322 KTEXT_ST auth;
1323 char *tkt_user = NULL;
1324 char *kdata = packet_get_string((unsigned int *) &auth.length);
1325 packet_integrity_check(plen, 4 + auth.length, type);
Damien Miller2ccf6611999-11-15 15:25:10 +11001326
Damien Miller95def091999-11-25 00:26:21 +11001327 if (auth.length < MAX_KTXT_LEN)
1328 memcpy(auth.dat, kdata, auth.length);
1329 xfree(kdata);
1330
1331 authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
1332
1333 if (authenticated) {
1334 snprintf(user, sizeof user, " tktuser %s", tkt_user);
1335 xfree(tkt_user);
1336 }
1337 }
1338 break;
Damien Miller2ccf6611999-11-15 15:25:10 +11001339#endif /* KRB4 */
Damien Miller2ccf6611999-11-15 15:25:10 +11001340
Damien Miller95def091999-11-25 00:26:21 +11001341 case SSH_CMSG_AUTH_RHOSTS:
1342 if (!options.rhosts_authentication) {
1343 verbose("Rhosts authentication disabled.");
1344 break;
1345 }
Damien Miller5428f641999-11-25 11:54:57 +11001346 /*
1347 * Get client user name. Note that we just have to
1348 * trust the client; this is one reason why rhosts
1349 * authentication is insecure. (Another is
1350 * IP-spoofing on a local network.)
1351 */
Damien Miller95def091999-11-25 00:26:21 +11001352 client_user = packet_get_string(&ulen);
1353 packet_integrity_check(plen, 4 + ulen, type);
1354
1355 /* Try to authenticate using /etc/hosts.equiv and
1356 .rhosts. */
1357 authenticated = auth_rhosts(pw, client_user);
1358
1359 snprintf(user, sizeof user, " ruser %s", client_user);
Damien Miller95def091999-11-25 00:26:21 +11001360 break;
Damien Miller7e8e8201999-11-16 13:37:16 +11001361
Damien Miller95def091999-11-25 00:26:21 +11001362 case SSH_CMSG_AUTH_RHOSTS_RSA:
1363 if (!options.rhosts_rsa_authentication) {
1364 verbose("Rhosts with RSA authentication disabled.");
1365 break;
1366 }
Damien Miller5428f641999-11-25 11:54:57 +11001367 /*
1368 * Get client user name. Note that we just have to
1369 * trust the client; root on the client machine can
1370 * claim to be any user.
1371 */
Damien Miller95def091999-11-25 00:26:21 +11001372 client_user = packet_get_string(&ulen);
1373
1374 /* Get the client host key. */
1375 client_host_key_e = BN_new();
1376 client_host_key_n = BN_new();
1377 bits = packet_get_int();
1378 packet_get_bignum(client_host_key_e, &elen);
1379 packet_get_bignum(client_host_key_n, &nlen);
1380
1381 if (bits != BN_num_bits(client_host_key_n))
1382 error("Warning: keysize mismatch for client_host_key: "
1383 "actual %d, announced %d", BN_num_bits(client_host_key_n), bits);
1384 packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1385
1386 authenticated = auth_rhosts_rsa(pw, client_user,
1387 client_host_key_e, client_host_key_n);
1388 BN_clear_free(client_host_key_e);
1389 BN_clear_free(client_host_key_n);
1390
1391 snprintf(user, sizeof user, " ruser %s", client_user);
Damien Miller95def091999-11-25 00:26:21 +11001392 break;
Damien Miller81428f91999-11-18 09:28:11 +11001393
Damien Miller95def091999-11-25 00:26:21 +11001394 case SSH_CMSG_AUTH_RSA:
1395 if (!options.rsa_authentication) {
1396 verbose("RSA authentication disabled.");
1397 break;
1398 }
1399 /* RSA authentication requested. */
1400 n = BN_new();
1401 packet_get_bignum(n, &nlen);
1402 packet_integrity_check(plen, nlen, type);
1403 authenticated = auth_rsa(pw, n);
1404 BN_clear_free(n);
1405 break;
1406
1407 case SSH_CMSG_AUTH_PASSWORD:
1408 if (!options.password_authentication) {
1409 verbose("Password authentication disabled.");
1410 break;
1411 }
Damien Miller5428f641999-11-25 11:54:57 +11001412 /*
1413 * Read user password. It is in plain text, but was
1414 * transmitted over the encrypted channel so it is
1415 * not visible to an outside observer.
1416 */
Damien Miller95def091999-11-25 00:26:21 +11001417 password = packet_get_string(&dlen);
1418 packet_integrity_check(plen, 4 + dlen, type);
1419
Damien Millerbeb4ba51999-12-28 15:09:35 +11001420#ifdef USE_PAM
Damien Miller95def091999-11-25 00:26:21 +11001421 /* Do PAM auth with password */
Damien Millere72b7af1999-12-30 15:08:44 +11001422 authenticated = auth_pam_password(pw, password);
Damien Millerbeb4ba51999-12-28 15:09:35 +11001423#else /* USE_PAM */
Damien Miller95def091999-11-25 00:26:21 +11001424 /* Try authentication with the password. */
1425 authenticated = auth_password(pw, password);
Damien Millerbeb4ba51999-12-28 15:09:35 +11001426#endif /* USE_PAM */
Damien Miller95def091999-11-25 00:26:21 +11001427 memset(password, 0, strlen(password));
1428 xfree(password);
1429 break;
Damien Miller2ccf6611999-11-15 15:25:10 +11001430
Damien Miller95def091999-11-25 00:26:21 +11001431#ifdef SKEY
1432 case SSH_CMSG_AUTH_TIS:
1433 debug("rcvd SSH_CMSG_AUTH_TIS");
1434 if (options.skey_authentication == 1) {
1435 char *skeyinfo = skey_keyinfo(pw->pw_name);
1436 if (skeyinfo == NULL) {
1437 debug("generating fake skeyinfo for %.100s.", pw->pw_name);
1438 skeyinfo = skey_fake_keyinfo(pw->pw_name);
1439 }
1440 if (skeyinfo != NULL) {
Damien Miller5428f641999-11-25 11:54:57 +11001441 /* we send our s/key- in tis-challenge messages */
Damien Miller95def091999-11-25 00:26:21 +11001442 debug("sending challenge '%s'", skeyinfo);
1443 packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1444 packet_put_string(skeyinfo, strlen(skeyinfo));
1445 packet_send();
1446 packet_write_wait();
1447 continue;
1448 }
1449 }
1450 break;
1451 case SSH_CMSG_AUTH_TIS_RESPONSE:
1452 debug("rcvd SSH_CMSG_AUTH_TIS_RESPONSE");
1453 if (options.skey_authentication == 1) {
1454 char *response = packet_get_string(&dlen);
1455 debug("skey response == '%s'", response);
1456 packet_integrity_check(plen, 4 + dlen, type);
1457 authenticated = (skey_haskey(pw->pw_name) == 0 &&
1458 skey_passcheck(pw->pw_name, response) != -1);
1459 xfree(response);
1460 }
1461 break;
1462#else
1463 case SSH_CMSG_AUTH_TIS:
1464 /* TIS Authentication is unsupported */
1465 log("TIS authentication unsupported.");
1466 break;
1467#endif
1468
1469 default:
Damien Miller5428f641999-11-25 11:54:57 +11001470 /*
1471 * Any unknown messages will be ignored (and failure
1472 * returned) during authentication.
1473 */
Damien Miller95def091999-11-25 00:26:21 +11001474 log("Unknown message during authentication: type %d", type);
1475 break;
1476 }
1477
1478 /* Raise logging level */
1479 if (authenticated ||
1480 attempt == AUTH_FAIL_LOG ||
1481 type == SSH_CMSG_AUTH_PASSWORD)
1482 authlog = log;
1483
1484 authlog("%s %s for %.200s from %.200s port %d%s",
1485 authenticated ? "Accepted" : "Failed",
1486 get_authname(type),
1487 pw->pw_uid == 0 ? "ROOT" : pw->pw_name,
1488 get_remote_ipaddr(),
1489 get_remote_port(),
1490 user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001491
Damien Millere72b7af1999-12-30 15:08:44 +11001492 if (authenticated) {
1493#ifdef USE_PAM
1494 if (!do_pam_account(pw->pw_name, client_user))
1495 {
1496 if (client_user != NULL)
1497 xfree(client_user);
1498
1499 do_fake_authloop(pw->pw_name);
1500 }
1501#endif /* USE_PAM */
Damien Miller95def091999-11-25 00:26:21 +11001502 return;
Damien Millere72b7af1999-12-30 15:08:44 +11001503 }
1504
1505 if (client_user != NULL)
1506 xfree(client_user);
Damien Miller95def091999-11-25 00:26:21 +11001507
1508 if (attempt > AUTH_FAIL_MAX)
1509 packet_disconnect(AUTH_FAIL_MSG, pw->pw_name);
1510
1511 /* Send a message indicating that the authentication attempt failed. */
1512 packet_start(SSH_SMSG_FAILURE);
1513 packet_send();
1514 packet_write_wait();
1515 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001516}
1517
Damien Miller95def091999-11-25 00:26:21 +11001518/*
1519 * The user does not exist or access is denied,
1520 * but fake indication that authentication is needed.
1521 */
Damien Miller2ccf6611999-11-15 15:25:10 +11001522void
1523do_fake_authloop(char *user)
Damien Miller3d112ef1999-10-28 13:20:30 +10001524{
Damien Miller95def091999-11-25 00:26:21 +11001525 int attempt = 0;
Damien Miller2ccf6611999-11-15 15:25:10 +11001526
Damien Miller95def091999-11-25 00:26:21 +11001527 log("Faking authloop for illegal user %.200s from %.200s port %d",
1528 user,
1529 get_remote_ipaddr(),
1530 get_remote_port());
Damien Miller3d112ef1999-10-28 13:20:30 +10001531
Damien Miller95def091999-11-25 00:26:21 +11001532 /* Indicate that authentication is needed. */
1533 packet_start(SSH_SMSG_FAILURE);
1534 packet_send();
1535 packet_write_wait();
1536
Damien Miller5428f641999-11-25 11:54:57 +11001537 /*
1538 * Keep reading packets, and always respond with a failure. This is
1539 * to avoid disclosing whether such a user really exists.
1540 */
Damien Miller95def091999-11-25 00:26:21 +11001541 for (attempt = 1;; attempt++) {
Damien Miller5428f641999-11-25 11:54:57 +11001542 /* Read a packet. This will not return if the client disconnects. */
Damien Miller95def091999-11-25 00:26:21 +11001543 int plen;
Damien Millere72b7af1999-12-30 15:08:44 +11001544#ifndef SKEY
1545 (void)packet_read(&plen);
1546#else /* SKEY */
Damien Miller95def091999-11-25 00:26:21 +11001547 int type = packet_read(&plen);
Damien Miller95def091999-11-25 00:26:21 +11001548 int dlen;
1549 char *password, *skeyinfo;
Damien Millera34a28b1999-12-14 10:47:15 +11001550 /* Try to send a fake s/key challenge. */
1551 if (options.skey_authentication == 1 &&
Damien Miller95def091999-11-25 00:26:21 +11001552 (skeyinfo = skey_fake_keyinfo(user)) != NULL) {
Damien Millera34a28b1999-12-14 10:47:15 +11001553 if (type == SSH_CMSG_AUTH_TIS) {
1554 packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1555 packet_put_string(skeyinfo, strlen(skeyinfo));
1556 packet_send();
1557 packet_write_wait();
1558 continue;
1559 } else if (type == SSH_CMSG_AUTH_PASSWORD &&
1560 options.password_authentication &&
1561 (password = packet_get_string(&dlen)) != NULL &&
1562 dlen == 5 &&
1563 strncasecmp(password, "s/key", 5) == 0 ) {
1564 packet_send_debug(skeyinfo);
1565 }
Damien Miller95def091999-11-25 00:26:21 +11001566 }
Damien Miller2ccf6611999-11-15 15:25:10 +11001567#endif
Damien Miller95def091999-11-25 00:26:21 +11001568 if (attempt > AUTH_FAIL_MAX)
1569 packet_disconnect(AUTH_FAIL_MSG, user);
1570
Damien Miller5428f641999-11-25 11:54:57 +11001571 /*
1572 * Send failure. This should be indistinguishable from a
1573 * failed authentication.
1574 */
Damien Miller95def091999-11-25 00:26:21 +11001575 packet_start(SSH_SMSG_FAILURE);
1576 packet_send();
1577 packet_write_wait();
1578 }
1579 /* NOTREACHED */
1580 abort();
Damien Miller3d112ef1999-10-28 13:20:30 +10001581}
1582
Damien Miller2ccf6611999-11-15 15:25:10 +11001583
Damien Miller95def091999-11-25 00:26:21 +11001584/*
1585 * Remove local Xauthority file.
1586 */
Damien Miller5ce662a1999-11-11 17:57:39 +11001587static void
1588xauthfile_cleanup_proc(void *ignore)
1589{
Damien Miller95def091999-11-25 00:26:21 +11001590 debug("xauthfile_cleanup_proc called");
Damien Miller5ce662a1999-11-11 17:57:39 +11001591
Damien Miller95def091999-11-25 00:26:21 +11001592 if (xauthfile != NULL) {
1593 unlink(xauthfile);
1594 xfree(xauthfile);
1595 xauthfile = NULL;
1596 }
Damien Miller5ce662a1999-11-11 17:57:39 +11001597}
1598
Damien Miller95def091999-11-25 00:26:21 +11001599/*
1600 * Prepares for an interactive session. This is called after the user has
1601 * been successfully authenticated. During this message exchange, pseudo
1602 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1603 * are requested, etc.
1604 */
1605void
1606do_authenticated(struct passwd * pw)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001607{
Damien Miller95def091999-11-25 00:26:21 +11001608 int type;
1609 int compression_level = 0, enable_compression_after_reply = 0;
1610 int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1;
1611 int row, col, xpixel, ypixel, screen;
1612 char ttyname[64];
1613 char *command, *term = NULL, *display = NULL, *proto = NULL,
1614 *data = NULL;
1615 struct group *grp;
1616 gid_t tty_gid;
1617 mode_t tty_mode;
1618 int n_bytes;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001619
Damien Miller5428f641999-11-25 11:54:57 +11001620 /*
1621 * Cancel the alarm we set to limit the time taken for
1622 * authentication.
1623 */
Damien Miller95def091999-11-25 00:26:21 +11001624 alarm(0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001625
Damien Miller5428f641999-11-25 11:54:57 +11001626 /*
1627 * Inform the channel mechanism that we are the server side and that
1628 * the client may request to connect to any port at all. (The user
1629 * could do it anyway, and we wouldn\'t know what is permitted except
1630 * by the client telling us, so we can equally well trust the client
1631 * not to request anything bogus.)
1632 */
Damien Miller95def091999-11-25 00:26:21 +11001633 channel_permit_all_opens();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001634
Damien Miller5428f641999-11-25 11:54:57 +11001635 /*
1636 * We stay in this loop until the client requests to execute a shell
1637 * or a command.
1638 */
Damien Miller95def091999-11-25 00:26:21 +11001639 while (1) {
1640 int plen, dlen;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001641
Damien Miller95def091999-11-25 00:26:21 +11001642 /* Get a packet from the client. */
1643 type = packet_read(&plen);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001644
Damien Miller95def091999-11-25 00:26:21 +11001645 /* Process the packet. */
1646 switch (type) {
1647 case SSH_CMSG_REQUEST_COMPRESSION:
1648 packet_integrity_check(plen, 4, type);
1649 compression_level = packet_get_int();
1650 if (compression_level < 1 || compression_level > 9) {
1651 packet_send_debug("Received illegal compression level %d.",
1652 compression_level);
1653 goto fail;
1654 }
1655 /* Enable compression after we have responded with SUCCESS. */
1656 enable_compression_after_reply = 1;
1657 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001658
Damien Miller95def091999-11-25 00:26:21 +11001659 case SSH_CMSG_REQUEST_PTY:
1660 if (no_pty_flag) {
1661 debug("Allocating a pty not permitted for this authentication.");
1662 goto fail;
1663 }
1664 if (have_pty)
1665 packet_disconnect("Protocol error: you already have a pty.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001666
Damien Miller95def091999-11-25 00:26:21 +11001667 debug("Allocating pty.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001668
Damien Miller95def091999-11-25 00:26:21 +11001669 /* Allocate a pty and open it. */
Damien Miller037a0dc1999-12-07 15:38:31 +11001670 if (!pty_allocate(&ptyfd, &ttyfd, ttyname,
1671 sizeof(ttyname))) {
Damien Miller95def091999-11-25 00:26:21 +11001672 error("Failed to allocate pty.");
1673 goto fail;
1674 }
1675 /* Determine the group to make the owner of the tty. */
1676 grp = getgrnam("tty");
1677 if (grp) {
1678 tty_gid = grp->gr_gid;
1679 tty_mode = S_IRUSR | S_IWUSR | S_IWGRP;
1680 } else {
1681 tty_gid = pw->pw_gid;
1682 tty_mode = S_IRUSR | S_IWUSR | S_IWGRP | S_IWOTH;
1683 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001684
Damien Miller95def091999-11-25 00:26:21 +11001685 /* Change ownership of the tty. */
1686 if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
1687 fatal("chown(%.100s, %d, %d) failed: %.100s",
1688 ttyname, pw->pw_uid, tty_gid, strerror(errno));
1689 if (chmod(ttyname, tty_mode) < 0)
1690 fatal("chmod(%.100s, 0%o) failed: %.100s",
1691 ttyname, tty_mode, strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001692
Damien Miller95def091999-11-25 00:26:21 +11001693 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
1694 term = packet_get_string(&dlen);
1695 packet_integrity_check(dlen, strlen(term), type);
1696 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
1697 /* Remaining bytes */
1698 n_bytes = plen - (4 + dlen + 4 * 4);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001699
Damien Miller95def091999-11-25 00:26:21 +11001700 if (strcmp(term, "") == 0)
1701 term = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001702
Damien Miller95def091999-11-25 00:26:21 +11001703 /* Get window size from the packet. */
1704 row = packet_get_int();
1705 col = packet_get_int();
1706 xpixel = packet_get_int();
1707 ypixel = packet_get_int();
1708 pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001709
Damien Miller95def091999-11-25 00:26:21 +11001710 /* Get tty modes from the packet. */
1711 tty_parse_modes(ttyfd, &n_bytes);
1712 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001713
Damien Miller95def091999-11-25 00:26:21 +11001714 /* Indicate that we now have a pty. */
1715 have_pty = 1;
Damien Millerbf1c9b21999-12-09 10:16:54 +11001716
Damien Millerbeb4ba51999-12-28 15:09:35 +11001717#ifdef USE_PAM
Damien Millerbf1c9b21999-12-09 10:16:54 +11001718 /* do the pam_open_session since we have the pty */
Damien Millere72b7af1999-12-30 15:08:44 +11001719 do_pam_session(pw->pw_name, ttyname);
Damien Millerbeb4ba51999-12-28 15:09:35 +11001720#endif /* USE_PAM */
Damien Millerbf1c9b21999-12-09 10:16:54 +11001721
Damien Miller95def091999-11-25 00:26:21 +11001722 break;
1723
1724 case SSH_CMSG_X11_REQUEST_FORWARDING:
1725 if (!options.x11_forwarding) {
1726 packet_send_debug("X11 forwarding disabled in server configuration file.");
1727 goto fail;
1728 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001729#ifdef XAUTH_PATH
Damien Miller95def091999-11-25 00:26:21 +11001730 if (no_x11_forwarding_flag) {
1731 packet_send_debug("X11 forwarding not permitted for this authentication.");
1732 goto fail;
1733 }
1734 debug("Received request for X11 forwarding with auth spoofing.");
1735 if (display)
1736 packet_disconnect("Protocol error: X11 display already set.");
1737 {
1738 int proto_len, data_len;
1739 proto = packet_get_string(&proto_len);
1740 data = packet_get_string(&data_len);
1741 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
1742 }
1743 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1744 screen = packet_get_int();
1745 else
1746 screen = 0;
Damien Millera34a28b1999-12-14 10:47:15 +11001747 display = x11_create_display_inet(screen, options.x11_display_offset);
Damien Miller95def091999-11-25 00:26:21 +11001748 if (!display)
1749 goto fail;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001750
Damien Miller95def091999-11-25 00:26:21 +11001751 /* Setup to always have a local .Xauthority. */
1752 xauthfile = xmalloc(MAXPATHLEN);
1753 snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX");
1754
1755 if ((xauthfd = mkstemp(xauthfile)) != -1) {
1756 fchown(xauthfd, pw->pw_uid, pw->pw_gid);
1757 close(xauthfd);
1758 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
1759 } else {
1760 xfree(xauthfile);
1761 xauthfile = NULL;
1762 }
1763 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001764#else /* XAUTH_PATH */
Damien Miller95def091999-11-25 00:26:21 +11001765 packet_send_debug("No xauth program; cannot forward with spoofing.");
1766 goto fail;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001767#endif /* XAUTH_PATH */
1768
Damien Miller95def091999-11-25 00:26:21 +11001769 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1770 if (no_agent_forwarding_flag) {
1771 debug("Authentication agent forwarding not permitted for this authentication.");
1772 goto fail;
1773 }
1774 debug("Received authentication agent forwarding request.");
1775 auth_input_request_forwarding(pw);
1776 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001777
Damien Miller95def091999-11-25 00:26:21 +11001778 case SSH_CMSG_PORT_FORWARD_REQUEST:
1779 if (no_port_forwarding_flag) {
1780 debug("Port forwarding not permitted for this authentication.");
1781 goto fail;
1782 }
1783 debug("Received TCP/IP port forwarding request.");
1784 channel_input_port_forward_request(pw->pw_uid == 0);
1785 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001786
Damien Miller95def091999-11-25 00:26:21 +11001787 case SSH_CMSG_MAX_PACKET_SIZE:
1788 if (packet_set_maxsize(packet_get_int()) < 0)
1789 goto fail;
1790 break;
Damien Miller6162d121999-11-21 13:23:52 +11001791
Damien Miller95def091999-11-25 00:26:21 +11001792 case SSH_CMSG_EXEC_SHELL:
1793 /* Set interactive/non-interactive mode. */
1794 packet_set_interactive(have_pty || display != NULL,
1795 options.keepalives);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001796
Damien Millerac3a4b41999-12-29 10:25:40 +11001797#ifdef USE_PAM
1798 do_pam_setcred();
Damien Millere72b7af1999-12-30 15:08:44 +11001799#endif /* USE_PAM */
Damien Miller95def091999-11-25 00:26:21 +11001800 if (forced_command != NULL)
1801 goto do_forced_command;
1802 debug("Forking shell.");
1803 packet_integrity_check(plen, 0, type);
1804 if (have_pty)
1805 do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1806 else
1807 do_exec_no_pty(NULL, pw, display, proto, data);
1808 return;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001809
Damien Miller95def091999-11-25 00:26:21 +11001810 case SSH_CMSG_EXEC_CMD:
1811 /* Set interactive/non-interactive mode. */
1812 packet_set_interactive(have_pty || display != NULL,
1813 options.keepalives);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001814
Damien Millerac3a4b41999-12-29 10:25:40 +11001815#ifdef USE_PAM
1816 do_pam_setcred();
Damien Millere72b7af1999-12-30 15:08:44 +11001817#endif /* USE_PAM */
Damien Miller95def091999-11-25 00:26:21 +11001818 if (forced_command != NULL)
1819 goto do_forced_command;
1820 /* Get command from the packet. */
1821 {
1822 int dlen;
1823 command = packet_get_string(&dlen);
1824 debug("Executing command '%.500s'", command);
1825 packet_integrity_check(plen, 4 + dlen, type);
1826 }
1827 if (have_pty)
1828 do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1829 else
1830 do_exec_no_pty(command, pw, display, proto, data);
1831 xfree(command);
1832 return;
1833
1834 default:
Damien Miller5428f641999-11-25 11:54:57 +11001835 /*
1836 * Any unknown messages in this phase are ignored,
1837 * and a failure message is returned.
1838 */
Damien Miller95def091999-11-25 00:26:21 +11001839 log("Unknown packet type received after authentication: %d", type);
1840 goto fail;
1841 }
1842
1843 /* The request was successfully processed. */
1844 packet_start(SSH_SMSG_SUCCESS);
1845 packet_send();
1846 packet_write_wait();
1847
1848 /* Enable compression now that we have replied if appropriate. */
1849 if (enable_compression_after_reply) {
1850 enable_compression_after_reply = 0;
1851 packet_start_compression(compression_level);
1852 }
1853 continue;
1854
1855fail:
1856 /* The request failed. */
1857 packet_start(SSH_SMSG_FAILURE);
1858 packet_send();
1859 packet_write_wait();
1860 continue;
1861
1862do_forced_command:
Damien Miller5428f641999-11-25 11:54:57 +11001863 /*
1864 * There is a forced command specified for this login.
1865 * Execute it.
1866 */
Damien Miller95def091999-11-25 00:26:21 +11001867 debug("Executing forced command: %.900s", forced_command);
1868 if (have_pty)
1869 do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1870 else
1871 do_exec_no_pty(forced_command, pw, display, proto, data);
1872 return;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001873 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001874}
1875
Damien Miller95def091999-11-25 00:26:21 +11001876/*
1877 * This is called to fork and execute a command when we have no tty. This
1878 * will call do_child from the child, and server_loop from the parent after
1879 * setting up file descriptors and such.
1880 */
1881void
1882do_exec_no_pty(const char *command, struct passwd * pw,
1883 const char *display, const char *auth_proto,
1884 const char *auth_data)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001885{
Damien Miller95def091999-11-25 00:26:21 +11001886 int pid;
1887
1888#ifdef USE_PIPES
1889 int pin[2], pout[2], perr[2];
1890 /* Allocate pipes for communicating with the program. */
1891 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1892 packet_disconnect("Could not create pipes: %.100s",
1893 strerror(errno));
1894#else /* USE_PIPES */
1895 int inout[2], err[2];
1896 /* Uses socket pairs to communicate with the program. */
1897 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
1898 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
1899 packet_disconnect("Could not create socket pairs: %.100s",
1900 strerror(errno));
1901#endif /* USE_PIPES */
1902
1903 setproctitle("%s@notty", pw->pw_name);
1904
1905 /* Fork the child. */
1906 if ((pid = fork()) == 0) {
1907 /* Child. Reinitialize the log since the pid has changed. */
1908 log_init(av0, options.log_level, options.log_facility, log_stderr);
1909
Damien Miller5428f641999-11-25 11:54:57 +11001910 /*
1911 * Create a new session and process group since the 4.4BSD
1912 * setlogin() affects the entire process group.
1913 */
Damien Miller95def091999-11-25 00:26:21 +11001914 if (setsid() < 0)
1915 error("setsid failed: %.100s", strerror(errno));
1916
1917#ifdef USE_PIPES
Damien Miller5428f641999-11-25 11:54:57 +11001918 /*
1919 * Redirect stdin. We close the parent side of the socket
1920 * pair, and make the child side the standard input.
1921 */
Damien Miller95def091999-11-25 00:26:21 +11001922 close(pin[1]);
1923 if (dup2(pin[0], 0) < 0)
1924 perror("dup2 stdin");
1925 close(pin[0]);
1926
1927 /* Redirect stdout. */
1928 close(pout[0]);
1929 if (dup2(pout[1], 1) < 0)
1930 perror("dup2 stdout");
1931 close(pout[1]);
1932
1933 /* Redirect stderr. */
1934 close(perr[0]);
1935 if (dup2(perr[1], 2) < 0)
1936 perror("dup2 stderr");
1937 close(perr[1]);
1938#else /* USE_PIPES */
Damien Miller5428f641999-11-25 11:54:57 +11001939 /*
1940 * Redirect stdin, stdout, and stderr. Stdin and stdout will
1941 * use the same socket, as some programs (particularly rdist)
1942 * seem to depend on it.
1943 */
Damien Miller95def091999-11-25 00:26:21 +11001944 close(inout[1]);
1945 close(err[1]);
1946 if (dup2(inout[0], 0) < 0) /* stdin */
1947 perror("dup2 stdin");
1948 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
1949 perror("dup2 stdout");
1950 if (dup2(err[0], 2) < 0) /* stderr */
1951 perror("dup2 stderr");
1952#endif /* USE_PIPES */
1953
1954 /* Do processing for the child (exec command etc). */
1955 do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
1956 /* NOTREACHED */
1957 }
1958 if (pid < 0)
1959 packet_disconnect("fork failed: %.100s", strerror(errno));
1960#ifdef USE_PIPES
1961 /* We are the parent. Close the child sides of the pipes. */
1962 close(pin[0]);
1963 close(pout[1]);
1964 close(perr[1]);
1965
1966 /* Enter the interactive session. */
1967 server_loop(pid, pin[1], pout[0], perr[0]);
1968 /* server_loop has closed pin[1], pout[1], and perr[1]. */
1969#else /* USE_PIPES */
1970 /* We are the parent. Close the child sides of the socket pairs. */
1971 close(inout[0]);
1972 close(err[0]);
1973
Damien Miller5428f641999-11-25 11:54:57 +11001974 /*
1975 * Enter the interactive session. Note: server_loop must be able to
1976 * handle the case that fdin and fdout are the same.
1977 */
Damien Miller95def091999-11-25 00:26:21 +11001978 server_loop(pid, inout[1], inout[1], err[1]);
1979 /* server_loop has closed inout[1] and err[1]. */
1980#endif /* USE_PIPES */
1981}
1982
1983struct pty_cleanup_context {
1984 const char *ttyname;
1985 int pid;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001986};
1987
Damien Miller95def091999-11-25 00:26:21 +11001988/*
1989 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
1990 * dropped connection).
1991 */
1992void
1993pty_cleanup_proc(void *context)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001994{
Damien Miller95def091999-11-25 00:26:21 +11001995 struct pty_cleanup_context *cu = context;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001996
Damien Miller95def091999-11-25 00:26:21 +11001997 debug("pty_cleanup_proc called");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001998
Damien Miller95def091999-11-25 00:26:21 +11001999 /* Record that the user has logged out. */
2000 record_logout(cu->pid, cu->ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002001
Damien Miller95def091999-11-25 00:26:21 +11002002 /* Release the pseudo-tty. */
2003 pty_release(cu->ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002004}
2005
Damien Miller95def091999-11-25 00:26:21 +11002006/*
2007 * This is called to fork and execute a command when we have a tty. This
2008 * will call do_child from the child, and server_loop from the parent after
2009 * setting up file descriptors, controlling tty, updating wtmp, utmp,
2010 * lastlog, and other such operations.
2011 */
2012void
2013do_exec_pty(const char *command, int ptyfd, int ttyfd,
2014 const char *ttyname, struct passwd * pw, const char *term,
2015 const char *display, const char *auth_proto,
2016 const char *auth_data)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002017{
Damien Miller95def091999-11-25 00:26:21 +11002018 int pid, fdout;
2019 const char *hostname;
2020 time_t last_login_time;
2021 char buf[100], *time_string;
2022 FILE *f;
2023 char line[256];
2024 struct stat st;
2025 int quiet_login;
Damien Miller34132e52000-01-14 15:45:46 +11002026 struct sockaddr_storage from;
2027 socklen_t fromlen;
Damien Miller95def091999-11-25 00:26:21 +11002028 struct pty_cleanup_context cleanup_context;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002029
Damien Miller95def091999-11-25 00:26:21 +11002030 /* Get remote host name. */
2031 hostname = get_canonical_hostname();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002032
Damien Miller5428f641999-11-25 11:54:57 +11002033 /*
2034 * Get the time when the user last logged in. Buf will be set to
2035 * contain the hostname the last login was from.
2036 */
Damien Miller95def091999-11-25 00:26:21 +11002037 if (!options.use_login) {
2038 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
2039 buf, sizeof(buf));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002040 }
Damien Miller95def091999-11-25 00:26:21 +11002041 setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002042
Damien Miller95def091999-11-25 00:26:21 +11002043 /* Fork the child. */
2044 if ((pid = fork()) == 0) {
2045 pid = getpid();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002046
Damien Miller95def091999-11-25 00:26:21 +11002047 /* Child. Reinitialize the log because the pid has
2048 changed. */
2049 log_init(av0, options.log_level, options.log_facility, log_stderr);
2050
2051 /* Close the master side of the pseudo tty. */
2052 close(ptyfd);
2053
2054 /* Make the pseudo tty our controlling tty. */
2055 pty_make_controlling_tty(&ttyfd, ttyname);
2056
2057 /* Redirect stdin from the pseudo tty. */
2058 if (dup2(ttyfd, fileno(stdin)) < 0)
2059 error("dup2 stdin failed: %.100s", strerror(errno));
2060
2061 /* Redirect stdout to the pseudo tty. */
2062 if (dup2(ttyfd, fileno(stdout)) < 0)
2063 error("dup2 stdin failed: %.100s", strerror(errno));
2064
2065 /* Redirect stderr to the pseudo tty. */
2066 if (dup2(ttyfd, fileno(stderr)) < 0)
2067 error("dup2 stdin failed: %.100s", strerror(errno));
2068
2069 /* Close the extra descriptor for the pseudo tty. */
2070 close(ttyfd);
2071
Damien Miller5428f641999-11-25 11:54:57 +11002072 /*
2073 * Get IP address of client. This is needed because we want
2074 * to record where the user logged in from. If the
2075 * connection is not a socket, let the ip address be 0.0.0.0.
2076 */
Damien Miller95def091999-11-25 00:26:21 +11002077 memset(&from, 0, sizeof(from));
2078 if (packet_get_connection_in() == packet_get_connection_out()) {
2079 fromlen = sizeof(from);
2080 if (getpeername(packet_get_connection_in(),
2081 (struct sockaddr *) & from, &fromlen) < 0) {
2082 debug("getpeername: %.100s", strerror(errno));
2083 fatal_cleanup();
2084 }
2085 }
2086 /* Record that there was a login on that terminal. */
2087 record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
Damien Miller34132e52000-01-14 15:45:46 +11002088 (struct sockaddr *)&from);
Damien Miller95def091999-11-25 00:26:21 +11002089
2090 /* Check if .hushlogin exists. */
2091 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2092 quiet_login = stat(line, &st) >= 0;
Damien Miller356a0b01999-11-08 15:30:59 +11002093
Damien Millerbeb4ba51999-12-28 15:09:35 +11002094#ifdef USE_PAM
Damien Millere72b7af1999-12-30 15:08:44 +11002095 if (!quiet_login)
2096 print_pam_messages();
2097#endif /* USE_PAM */
Damien Miller95def091999-11-25 00:26:21 +11002098
Damien Miller5428f641999-11-25 11:54:57 +11002099 /*
2100 * If the user has logged in before, display the time of last
2101 * login. However, don't display anything extra if a command
2102 * has been specified (so that ssh can be used to execute
2103 * commands on a remote machine without users knowing they
2104 * are going to another machine). Login(1) will do this for
2105 * us as well, so check if login(1) is used
2106 */
Damien Miller95def091999-11-25 00:26:21 +11002107 if (command == NULL && last_login_time != 0 && !quiet_login &&
2108 !options.use_login) {
2109 /* Convert the date to a string. */
2110 time_string = ctime(&last_login_time);
2111 /* Remove the trailing newline. */
2112 if (strchr(time_string, '\n'))
2113 *strchr(time_string, '\n') = 0;
2114 /* Display the last login time. Host if displayed
2115 if known. */
2116 if (strcmp(buf, "") == 0)
2117 printf("Last login: %s\r\n", time_string);
2118 else
2119 printf("Last login: %s from %s\r\n", time_string, buf);
2120 }
Damien Miller5428f641999-11-25 11:54:57 +11002121 /*
2122 * Print /etc/motd unless a command was specified or printing
2123 * it was disabled in server options or login(1) will be
2124 * used. Note that some machines appear to print it in
2125 * /etc/profile or similar.
2126 */
Damien Miller95def091999-11-25 00:26:21 +11002127 if (command == NULL && options.print_motd && !quiet_login &&
2128 !options.use_login) {
2129 /* Print /etc/motd if it exists. */
2130 f = fopen("/etc/motd", "r");
2131 if (f) {
2132 while (fgets(line, sizeof(line), f))
2133 fputs(line, stdout);
2134 fclose(f);
2135 }
2136 }
2137 /* Do common processing for the child, such as execing the command. */
2138 do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
2139 /* NOTREACHED */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002140 }
Damien Miller95def091999-11-25 00:26:21 +11002141 if (pid < 0)
2142 packet_disconnect("fork failed: %.100s", strerror(errno));
2143 /* Parent. Close the slave side of the pseudo tty. */
2144 close(ttyfd);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002145
Damien Miller5428f641999-11-25 11:54:57 +11002146 /*
2147 * Create another descriptor of the pty master side for use as the
2148 * standard input. We could use the original descriptor, but this
2149 * simplifies code in server_loop. The descriptor is bidirectional.
2150 */
Damien Miller95def091999-11-25 00:26:21 +11002151 fdout = dup(ptyfd);
2152 if (fdout < 0)
2153 packet_disconnect("dup failed: %.100s", strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002154
Damien Miller5428f641999-11-25 11:54:57 +11002155 /*
2156 * Add a cleanup function to clear the utmp entry and record logout
2157 * time in case we call fatal() (e.g., the connection gets closed).
2158 */
Damien Miller95def091999-11-25 00:26:21 +11002159 cleanup_context.pid = pid;
2160 cleanup_context.ttyname = ttyname;
2161 fatal_add_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002162
Damien Miller95def091999-11-25 00:26:21 +11002163 /* Enter interactive session. */
2164 server_loop(pid, ptyfd, fdout, -1);
2165 /* server_loop has not closed ptyfd and fdout. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002166
Damien Miller95def091999-11-25 00:26:21 +11002167 /* Cancel the cleanup function. */
2168 fatal_remove_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002169
Damien Miller95def091999-11-25 00:26:21 +11002170 /* Record that the user has logged out. */
2171 record_logout(pid, ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002172
Damien Miller95def091999-11-25 00:26:21 +11002173 /* Release the pseudo-tty. */
2174 pty_release(ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002175
Damien Miller5428f641999-11-25 11:54:57 +11002176 /*
2177 * Close the server side of the socket pairs. We must do this after
2178 * the pty cleanup, so that another process doesn't get this pty
2179 * while we're still cleaning up.
2180 */
Damien Miller95def091999-11-25 00:26:21 +11002181 close(ptyfd);
2182 close(fdout);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002183}
2184
Damien Miller95def091999-11-25 00:26:21 +11002185/*
2186 * Sets the value of the given variable in the environment. If the variable
2187 * already exists, its value is overriden.
2188 */
2189void
2190child_set_env(char ***envp, unsigned int *envsizep, const char *name,
2191 const char *value)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002192{
Damien Miller95def091999-11-25 00:26:21 +11002193 unsigned int i, namelen;
2194 char **env;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002195
Damien Miller5428f641999-11-25 11:54:57 +11002196 /*
2197 * Find the slot where the value should be stored. If the variable
2198 * already exists, we reuse the slot; otherwise we append a new slot
2199 * at the end of the array, expanding if necessary.
2200 */
Damien Miller95def091999-11-25 00:26:21 +11002201 env = *envp;
2202 namelen = strlen(name);
2203 for (i = 0; env[i]; i++)
2204 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2205 break;
2206 if (env[i]) {
Damien Miller5428f641999-11-25 11:54:57 +11002207 /* Reuse the slot. */
Damien Miller95def091999-11-25 00:26:21 +11002208 xfree(env[i]);
2209 } else {
Damien Miller5428f641999-11-25 11:54:57 +11002210 /* New variable. Expand if necessary. */
Damien Miller95def091999-11-25 00:26:21 +11002211 if (i >= (*envsizep) - 1) {
2212 (*envsizep) += 50;
2213 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2214 }
2215 /* Need to set the NULL pointer at end of array beyond the new slot. */
2216 env[i + 1] = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002217 }
2218
Damien Miller95def091999-11-25 00:26:21 +11002219 /* Allocate space and format the variable in the appropriate slot. */
2220 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2221 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002222}
2223
Damien Miller95def091999-11-25 00:26:21 +11002224/*
2225 * Reads environment variables from the given file and adds/overrides them
2226 * into the environment. If the file does not exist, this does nothing.
2227 * Otherwise, it must consist of empty lines, comments (line starts with '#')
2228 * and assignments of the form name=value. No other forms are allowed.
2229 */
2230void
2231read_environment_file(char ***env, unsigned int *envsize,
2232 const char *filename)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002233{
Damien Miller95def091999-11-25 00:26:21 +11002234 FILE *f;
2235 char buf[4096];
2236 char *cp, *value;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002237
Damien Miller95def091999-11-25 00:26:21 +11002238 f = fopen(filename, "r");
2239 if (!f)
2240 return;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002241
Damien Miller95def091999-11-25 00:26:21 +11002242 while (fgets(buf, sizeof(buf), f)) {
Damien Miller5428f641999-11-25 11:54:57 +11002243 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
2244 ;
Damien Miller95def091999-11-25 00:26:21 +11002245 if (!*cp || *cp == '#' || *cp == '\n')
2246 continue;
Damien Miller95def091999-11-25 00:26:21 +11002247 if (strchr(cp, '\n'))
2248 *strchr(cp, '\n') = '\0';
Damien Miller95def091999-11-25 00:26:21 +11002249 value = strchr(cp, '=');
2250 if (value == NULL) {
2251 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
2252 continue;
2253 }
Damien Miller5428f641999-11-25 11:54:57 +11002254 /* Replace the equals sign by nul, and advance value to the value string. */
Damien Miller95def091999-11-25 00:26:21 +11002255 *value = '\0';
2256 value++;
Damien Miller95def091999-11-25 00:26:21 +11002257 child_set_env(env, envsize, cp, value);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002258 }
Damien Miller95def091999-11-25 00:26:21 +11002259 fclose(f);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002260}
2261
Damien Millere72b7af1999-12-30 15:08:44 +11002262#ifdef USE_PAM
2263/*
2264 * Sets any environment variables which have been specified by PAM
2265 */
2266void do_pam_environment(char ***env, int *envsize)
2267{
2268 char *equals, var_name[512], var_val[512];
2269 char **pam_env;
2270 int i;
2271
2272 if ((pam_env = fetch_pam_environment()) == NULL)
2273 return;
2274
2275 for(i = 0; pam_env[i] != NULL; i++) {
2276 if ((equals = strstr(pam_env[i], "=")) == NULL)
2277 continue;
2278
2279 if (strlen(pam_env[i]) < (sizeof(var_name) - 1))
2280 {
2281 memset(var_name, '\0', sizeof(var_name));
2282 memset(var_val, '\0', sizeof(var_val));
2283
2284 strncpy(var_name, pam_env[i], equals - pam_env[i]);
2285 strcpy(var_val, equals + 1);
2286
2287 debug("PAM environment: %s=%s", var_name, var_val);
2288
2289 child_set_env(env, envsize, var_name, var_val);
2290 }
2291 }
2292}
2293#endif /* USE_PAM */
2294
Damien Miller95def091999-11-25 00:26:21 +11002295/*
2296 * Performs common processing for the child, such as setting up the
2297 * environment, closing extra file descriptors, setting the user and group
2298 * ids, and executing the command or shell.
2299 */
2300void
2301do_child(const char *command, struct passwd * pw, const char *term,
2302 const char *display, const char *auth_proto,
2303 const char *auth_data, const char *ttyname)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002304{
Damien Miller95def091999-11-25 00:26:21 +11002305 const char *shell, *cp = NULL;
2306 char buf[256];
2307 FILE *f;
2308 unsigned int envsize, i;
2309 char **env;
2310 extern char **environ;
2311 struct stat st;
2312 char *argv[10];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002313
Damien Millerbeb4ba51999-12-28 15:09:35 +11002314#ifndef USE_PAM /* pam_nologin handles this */
Damien Miller95def091999-11-25 00:26:21 +11002315 /* Check /etc/nologin. */
2316 f = fopen("/etc/nologin", "r");
2317 if (f) {
2318 /* /etc/nologin exists. Print its contents and exit. */
2319 while (fgets(buf, sizeof(buf), f))
2320 fputs(buf, stderr);
2321 fclose(f);
2322 if (pw->pw_uid != 0)
2323 exit(254);
2324 }
Damien Millerbeb4ba51999-12-28 15:09:35 +11002325#endif /* USE_PAM */
Damien Miller776af5d1999-11-12 08:49:09 +11002326
Damien Miller95def091999-11-25 00:26:21 +11002327 /* Set login name in the kernel. */
2328 if (setlogin(pw->pw_name) < 0)
2329 error("setlogin failed: %s", strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002330
Damien Miller95def091999-11-25 00:26:21 +11002331 /* Set uid, gid, and groups. */
2332 /* Login(1) does this as well, and it needs uid 0 for the "-h"
2333 switch, so we let login(1) to this for us. */
2334 if (!options.use_login) {
2335 if (getuid() == 0 || geteuid() == 0) {
2336 if (setgid(pw->pw_gid) < 0) {
2337 perror("setgid");
2338 exit(1);
2339 }
2340 /* Initialize the group list. */
2341 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
2342 perror("initgroups");
2343 exit(1);
2344 }
2345 endgrent();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002346
Damien Miller95def091999-11-25 00:26:21 +11002347 /* Permanently switch to the desired uid. */
2348 permanently_set_uid(pw->pw_uid);
2349 }
2350 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
2351 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
2352 }
Damien Miller5428f641999-11-25 11:54:57 +11002353 /*
2354 * Get the shell from the password data. An empty shell field is
2355 * legal, and means /bin/sh.
2356 */
Damien Miller95def091999-11-25 00:26:21 +11002357 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002358
2359#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11002360 /* Try to get AFS tokens for the local cell. */
2361 if (k_hasafs()) {
2362 char cell[64];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002363
Damien Miller95def091999-11-25 00:26:21 +11002364 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
2365 krb_afslog(cell, 0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002366
Damien Miller95def091999-11-25 00:26:21 +11002367 krb_afslog(0, 0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002368 }
Damien Miller95def091999-11-25 00:26:21 +11002369#endif /* AFS */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002370
Damien Miller5428f641999-11-25 11:54:57 +11002371 /* Initialize the environment. */
Damien Miller95def091999-11-25 00:26:21 +11002372 envsize = 100;
2373 env = xmalloc(envsize * sizeof(char *));
2374 env[0] = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002375
Damien Miller95def091999-11-25 00:26:21 +11002376 if (!options.use_login) {
2377 /* Set basic environment. */
2378 child_set_env(&env, &envsize, "USER", pw->pw_name);
2379 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
2380 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2381 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002382
Damien Miller95def091999-11-25 00:26:21 +11002383 snprintf(buf, sizeof buf, "%.200s/%.50s",
2384 _PATH_MAILDIR, pw->pw_name);
2385 child_set_env(&env, &envsize, "MAIL", buf);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002386
Damien Miller95def091999-11-25 00:26:21 +11002387 /* Normal systems set SHELL by default. */
2388 child_set_env(&env, &envsize, "SHELL", shell);
2389 }
Damien Miller95def091999-11-25 00:26:21 +11002390 if (getenv("TZ"))
2391 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
2392
2393 /* Set custom environment options from RSA authentication. */
2394 while (custom_environment) {
2395 struct envstring *ce = custom_environment;
2396 char *s = ce->s;
2397 int i;
2398 for (i = 0; s[i] != '=' && s[i]; i++);
2399 if (s[i] == '=') {
2400 s[i] = 0;
2401 child_set_env(&env, &envsize, s, s + i + 1);
2402 }
2403 custom_environment = ce->next;
2404 xfree(ce->s);
2405 xfree(ce);
2406 }
2407
Damien Miller95def091999-11-25 00:26:21 +11002408 snprintf(buf, sizeof buf, "%.50s %d %d",
Damien Miller34132e52000-01-14 15:45:46 +11002409 get_remote_ipaddr(), get_remote_port(), get_local_port());
Damien Miller95def091999-11-25 00:26:21 +11002410 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2411
Damien Miller95def091999-11-25 00:26:21 +11002412 if (ttyname)
2413 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
Damien Miller95def091999-11-25 00:26:21 +11002414 if (term)
2415 child_set_env(&env, &envsize, "TERM", term);
Damien Miller95def091999-11-25 00:26:21 +11002416 if (display)
2417 child_set_env(&env, &envsize, "DISPLAY", display);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002418
2419#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11002420 {
2421 extern char *ticket;
2422
2423 if (ticket)
2424 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2425 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002426#endif /* KRB4 */
2427
Damien Millerbeb4ba51999-12-28 15:09:35 +11002428#ifdef USE_PAM
Damien Miller95def091999-11-25 00:26:21 +11002429 /* Pull in any environment variables that may have been set by PAM. */
Damien Millere72b7af1999-12-30 15:08:44 +11002430 do_pam_environment(&env, &envsize);
Damien Millerbeb4ba51999-12-28 15:09:35 +11002431#endif /* USE_PAM */
Damien Miller94388161999-10-29 09:57:31 +10002432
Damien Miller95def091999-11-25 00:26:21 +11002433 if (xauthfile)
2434 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002435
Damien Miller95def091999-11-25 00:26:21 +11002436 if (auth_get_socket_name() != NULL)
2437 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
2438 auth_get_socket_name());
Damien Miller776af5d1999-11-12 08:49:09 +11002439
Damien Miller5428f641999-11-25 11:54:57 +11002440 /* read $HOME/.ssh/environment. */
Damien Miller95def091999-11-25 00:26:21 +11002441 if (!options.use_login) {
2442 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
2443 read_environment_file(&env, &envsize, buf);
2444 }
Damien Miller95def091999-11-25 00:26:21 +11002445 if (debug_flag) {
Damien Miller5428f641999-11-25 11:54:57 +11002446 /* dump the environment */
Damien Miller95def091999-11-25 00:26:21 +11002447 fprintf(stderr, "Environment:\n");
2448 for (i = 0; env[i]; i++)
2449 fprintf(stderr, " %.200s\n", env[i]);
2450 }
Damien Miller5428f641999-11-25 11:54:57 +11002451 /*
2452 * Close the connection descriptors; note that this is the child, and
2453 * the server will still have the socket open, and it is important
2454 * that we do not shutdown it. Note that the descriptors cannot be
2455 * closed before building the environment, as we call
2456 * get_remote_ipaddr there.
2457 */
Damien Miller95def091999-11-25 00:26:21 +11002458 if (packet_get_connection_in() == packet_get_connection_out())
2459 close(packet_get_connection_in());
2460 else {
2461 close(packet_get_connection_in());
2462 close(packet_get_connection_out());
2463 }
Damien Miller5428f641999-11-25 11:54:57 +11002464 /*
2465 * Close all descriptors related to channels. They will still remain
2466 * open in the parent.
2467 */
2468 /* XXX better use close-on-exec? -markus */
Damien Miller95def091999-11-25 00:26:21 +11002469 channel_close_all();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002470
Damien Miller5428f641999-11-25 11:54:57 +11002471 /*
2472 * Close any extra file descriptors. Note that there may still be
2473 * descriptors left by system functions. They will be closed later.
2474 */
Damien Miller95def091999-11-25 00:26:21 +11002475 endpwent();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002476
Damien Miller5428f641999-11-25 11:54:57 +11002477 /*
2478 * Close any extra open file descriptors so that we don\'t have them
2479 * hanging around in clients. Note that we want to do this after
2480 * initgroups, because at least on Solaris 2.3 it leaves file
2481 * descriptors open.
2482 */
Damien Miller95def091999-11-25 00:26:21 +11002483 for (i = 3; i < 64; i++)
2484 close(i);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002485
Damien Miller95def091999-11-25 00:26:21 +11002486 /* Change current directory to the user\'s home directory. */
2487 if (chdir(pw->pw_dir) < 0)
2488 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2489 pw->pw_dir, strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002490
Damien Miller5428f641999-11-25 11:54:57 +11002491 /*
2492 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
2493 * xauth are run in the proper environment.
2494 */
Damien Miller95def091999-11-25 00:26:21 +11002495 environ = env;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002496
Damien Miller5428f641999-11-25 11:54:57 +11002497 /*
2498 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
2499 * in this order).
2500 */
Damien Miller95def091999-11-25 00:26:21 +11002501 if (!options.use_login) {
2502 if (stat(SSH_USER_RC, &st) >= 0) {
2503 if (debug_flag)
2504 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002505
Damien Miller95def091999-11-25 00:26:21 +11002506 f = popen("/bin/sh " SSH_USER_RC, "w");
2507 if (f) {
2508 if (auth_proto != NULL && auth_data != NULL)
2509 fprintf(f, "%s %s\n", auth_proto, auth_data);
2510 pclose(f);
2511 } else
2512 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2513 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
2514 if (debug_flag)
2515 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002516
Damien Miller95def091999-11-25 00:26:21 +11002517 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2518 if (f) {
2519 if (auth_proto != NULL && auth_data != NULL)
2520 fprintf(f, "%s %s\n", auth_proto, auth_data);
2521 pclose(f);
2522 } else
2523 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2524 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002525#ifdef XAUTH_PATH
Damien Miller95def091999-11-25 00:26:21 +11002526 else {
Damien Miller5428f641999-11-25 11:54:57 +11002527 /* Add authority data to .Xauthority if appropriate. */
Damien Miller95def091999-11-25 00:26:21 +11002528 if (auth_proto != NULL && auth_data != NULL) {
2529 if (debug_flag)
2530 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2531 XAUTH_PATH, display, auth_proto, auth_data);
2532
2533 f = popen(XAUTH_PATH " -q -", "w");
2534 if (f) {
2535 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
2536 fclose(f);
2537 } else
2538 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2539 }
2540 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002541#endif /* XAUTH_PATH */
2542
Damien Miller95def091999-11-25 00:26:21 +11002543 /* Get the last component of the shell name. */
2544 cp = strrchr(shell, '/');
2545 if (cp)
2546 cp++;
2547 else
2548 cp = shell;
2549 }
Damien Miller5428f641999-11-25 11:54:57 +11002550 /*
2551 * If we have no command, execute the shell. In this case, the shell
2552 * name to be passed in argv[0] is preceded by '-' to indicate that
2553 * this is a login shell.
2554 */
Damien Miller95def091999-11-25 00:26:21 +11002555 if (!command) {
2556 if (!options.use_login) {
2557 char buf[256];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002558
Damien Miller5428f641999-11-25 11:54:57 +11002559 /*
2560 * Check for mail if we have a tty and it was enabled
2561 * in server options.
2562 */
Damien Miller95def091999-11-25 00:26:21 +11002563 if (ttyname && options.check_mail) {
2564 char *mailbox;
2565 struct stat mailstat;
2566 mailbox = getenv("MAIL");
2567 if (mailbox != NULL) {
2568 if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
2569 printf("No mail.\n");
2570 else if (mailstat.st_mtime < mailstat.st_atime)
2571 printf("You have mail.\n");
2572 else
2573 printf("You have new mail.\n");
2574 }
2575 }
2576 /* Start the shell. Set initial character to '-'. */
2577 buf[0] = '-';
2578 strncpy(buf + 1, cp, sizeof(buf) - 1);
2579 buf[sizeof(buf) - 1] = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002580
Damien Miller95def091999-11-25 00:26:21 +11002581 /* Execute the shell. */
2582 argv[0] = buf;
2583 argv[1] = NULL;
2584 execve(shell, argv, env);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002585
Damien Miller95def091999-11-25 00:26:21 +11002586 /* Executing the shell failed. */
2587 perror(shell);
2588 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002589
Damien Miller95def091999-11-25 00:26:21 +11002590 } else {
2591 /* Launch login(1). */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002592
Damien Miller95def091999-11-25 00:26:21 +11002593 execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(),
2594 "-p", "-f", "--", pw->pw_name, NULL);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002595
Damien Miller95def091999-11-25 00:26:21 +11002596 /* Login couldn't be executed, die. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002597
Damien Miller95def091999-11-25 00:26:21 +11002598 perror("login");
2599 exit(1);
2600 }
2601 }
Damien Miller5428f641999-11-25 11:54:57 +11002602 /*
2603 * Execute the command using the user's shell. This uses the -c
2604 * option to execute the command.
2605 */
Damien Miller95def091999-11-25 00:26:21 +11002606 argv[0] = (char *) cp;
2607 argv[1] = "-c";
2608 argv[2] = (char *) command;
2609 argv[3] = NULL;
2610 execve(shell, argv, env);
2611 perror(shell);
2612 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002613}