blob: 60d34d8b65c5129c095fc32f4fa1f260dc748100 [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 Millereabf3411999-12-07 14:56:27 +110014RCSID("$Id: sshd.c,v 1.34 1999/12/07 03:56:27 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 Miller95def091999-11-25 00:26:21 +110048/*
49 * Debug mode flag. This can be set on the command line. If debug
50 * mode is enabled, extra debugging output will be sent to the system
51 * log, the daemon will not go to background, and will exit after processing
52 * the first connection.
53 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100054int debug_flag = 0;
55
56/* Flag indicating that the daemon is being started from inetd. */
57int inetd_flag = 0;
58
Damien Miller5ce662a1999-11-11 17:57:39 +110059/* debug goes to stderr unless inetd_flag is set */
60int log_stderr = 0;
61
Damien Millerd4a8b7e1999-10-27 13:42:43 +100062/* argv[0] without path. */
63char *av0;
64
65/* Saved arguments to main(). */
66char **saved_argv;
67
Damien Miller5428f641999-11-25 11:54:57 +110068/*
69 * This is set to the socket that the server is listening; this is used in
70 * the SIGHUP signal handler.
71 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100072int listen_sock;
73
Damien Miller5428f641999-11-25 11:54:57 +110074/*
75 * the client's version string, passed by sshd2 in compat mode. if != NULL,
76 * sshd will skip the version-number exchange
77 */
Damien Miller95def091999-11-25 00:26:21 +110078char *client_version_string = NULL;
79
80/* Flags set in auth-rsa from authorized_keys flags. These are set in auth-rsa.c. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100081int no_port_forwarding_flag = 0;
82int no_agent_forwarding_flag = 0;
83int no_x11_forwarding_flag = 0;
84int no_pty_flag = 0;
Damien Miller95def091999-11-25 00:26:21 +110085
86/* RSA authentication "command=" option. */
87char *forced_command = NULL;
88
89/* RSA authentication "environment=" options. */
90struct envstring *custom_environment = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +100091
92/* Session id for the current session. */
93unsigned char session_id[16];
94
Damien Miller5428f641999-11-25 11:54:57 +110095/*
96 * Any really sensitive data in the application is contained in this
97 * structure. The idea is that this structure could be locked into memory so
98 * that the pages do not get written into swap. However, there are some
99 * problems. The private key contains BIGNUMs, and we do not (in principle)
100 * have access to the internals of them, and locking just the structure is
101 * not very useful. Currently, memory locking is not implemented.
102 */
Damien Miller95def091999-11-25 00:26:21 +1100103struct {
104 RSA *private_key; /* Private part of server key. */
105 RSA *host_key; /* Private part of host key. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000106} sensitive_data;
107
Damien Miller5428f641999-11-25 11:54:57 +1100108/*
109 * Flag indicating whether the current session key has been used. This flag
110 * is set whenever the key is used, and cleared when the key is regenerated.
111 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000112int key_used = 0;
113
114/* This is set to true when SIGHUP is received. */
115int received_sighup = 0;
116
117/* Public side of the server key. This value is regenerated regularly with
118 the private key. */
119RSA *public_key;
120
121/* Prototypes for various functions defined later in this file. */
Damien Miller2ccf6611999-11-15 15:25:10 +1100122void do_connection();
123void do_authentication(char *user);
Damien Miller95def091999-11-25 00:26:21 +1100124void do_authloop(struct passwd * pw);
Damien Miller2ccf6611999-11-15 15:25:10 +1100125void do_fake_authloop(char *user);
Damien Miller95def091999-11-25 00:26:21 +1100126void do_authenticated(struct passwd * pw);
127void do_exec_pty(const char *command, int ptyfd, int ttyfd,
128 const char *ttyname, struct passwd * pw, const char *term,
129 const char *display, const char *auth_proto,
130 const char *auth_data);
131void do_exec_no_pty(const char *command, struct passwd * pw,
132 const char *display, const char *auth_proto,
133 const char *auth_data);
134void do_child(const char *command, struct passwd * pw, const char *term,
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000135 const char *display, const char *auth_proto,
136 const char *auth_data, const char *ttyname);
Damien Miller2ccf6611999-11-15 15:25:10 +1100137
Damien Miller06230761999-10-28 14:03:14 +1000138#ifdef HAVE_LIBPAM
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000139static int pamconv(int num_msg, const struct pam_message **msg,
Damien Miller95def091999-11-25 00:26:21 +1100140 struct pam_response **resp, void *appdata_ptr);
Damien Millerdc33fc31999-12-04 20:24:48 +1100141void do_pam_account_and_session(char *username, char *remote_user);
Damien Miller332e67f1999-10-27 23:42:05 +1000142void pam_cleanup_proc(void *context);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000143
144static struct pam_conv conv = {
Damien Miller95def091999-11-25 00:26:21 +1100145 pamconv,
146 NULL
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000147};
Damien Miller332e67f1999-10-27 23:42:05 +1000148struct pam_handle_t *pamh = NULL;
149const char *pampasswd = NULL;
Damien Miller356a0b01999-11-08 15:30:59 +1100150char *pamconv_msg = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000151
152static int pamconv(int num_msg, const struct pam_message **msg,
Damien Miller9072e181999-11-25 10:42:08 +1100153 struct pam_response **resp, void *appdata_ptr)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000154{
Damien Miller95def091999-11-25 00:26:21 +1100155 struct pam_response *reply;
156 int count;
157 size_t msg_len;
158 char *p;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000159
Damien Miller95def091999-11-25 00:26:21 +1100160 /* PAM will free this later */
161 reply = malloc(num_msg * sizeof(*reply));
162 if (reply == NULL)
163 return PAM_CONV_ERR;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000164
Damien Miller95def091999-11-25 00:26:21 +1100165 for(count = 0; count < num_msg; count++) {
166 switch (msg[count]->msg_style) {
167 case PAM_PROMPT_ECHO_OFF:
168 if (pampasswd == NULL) {
169 free(reply);
170 return PAM_CONV_ERR;
171 }
172 reply[count].resp_retcode = PAM_SUCCESS;
173 reply[count].resp = xstrdup(pampasswd);
174 break;
Damien Miller5bbbd361999-11-19 07:56:21 +1100175
Damien Miller95def091999-11-25 00:26:21 +1100176 case PAM_TEXT_INFO:
177 reply[count].resp_retcode = PAM_SUCCESS;
178 reply[count].resp = xstrdup("");
179
180 if (msg[count]->msg == NULL)
181 break;
182
183 debug("Adding PAM message: %s", msg[count]->msg);
184
185 msg_len = strlen(msg[count]->msg);
186 if (pamconv_msg) {
187 size_t n = strlen(pamconv_msg);
188 pamconv_msg = xrealloc(pamconv_msg, n + msg_len + 2);
189 p = pamconv_msg + n;
190 } else {
191 pamconv_msg = p = xmalloc(msg_len + 2);
192 }
193 memcpy(p, msg[count]->msg, msg_len);
194 p[msg_len] = '\n';
195 p[msg_len + 1] = '\0';
196 break;
197
198 case PAM_PROMPT_ECHO_ON:
199 case PAM_ERROR_MSG:
200 default:
201 free(reply);
202 return PAM_CONV_ERR;
203 }
Damien Miller356a0b01999-11-08 15:30:59 +1100204 }
Damien Miller332e67f1999-10-27 23:42:05 +1000205
Damien Miller95def091999-11-25 00:26:21 +1100206 *resp = reply;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000207
Damien Miller95def091999-11-25 00:26:21 +1100208 return PAM_SUCCESS;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000209}
210
211void pam_cleanup_proc(void *context)
212{
Damien Miller95def091999-11-25 00:26:21 +1100213 int pam_retval;
214
215 if (pamh != NULL)
216 {
217 pam_retval = pam_close_session((pam_handle_t *)pamh, 0);
218 if (pam_retval != PAM_SUCCESS) {
219 log("Cannot close PAM session: %.200s",
220 PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
221 }
222
223 pam_retval = pam_end((pam_handle_t *)pamh, pam_retval);
224 if (pam_retval != PAM_SUCCESS) {
225 log("Cannot release PAM authentication: %.200s",
226 PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
227 }
228 }
Damien Miller332e67f1999-10-27 23:42:05 +1000229}
230
Damien Millerdc33fc31999-12-04 20:24:48 +1100231void do_pam_account_and_session(char *username, char *remote_user)
Damien Miller332e67f1999-10-27 23:42:05 +1000232{
Damien Miller95def091999-11-25 00:26:21 +1100233 int pam_retval;
Damien Miller332e67f1999-10-27 23:42:05 +1000234
Damien Millerdc33fc31999-12-04 20:24:48 +1100235 debug("PAM setting rhost to \"%.200s\"", get_canonical_hostname());
236 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RHOST,
237 get_canonical_hostname());
238 if (pam_retval != PAM_SUCCESS) {
239 log("PAM set rhost failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
240 do_fake_authloop(username);
Damien Miller95def091999-11-25 00:26:21 +1100241 }
242
243 if (remote_user != NULL) {
244 debug("PAM setting ruser to \"%.200s\"", remote_user);
245 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RUSER, remote_user);
246 if (pam_retval != PAM_SUCCESS) {
247 log("PAM set ruser failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
248 do_fake_authloop(username);
249 }
250 }
251
252 pam_retval = pam_acct_mgmt((pam_handle_t *)pamh, 0);
253 if (pam_retval != PAM_SUCCESS) {
254 log("PAM rejected by account configuration: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
255 do_fake_authloop(username);
256 }
257
258 pam_retval = pam_open_session((pam_handle_t *)pamh, 0);
259 if (pam_retval != PAM_SUCCESS) {
260 log("PAM session setup failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
261 do_fake_authloop(username);
262 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000263}
Damien Miller06230761999-10-28 14:03:14 +1000264#endif /* HAVE_LIBPAM */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000265
Damien Miller95def091999-11-25 00:26:21 +1100266/*
267 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
268 * the effect is to reread the configuration file (and to regenerate
269 * the server key).
270 */
271void
272sighup_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000273{
Damien Miller95def091999-11-25 00:26:21 +1100274 received_sighup = 1;
275 signal(SIGHUP, sighup_handler);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000276}
277
Damien Miller95def091999-11-25 00:26:21 +1100278/*
279 * Called from the main program after receiving SIGHUP.
280 * Restarts the server.
281 */
282void
283sighup_restart()
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000284{
Damien Miller95def091999-11-25 00:26:21 +1100285 log("Received SIGHUP; restarting.");
286 close(listen_sock);
287 execv(saved_argv[0], saved_argv);
288 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
289 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000290}
291
Damien Miller95def091999-11-25 00:26:21 +1100292/*
293 * Generic signal handler for terminating signals in the master daemon.
294 * These close the listen socket; not closing it seems to cause "Address
295 * already in use" problems on some machines, which is inconvenient.
296 */
297void
298sigterm_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000299{
Damien Miller95def091999-11-25 00:26:21 +1100300 log("Received signal %d; terminating.", sig);
301 close(listen_sock);
302 exit(255);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000303}
304
Damien Miller95def091999-11-25 00:26:21 +1100305/*
306 * SIGCHLD handler. This is called whenever a child dies. This will then
307 * reap any zombies left by exited c.
308 */
309void
310main_sigchld_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000311{
Damien Miller95def091999-11-25 00:26:21 +1100312 int save_errno = errno;
313 int status;
Damien Miller431f66b1999-11-21 18:31:57 +1100314
Damien Miller95def091999-11-25 00:26:21 +1100315 while (waitpid(-1, &status, WNOHANG) > 0)
316 ;
Damien Miller431f66b1999-11-21 18:31:57 +1100317
Damien Miller95def091999-11-25 00:26:21 +1100318 signal(SIGCHLD, main_sigchld_handler);
319 errno = save_errno;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000320}
321
Damien Miller95def091999-11-25 00:26:21 +1100322/*
323 * Signal handler for the alarm after the login grace period has expired.
324 */
325void
326grace_alarm_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000327{
Damien Miller95def091999-11-25 00:26:21 +1100328 /* Close the connection. */
329 packet_close();
330
331 /* Log error and exit. */
332 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000333}
334
Damien Miller95def091999-11-25 00:26:21 +1100335/*
336 * convert ssh auth msg type into description
337 */
338char *
339get_authname(int type)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000340{
Damien Miller95def091999-11-25 00:26:21 +1100341 switch (type) {
342 case SSH_CMSG_AUTH_PASSWORD:
343 return "password";
344 case SSH_CMSG_AUTH_RSA:
345 return "rsa";
346 case SSH_CMSG_AUTH_RHOSTS_RSA:
347 return "rhosts-rsa";
348 case SSH_CMSG_AUTH_RHOSTS:
349 return "rhosts";
350#ifdef KRB4
351 case SSH_CMSG_AUTH_KERBEROS:
352 return "kerberos";
353#endif
354#ifdef SKEY
355 case SSH_CMSG_AUTH_TIS_RESPONSE:
356 return "s/key";
357#endif
358 }
359 fatal("get_authname: unknown auth %d: internal error", type);
360 return NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000361}
362
Damien Miller95def091999-11-25 00:26:21 +1100363/*
364 * Signal handler for the key regeneration alarm. Note that this
365 * alarm only occurs in the daemon waiting for connections, and it does not
366 * do anything with the private key or random state before forking.
367 * Thus there should be no concurrency control/asynchronous execution
368 * problems.
369 */
370void
371key_regeneration_alarm(int sig)
372{
373 int save_errno = errno;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000374
Damien Miller95def091999-11-25 00:26:21 +1100375 /* Check if we should generate a new key. */
376 if (key_used) {
377 /* This should really be done in the background. */
378 log("Generating new %d bit RSA key.", options.server_key_bits);
379
380 if (sensitive_data.private_key != NULL)
381 RSA_free(sensitive_data.private_key);
382 sensitive_data.private_key = RSA_new();
383
384 if (public_key != NULL)
385 RSA_free(public_key);
386 public_key = RSA_new();
387
388 rsa_generate_key(sensitive_data.private_key, public_key,
389 options.server_key_bits);
390 arc4random_stir();
391 key_used = 0;
392 log("RSA key generation complete.");
393 }
394 /* Reschedule the alarm. */
395 signal(SIGALRM, key_regeneration_alarm);
396 alarm(options.key_regeneration_time);
397 errno = save_errno;
398}
399
400/*
401 * Main program for the daemon.
402 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000403int
404main(int ac, char **av)
405{
Damien Miller95def091999-11-25 00:26:21 +1100406 extern char *optarg;
407 extern int optind;
408 int opt, aux, sock_in, sock_out, newsock, i, pid, on = 1;
409 int remote_major, remote_minor;
410 int silentrsa = 0;
411 struct sockaddr_in sin;
412 char buf[100]; /* Must not be larger than remote_version. */
413 char remote_version[100]; /* Must be at least as big as buf. */
414 const char *remote_ip;
415 int remote_port;
416 char *comment;
417 FILE *f;
418 struct linger linger;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000419
Damien Miller95def091999-11-25 00:26:21 +1100420 /* Save argv[0]. */
421 saved_argv = av;
422 if (strchr(av[0], '/'))
423 av0 = strrchr(av[0], '/') + 1;
424 else
425 av0 = av[0];
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000426
Damien Miller95def091999-11-25 00:26:21 +1100427 /* Initialize configuration options to their default values. */
428 initialize_server_options(&options);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000429
Damien Miller95def091999-11-25 00:26:21 +1100430 /* Parse command-line arguments. */
431 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ")) != EOF) {
432 switch (opt) {
433 case 'f':
434 config_file_name = optarg;
435 break;
436 case 'd':
437 debug_flag = 1;
438 options.log_level = SYSLOG_LEVEL_DEBUG;
439 break;
440 case 'i':
441 inetd_flag = 1;
442 break;
443 case 'Q':
444 silentrsa = 1;
445 break;
446 case 'q':
447 options.log_level = SYSLOG_LEVEL_QUIET;
448 break;
449 case 'b':
450 options.server_key_bits = atoi(optarg);
451 break;
452 case 'p':
453 options.port = atoi(optarg);
454 break;
455 case 'g':
456 options.login_grace_time = atoi(optarg);
457 break;
458 case 'k':
459 options.key_regeneration_time = atoi(optarg);
460 break;
461 case 'h':
462 options.host_key_file = optarg;
463 break;
464 case 'V':
465 client_version_string = optarg;
466 /* only makes sense with inetd_flag, i.e. no listen() */
467 inetd_flag = 1;
468 break;
469 case '?':
470 default:
471 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
472 fprintf(stderr, "Usage: %s [options]\n", av0);
473 fprintf(stderr, "Options:\n");
Damien Miller5428f641999-11-25 11:54:57 +1100474 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE);
Damien Miller95def091999-11-25 00:26:21 +1100475 fprintf(stderr, " -d Debugging mode\n");
476 fprintf(stderr, " -i Started from inetd\n");
477 fprintf(stderr, " -q Quiet (no logging)\n");
478 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
479 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
480 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
481 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
482 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
483 HOST_KEY_FILE);
484 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000485 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000486 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000487
Damien Miller95def091999-11-25 00:26:21 +1100488 /* check if RSA support exists */
489 if (rsa_alive() == 0) {
490 if (silentrsa == 0)
491 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
492 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
493 exit(1);
494 }
495 /* Read server configuration options from the configuration file. */
496 read_server_config(&options, config_file_name);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000497
Damien Miller95def091999-11-25 00:26:21 +1100498 /* Fill in default values for those options not explicitly set. */
499 fill_default_server_options(&options);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000500
Damien Miller95def091999-11-25 00:26:21 +1100501 /* Check certain values for sanity. */
502 if (options.server_key_bits < 512 ||
503 options.server_key_bits > 32768) {
504 fprintf(stderr, "Bad server key size.\n");
505 exit(1);
506 }
507 if (options.port < 1 || options.port > 65535) {
508 fprintf(stderr, "Bad port number.\n");
509 exit(1);
510 }
511 /* Check that there are no remaining arguments. */
512 if (optind < ac) {
513 fprintf(stderr, "Extra argument %s.\n", av[optind]);
514 exit(1);
515 }
516 /* Force logging to stderr while loading the private host key
517 unless started from inetd */
518 log_init(av0, options.log_level, options.log_facility, !inetd_flag);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000519
Damien Miller95def091999-11-25 00:26:21 +1100520 debug("sshd version %.100s", SSH_VERSION);
Damien Miller2ccf6611999-11-15 15:25:10 +1100521
Damien Miller95def091999-11-25 00:26:21 +1100522 sensitive_data.host_key = RSA_new();
523 errno = 0;
524 /* Load the host key. It must have empty passphrase. */
525 if (!load_private_key(options.host_key_file, "",
526 sensitive_data.host_key, &comment)) {
527 error("Could not load host key: %.200s: %.100s",
528 options.host_key_file, strerror(errno));
529 exit(1);
530 }
531 xfree(comment);
532
533 /* Initialize the log (it is reinitialized below in case we
534 forked). */
535 if (debug_flag && !inetd_flag)
536 log_stderr = 1;
537 log_init(av0, options.log_level, options.log_facility, log_stderr);
538
539 /* If not in debugging mode, and not started from inetd,
540 disconnect from the controlling terminal, and fork. The
541 original process exits. */
542 if (!debug_flag && !inetd_flag) {
543#ifdef TIOCNOTTY
544 int fd;
545#endif /* TIOCNOTTY */
546 if (daemon(0, 0) < 0)
547 fatal("daemon() failed: %.200s", strerror(errno));
548
549 /* Disconnect from the controlling tty. */
550#ifdef TIOCNOTTY
551 fd = open("/dev/tty", O_RDWR | O_NOCTTY);
552 if (fd >= 0) {
553 (void) ioctl(fd, TIOCNOTTY, NULL);
554 close(fd);
555 }
556#endif /* TIOCNOTTY */
557 }
558 /* Reinitialize the log (because of the fork above). */
559 log_init(av0, options.log_level, options.log_facility, log_stderr);
560
561 /* Check that server and host key lengths differ sufficiently.
562 This is necessary to make double encryption work with rsaref.
563 Oh, I hate software patents. I dont know if this can go? Niels */
564 if (options.server_key_bits >
565 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
566 options.server_key_bits <
567 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
568 options.server_key_bits =
569 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
570 debug("Forcing server key to %d bits to make it differ from host key.",
571 options.server_key_bits);
572 }
573 /* Do not display messages to stdout in RSA code. */
574 rsa_set_verbose(0);
575
576 /* Initialize the random number generator. */
577 arc4random_stir();
578
579 /* Chdir to the root directory so that the current disk can be
580 unmounted if desired. */
581 chdir("/");
582
583 /* Close connection cleanly after attack. */
584 cipher_attack_detected = packet_disconnect;
585
586 /* Start listening for a socket, unless started from inetd. */
587 if (inetd_flag) {
588 int s1, s2;
589 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
590 s2 = dup(s1);
591 sock_in = dup(0);
592 sock_out = dup(1);
593 /* We intentionally do not close the descriptors 0, 1, and 2
594 as our code for setting the descriptors won\'t work
595 if ttyfd happens to be one of those. */
596 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
597
598 public_key = RSA_new();
599 sensitive_data.private_key = RSA_new();
600
601 log("Generating %d bit RSA key.", options.server_key_bits);
602 rsa_generate_key(sensitive_data.private_key, public_key,
603 options.server_key_bits);
604 arc4random_stir();
605 log("RSA key generation complete.");
606 } else {
607 /* Create socket for listening. */
608 listen_sock = socket(AF_INET, SOCK_STREAM, 0);
609 if (listen_sock < 0)
610 fatal("socket: %.100s", strerror(errno));
611
612 /* Set socket options. We try to make the port reusable
613 and have it close as fast as possible without waiting
614 in unnecessary wait states on close. */
615 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on,
616 sizeof(on));
617 linger.l_onoff = 1;
618 linger.l_linger = 5;
619 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, (void *) &linger,
620 sizeof(linger));
621
Damien Miller95def091999-11-25 00:26:21 +1100622 memset(&sin, 0, sizeof(sin));
623 sin.sin_family = AF_INET;
624 sin.sin_addr = options.listen_addr;
625 sin.sin_port = htons(options.port);
626
Damien Miller95def091999-11-25 00:26:21 +1100627 if (bind(listen_sock, (struct sockaddr *) & sin, sizeof(sin)) < 0) {
628 error("bind: %.100s", strerror(errno));
629 shutdown(listen_sock, SHUT_RDWR);
630 close(listen_sock);
631 fatal("Bind to port %d failed.", options.port);
632 }
633 if (!debug_flag) {
Damien Miller5428f641999-11-25 11:54:57 +1100634 /*
635 * Record our pid in /etc/sshd_pid to make it easier
636 * to kill the correct sshd. We don\'t want to do
637 * this before the bind above because the bind will
638 * fail if there already is a daemon, and this will
639 * overwrite any old pid in the file.
640 */
Damien Miller95def091999-11-25 00:26:21 +1100641 f = fopen(SSH_DAEMON_PID_FILE, "w");
642 if (f) {
643 fprintf(f, "%u\n", (unsigned int) getpid());
644 fclose(f);
645 }
646 }
647
648 log("Server listening on port %d.", options.port);
649 if (listen(listen_sock, 5) < 0)
650 fatal("listen: %.100s", strerror(errno));
651
652 public_key = RSA_new();
653 sensitive_data.private_key = RSA_new();
654
655 log("Generating %d bit RSA key.", options.server_key_bits);
656 rsa_generate_key(sensitive_data.private_key, public_key,
657 options.server_key_bits);
658 arc4random_stir();
659 log("RSA key generation complete.");
660
661 /* Schedule server key regeneration alarm. */
662 signal(SIGALRM, key_regeneration_alarm);
663 alarm(options.key_regeneration_time);
664
665 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
666 signal(SIGHUP, sighup_handler);
667 signal(SIGTERM, sigterm_handler);
668 signal(SIGQUIT, sigterm_handler);
669
670 /* Arrange SIGCHLD to be caught. */
671 signal(SIGCHLD, main_sigchld_handler);
672
Damien Miller5428f641999-11-25 11:54:57 +1100673 /*
674 * Stay listening for connections until the system crashes or
675 * the daemon is killed with a signal.
676 */
Damien Miller95def091999-11-25 00:26:21 +1100677 for (;;) {
678 if (received_sighup)
679 sighup_restart();
680 /* Wait in accept until there is a connection. */
681 aux = sizeof(sin);
682 newsock = accept(listen_sock, (struct sockaddr *) & sin, &aux);
683 if (received_sighup)
684 sighup_restart();
685 if (newsock < 0) {
686 if (errno == EINTR)
687 continue;
688 error("accept: %.100s", strerror(errno));
689 continue;
690 }
Damien Miller5428f641999-11-25 11:54:57 +1100691 /*
692 * Got connection. Fork a child to handle it, unless
693 * we are in debugging mode.
694 */
Damien Miller95def091999-11-25 00:26:21 +1100695 if (debug_flag) {
Damien Miller5428f641999-11-25 11:54:57 +1100696 /*
697 * In debugging mode. Close the listening
698 * socket, and start processing the
699 * connection without forking.
700 */
Damien Miller95def091999-11-25 00:26:21 +1100701 debug("Server will not fork when running in debugging mode.");
702 close(listen_sock);
703 sock_in = newsock;
704 sock_out = newsock;
705 pid = getpid();
706 break;
707 } else {
Damien Miller5428f641999-11-25 11:54:57 +1100708 /*
709 * Normal production daemon. Fork, and have
710 * the child process the connection. The
711 * parent continues listening.
712 */
Damien Miller95def091999-11-25 00:26:21 +1100713 if ((pid = fork()) == 0) {
Damien Miller5428f641999-11-25 11:54:57 +1100714 /*
715 * Child. Close the listening socket, and start using the
716 * accepted socket. Reinitialize logging (since our pid has
717 * changed). We break out of the loop to handle the connection.
718 */
Damien Miller95def091999-11-25 00:26:21 +1100719 close(listen_sock);
720 sock_in = newsock;
721 sock_out = newsock;
722 log_init(av0, options.log_level, options.log_facility, log_stderr);
723 break;
724 }
725 }
726
727 /* Parent. Stay in the loop. */
728 if (pid < 0)
729 error("fork: %.100s", strerror(errno));
730 else
731 debug("Forked child %d.", pid);
732
733 /* Mark that the key has been used (it was "given" to the child). */
734 key_used = 1;
735
736 arc4random_stir();
737
738 /* Close the new socket (the child is now taking care of it). */
739 close(newsock);
740 }
741 }
742
743 /* This is the child processing a new connection. */
744
Damien Miller5428f641999-11-25 11:54:57 +1100745 /*
746 * Disable the key regeneration alarm. We will not regenerate the
747 * key since we are no longer in a position to give it to anyone. We
748 * will not restart on SIGHUP since it no longer makes sense.
749 */
Damien Miller95def091999-11-25 00:26:21 +1100750 alarm(0);
751 signal(SIGALRM, SIG_DFL);
752 signal(SIGHUP, SIG_DFL);
753 signal(SIGTERM, SIG_DFL);
754 signal(SIGQUIT, SIG_DFL);
755 signal(SIGCHLD, SIG_DFL);
756
Damien Miller5428f641999-11-25 11:54:57 +1100757 /*
758 * Set socket options for the connection. We want the socket to
759 * close as fast as possible without waiting for anything. If the
760 * connection is not a socket, these will do nothing.
761 */
762 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
Damien Miller95def091999-11-25 00:26:21 +1100763 linger.l_onoff = 1;
764 linger.l_linger = 5;
765 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
766
Damien Miller5428f641999-11-25 11:54:57 +1100767 /*
768 * Register our connection. This turns encryption off because we do
769 * not have a key.
770 */
Damien Miller95def091999-11-25 00:26:21 +1100771 packet_set_connection(sock_in, sock_out);
772
773 remote_port = get_remote_port();
774 remote_ip = get_remote_ipaddr();
775
776 /* Check whether logins are denied from this host. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000777#ifdef LIBWRAP
Damien Miller95def091999-11-25 00:26:21 +1100778 {
779 struct request_info req;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000780
Damien Miller95def091999-11-25 00:26:21 +1100781 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
782 fromhost(&req);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000783
Damien Miller95def091999-11-25 00:26:21 +1100784 if (!hosts_access(&req)) {
785 close(sock_in);
786 close(sock_out);
787 refuse(&req);
788 }
789 verbose("Connection from %.500s port %d", eval_client(&req), remote_port);
790 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000791#else
Damien Miller95def091999-11-25 00:26:21 +1100792 /* Log the connection. */
793 verbose("Connection from %.500s port %d", remote_ip, remote_port);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000794#endif /* LIBWRAP */
795
Damien Miller5428f641999-11-25 11:54:57 +1100796 /*
797 * We don\'t want to listen forever unless the other side
798 * successfully authenticates itself. So we set up an alarm which is
799 * cleared after successful authentication. A limit of zero
800 * indicates no limit. Note that we don\'t set the alarm in debugging
801 * mode; it is just annoying to have the server exit just when you
802 * are about to discover the bug.
803 */
Damien Miller95def091999-11-25 00:26:21 +1100804 signal(SIGALRM, grace_alarm_handler);
805 if (!debug_flag)
806 alarm(options.login_grace_time);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000807
Damien Miller95def091999-11-25 00:26:21 +1100808 if (client_version_string != NULL) {
809 /* we are exec'ed by sshd2, so skip exchange of protocol version */
810 strlcpy(buf, client_version_string, sizeof(buf));
811 } else {
812 /* Send our protocol version identification. */
813 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
814 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
815 if (write(sock_out, buf, strlen(buf)) != strlen(buf))
816 fatal("Could not write ident string to %s.", get_remote_ipaddr());
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000817
Damien Miller95def091999-11-25 00:26:21 +1100818 /* Read other side\'s version identification. */
819 for (i = 0; i < sizeof(buf) - 1; i++) {
820 if (read(sock_in, &buf[i], 1) != 1)
821 fatal("Did not receive ident string from %s.", get_remote_ipaddr());
822 if (buf[i] == '\r') {
823 buf[i] = '\n';
824 buf[i + 1] = 0;
825 break;
826 }
827 if (buf[i] == '\n') {
828 /* buf[i] == '\n' */
829 buf[i + 1] = 0;
830 break;
831 }
832 }
833 buf[sizeof(buf) - 1] = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000834 }
Damien Miller95def091999-11-25 00:26:21 +1100835
Damien Miller5428f641999-11-25 11:54:57 +1100836 /*
837 * Check that the versions match. In future this might accept
838 * several versions and set appropriate flags to handle them.
839 */
Damien Miller95def091999-11-25 00:26:21 +1100840 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
841 remote_version) != 3) {
842 const char *s = "Protocol mismatch.\n";
843 (void) write(sock_out, s, strlen(s));
844 close(sock_in);
845 close(sock_out);
846 fatal("Bad protocol version identification '%.100s' from %s",
847 buf, get_remote_ipaddr());
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000848 }
Damien Miller95def091999-11-25 00:26:21 +1100849 debug("Client protocol version %d.%d; client software version %.100s",
850 remote_major, remote_minor, remote_version);
851 if (remote_major != PROTOCOL_MAJOR) {
852 const char *s = "Protocol major versions differ.\n";
853 (void) write(sock_out, s, strlen(s));
854 close(sock_in);
855 close(sock_out);
856 fatal("Protocol major versions differ for %s: %d vs. %d",
857 get_remote_ipaddr(),
858 PROTOCOL_MAJOR, remote_major);
859 }
860 /* Check that the client has sufficiently high software version. */
861 if (remote_major == 1 && remote_minor < 3)
862 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 +1000863
Damien Miller95def091999-11-25 00:26:21 +1100864 if (remote_major == 1 && remote_minor == 3) {
865 enable_compat13();
866 if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
867 debug("Agent forwarding disabled, remote version is not compatible.");
868 no_agent_forwarding_flag = 1;
869 }
870 }
Damien Miller5428f641999-11-25 11:54:57 +1100871 /*
872 * Check that the connection comes from a privileged port. Rhosts-
873 * and Rhosts-RSA-Authentication only make sense from priviledged
874 * programs. Of course, if the intruder has root access on his local
875 * machine, he can connect from any port. So do not use these
876 * authentication methods from machines that you do not trust.
877 */
Damien Miller95def091999-11-25 00:26:21 +1100878 if (remote_port >= IPPORT_RESERVED ||
879 remote_port < IPPORT_RESERVED / 2) {
880 options.rhosts_authentication = 0;
881 options.rhosts_rsa_authentication = 0;
882 }
883 packet_set_nonblocking();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000884
Damien Miller95def091999-11-25 00:26:21 +1100885 /* Handle the connection. */
886 do_connection();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000887
888#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +1100889 /* Cleanup user's ticket cache file. */
890 if (options.kerberos_ticket_cleanup)
891 (void) dest_tkt();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000892#endif /* KRB4 */
893
Damien Miller95def091999-11-25 00:26:21 +1100894 /* Cleanup user's local Xauthority file. */
895 if (xauthfile)
896 unlink(xauthfile);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000897
Damien Miller95def091999-11-25 00:26:21 +1100898 /* The connection has been terminated. */
899 verbose("Closing connection to %.100s", remote_ip);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000900
Damien Miller06230761999-10-28 14:03:14 +1000901#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +1100902 {
903 int retval;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000904
Damien Miller95def091999-11-25 00:26:21 +1100905 if (pamh != NULL) {
906 debug("Closing PAM session.");
907 retval = pam_close_session((pam_handle_t *)pamh, 0);
908
909 debug("Terminating PAM library.");
910 if (pam_end((pam_handle_t *)pamh, retval) != PAM_SUCCESS)
911 log("Cannot release PAM authentication.");
912
913 fatal_remove_cleanup(&pam_cleanup_proc, NULL);
914 }
915 }
Damien Miller06230761999-10-28 14:03:14 +1000916#endif /* HAVE_LIBPAM */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000917
Damien Miller95def091999-11-25 00:26:21 +1100918 packet_close();
919 exit(0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000920}
921
Damien Miller95def091999-11-25 00:26:21 +1100922/*
923 * Process an incoming connection. Protocol version identifiers have already
924 * been exchanged. This sends server key and performs the key exchange.
925 * Server and host keys will no longer be needed after this functions.
926 */
Damien Miller2ccf6611999-11-15 15:25:10 +1100927void
928do_connection()
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000929{
Damien Miller95def091999-11-25 00:26:21 +1100930 int i, len;
931 BIGNUM *session_key_int;
932 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
933 unsigned char check_bytes[8];
934 char *user;
935 unsigned int cipher_type, auth_mask, protocol_flags;
936 int plen, slen;
937 u_int32_t rand = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000938
Damien Miller5428f641999-11-25 11:54:57 +1100939 /*
940 * Generate check bytes that the client must send back in the user
941 * packet in order for it to be accepted; this is used to defy ip
942 * spoofing attacks. Note that this only works against somebody
943 * doing IP spoofing from a remote machine; any machine on the local
944 * network can still see outgoing packets and catch the random
945 * cookie. This only affects rhosts authentication, and this is one
946 * of the reasons why it is inherently insecure.
947 */
Damien Miller95def091999-11-25 00:26:21 +1100948 for (i = 0; i < 8; i++) {
949 if (i % 4 == 0)
950 rand = arc4random();
951 check_bytes[i] = rand & 0xff;
952 rand >>= 8;
953 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000954
Damien Miller5428f641999-11-25 11:54:57 +1100955 /*
956 * Send our public key. We include in the packet 64 bits of random
957 * data that must be matched in the reply in order to prevent IP
958 * spoofing.
959 */
Damien Miller95def091999-11-25 00:26:21 +1100960 packet_start(SSH_SMSG_PUBLIC_KEY);
961 for (i = 0; i < 8; i++)
962 packet_put_char(check_bytes[i]);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000963
Damien Miller95def091999-11-25 00:26:21 +1100964 /* Store our public server RSA key. */
965 packet_put_int(BN_num_bits(public_key->n));
966 packet_put_bignum(public_key->e);
967 packet_put_bignum(public_key->n);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000968
Damien Miller95def091999-11-25 00:26:21 +1100969 /* Store our public host RSA key. */
970 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
971 packet_put_bignum(sensitive_data.host_key->e);
972 packet_put_bignum(sensitive_data.host_key->n);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000973
Damien Miller95def091999-11-25 00:26:21 +1100974 /* Put protocol flags. */
975 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000976
Damien Miller95def091999-11-25 00:26:21 +1100977 /* Declare which ciphers we support. */
978 packet_put_int(cipher_mask());
979
980 /* Declare supported authentication types. */
981 auth_mask = 0;
982 if (options.rhosts_authentication)
983 auth_mask |= 1 << SSH_AUTH_RHOSTS;
984 if (options.rhosts_rsa_authentication)
985 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
986 if (options.rsa_authentication)
987 auth_mask |= 1 << SSH_AUTH_RSA;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000988#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +1100989 if (options.kerberos_authentication)
990 auth_mask |= 1 << SSH_AUTH_KERBEROS;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000991#endif
992#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +1100993 if (options.kerberos_tgt_passing)
994 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
995 if (options.afs_token_passing)
996 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000997#endif
Damien Miller95def091999-11-25 00:26:21 +1100998#ifdef SKEY
999 if (options.skey_authentication == 1)
1000 auth_mask |= 1 << SSH_AUTH_TIS;
1001#endif
1002 if (options.password_authentication)
1003 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1004 packet_put_int(auth_mask);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001005
Damien Miller95def091999-11-25 00:26:21 +11001006 /* Send the packet and wait for it to be sent. */
1007 packet_send();
1008 packet_write_wait();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001009
Damien Miller95def091999-11-25 00:26:21 +11001010 debug("Sent %d bit public key and %d bit host key.",
1011 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001012
Damien Miller95def091999-11-25 00:26:21 +11001013 /* Read clients reply (cipher type and session key). */
1014 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001015
Damien Miller95def091999-11-25 00:26:21 +11001016 /* Get cipher type. */
1017 cipher_type = packet_get_char();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001018
Damien Miller95def091999-11-25 00:26:21 +11001019 /* Get check bytes from the packet. These must match those we
1020 sent earlier with the public key packet. */
1021 for (i = 0; i < 8; i++)
1022 if (check_bytes[i] != packet_get_char())
1023 packet_disconnect("IP Spoofing check bytes do not match.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001024
Damien Miller95def091999-11-25 00:26:21 +11001025 debug("Encryption type: %.200s", cipher_name(cipher_type));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001026
Damien Miller95def091999-11-25 00:26:21 +11001027 /* Get the encrypted integer. */
1028 session_key_int = BN_new();
1029 packet_get_bignum(session_key_int, &slen);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001030
Damien Miller95def091999-11-25 00:26:21 +11001031 protocol_flags = packet_get_int();
1032 packet_set_protocol_flags(protocol_flags);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001033
Damien Miller95def091999-11-25 00:26:21 +11001034 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001035
Damien Miller5428f641999-11-25 11:54:57 +11001036 /*
1037 * Decrypt it using our private server key and private host key (key
1038 * with larger modulus first).
1039 */
Damien Miller95def091999-11-25 00:26:21 +11001040 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1041 /* Private key has bigger modulus. */
1042 if (BN_num_bits(sensitive_data.private_key->n) <
1043 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1044 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1045 get_remote_ipaddr(),
1046 BN_num_bits(sensitive_data.private_key->n),
1047 BN_num_bits(sensitive_data.host_key->n),
1048 SSH_KEY_BITS_RESERVED);
1049 }
1050 rsa_private_decrypt(session_key_int, session_key_int,
1051 sensitive_data.private_key);
1052 rsa_private_decrypt(session_key_int, session_key_int,
1053 sensitive_data.host_key);
1054 } else {
1055 /* Host key has bigger modulus (or they are equal). */
1056 if (BN_num_bits(sensitive_data.host_key->n) <
1057 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1058 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1059 get_remote_ipaddr(),
1060 BN_num_bits(sensitive_data.host_key->n),
1061 BN_num_bits(sensitive_data.private_key->n),
1062 SSH_KEY_BITS_RESERVED);
1063 }
1064 rsa_private_decrypt(session_key_int, session_key_int,
1065 sensitive_data.host_key);
1066 rsa_private_decrypt(session_key_int, session_key_int,
1067 sensitive_data.private_key);
1068 }
Damien Miller356a0b01999-11-08 15:30:59 +11001069
Damien Miller95def091999-11-25 00:26:21 +11001070 compute_session_id(session_id, check_bytes,
1071 sensitive_data.host_key->n,
1072 sensitive_data.private_key->n);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001073
Damien Miller5428f641999-11-25 11:54:57 +11001074 /*
1075 * Extract session key from the decrypted integer. The key is in the
1076 * least significant 256 bits of the integer; the first byte of the
1077 * key is in the highest bits.
1078 */
Damien Miller95def091999-11-25 00:26:21 +11001079 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1080 len = BN_num_bytes(session_key_int);
1081 if (len < 0 || len > sizeof(session_key))
1082 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1083 get_remote_ipaddr(),
1084 len, sizeof(session_key));
1085 memset(session_key, 0, sizeof(session_key));
1086 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001087
Damien Miller95def091999-11-25 00:26:21 +11001088 /* Xor the first 16 bytes of the session key with the session id. */
1089 for (i = 0; i < 16; i++)
1090 session_key[i] ^= session_id[i];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001091
Damien Miller95def091999-11-25 00:26:21 +11001092 /* Destroy the decrypted integer. It is no longer needed. */
1093 BN_clear_free(session_key_int);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001094
Damien Miller95def091999-11-25 00:26:21 +11001095 /* Set the session key. From this on all communications will be encrypted. */
1096 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001097
Damien Miller95def091999-11-25 00:26:21 +11001098 /* Destroy our copy of the session key. It is no longer needed. */
1099 memset(session_key, 0, sizeof(session_key));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001100
Damien Miller95def091999-11-25 00:26:21 +11001101 debug("Received session key; encryption turned on.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001102
Damien Miller95def091999-11-25 00:26:21 +11001103 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1104 packet_start(SSH_SMSG_SUCCESS);
1105 packet_send();
1106 packet_write_wait();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001107
Damien Miller95def091999-11-25 00:26:21 +11001108 /* Get the name of the user that we wish to log in as. */
1109 packet_read_expect(&plen, SSH_CMSG_USER);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001110
Damien Miller95def091999-11-25 00:26:21 +11001111 /* Get the user name. */
1112 {
1113 int ulen;
1114 user = packet_get_string(&ulen);
1115 packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
1116 }
1117
1118 /* Destroy the private and public keys. They will no longer be needed. */
1119 RSA_free(public_key);
1120 RSA_free(sensitive_data.private_key);
1121 RSA_free(sensitive_data.host_key);
1122
1123 setproctitle("%s", user);
1124 /* Do the authentication. */
1125 do_authentication(user);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001126}
1127
Damien Miller95def091999-11-25 00:26:21 +11001128/*
1129 * Check if the user is allowed to log in via ssh. If user is listed in
1130 * DenyUsers or user's primary group is listed in DenyGroups, false will
1131 * be returned. If AllowUsers isn't empty and user isn't listed there, or
1132 * if AllowGroups isn't empty and user isn't listed there, false will be
1133 * returned. Otherwise true is returned.
1134 * XXX This function should also check if user has a valid shell
1135 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001136static int
Damien Miller95def091999-11-25 00:26:21 +11001137allowed_user(struct passwd * pw)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001138{
Damien Miller95def091999-11-25 00:26:21 +11001139 struct group *grp;
1140 int i;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001141
Damien Miller95def091999-11-25 00:26:21 +11001142 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1143 if (!pw)
1144 return 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001145
Damien Miller95def091999-11-25 00:26:21 +11001146 /* XXX Should check for valid login shell */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001147
Damien Miller95def091999-11-25 00:26:21 +11001148 /* Return false if user is listed in DenyUsers */
1149 if (options.num_deny_users > 0) {
1150 if (!pw->pw_name)
1151 return 0;
1152 for (i = 0; i < options.num_deny_users; i++)
1153 if (match_pattern(pw->pw_name, options.deny_users[i]))
1154 return 0;
1155 }
Damien Miller5428f641999-11-25 11:54:57 +11001156 /* Return false if AllowUsers isn't empty and user isn't listed there */
Damien Miller95def091999-11-25 00:26:21 +11001157 if (options.num_allow_users > 0) {
1158 if (!pw->pw_name)
1159 return 0;
1160 for (i = 0; i < options.num_allow_users; i++)
1161 if (match_pattern(pw->pw_name, options.allow_users[i]))
1162 break;
1163 /* i < options.num_allow_users iff we break for loop */
1164 if (i >= options.num_allow_users)
1165 return 0;
1166 }
1167 /* Get the primary group name if we need it. Return false if it fails */
1168 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
1169 grp = getgrgid(pw->pw_gid);
1170 if (!grp)
1171 return 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001172
Damien Miller95def091999-11-25 00:26:21 +11001173 /* Return false if user's group is listed in DenyGroups */
1174 if (options.num_deny_groups > 0) {
1175 if (!grp->gr_name)
1176 return 0;
1177 for (i = 0; i < options.num_deny_groups; i++)
1178 if (match_pattern(grp->gr_name, options.deny_groups[i]))
1179 return 0;
1180 }
Damien Miller5428f641999-11-25 11:54:57 +11001181 /*
1182 * Return false if AllowGroups isn't empty and user's group
1183 * isn't listed there
1184 */
Damien Miller95def091999-11-25 00:26:21 +11001185 if (options.num_allow_groups > 0) {
1186 if (!grp->gr_name)
1187 return 0;
1188 for (i = 0; i < options.num_allow_groups; i++)
1189 if (match_pattern(grp->gr_name, options.allow_groups[i]))
1190 break;
1191 /* i < options.num_allow_groups iff we break for
1192 loop */
1193 if (i >= options.num_allow_groups)
1194 return 0;
1195 }
1196 }
1197 /* We found no reason not to let this user try to log on... */
1198 return 1;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001199}
1200
Damien Miller95def091999-11-25 00:26:21 +11001201/*
1202 * Performs authentication of an incoming connection. Session key has already
1203 * been exchanged and encryption is enabled. User is the user name to log
1204 * in as (received from the client).
1205 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001206void
Damien Miller2ccf6611999-11-15 15:25:10 +11001207do_authentication(char *user)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001208{
Damien Miller95def091999-11-25 00:26:21 +11001209 struct passwd *pw, pwcopy;
Damien Miller2ccf6611999-11-15 15:25:10 +11001210
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001211#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11001212 /* If machine has AFS, set process authentication group. */
1213 if (k_hasafs()) {
1214 k_setpag();
1215 k_unlog();
1216 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001217#endif /* AFS */
Damien Miller95def091999-11-25 00:26:21 +11001218
1219 /* Verify that the user is a valid user. */
1220 pw = getpwnam(user);
1221 if (!pw || !allowed_user(pw))
1222 do_fake_authloop(user);
1223
1224 /* Take a copy of the returned structure. */
1225 memset(&pwcopy, 0, sizeof(pwcopy));
1226 pwcopy.pw_name = xstrdup(pw->pw_name);
1227 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1228 pwcopy.pw_uid = pw->pw_uid;
1229 pwcopy.pw_gid = pw->pw_gid;
1230 pwcopy.pw_dir = xstrdup(pw->pw_dir);
1231 pwcopy.pw_shell = xstrdup(pw->pw_shell);
1232 pw = &pwcopy;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001233
Damien Miller06230761999-10-28 14:03:14 +10001234#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001235 {
1236 int pam_retval;
Damien Miller2ccf6611999-11-15 15:25:10 +11001237
Damien Miller95def091999-11-25 00:26:21 +11001238 debug("Starting up PAM with username \"%.200s\"", pw->pw_name);
Damien Miller2ccf6611999-11-15 15:25:10 +11001239
Damien Miller95def091999-11-25 00:26:21 +11001240 pam_retval = pam_start("sshd", pw->pw_name, &conv, (pam_handle_t**)&pamh);
1241 if (pam_retval != PAM_SUCCESS)
1242 fatal("PAM initialisation failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
1243
1244 fatal_add_cleanup(&pam_cleanup_proc, NULL);
1245 }
Damien Miller06230761999-10-28 14:03:14 +10001246#endif
Damien Miller3d112ef1999-10-28 13:20:30 +10001247
Damien Miller5428f641999-11-25 11:54:57 +11001248 /*
1249 * If we are not running as root, the user must have the same uid as
1250 * the server.
1251 */
Damien Miller95def091999-11-25 00:26:21 +11001252 if (getuid() != 0 && pw->pw_uid != getuid())
1253 packet_disconnect("Cannot change user when server not running as root.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001254
Damien Miller95def091999-11-25 00:26:21 +11001255 debug("Attempting authentication for %.100s.", user);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001256
Damien Miller95def091999-11-25 00:26:21 +11001257 /* If the user has no password, accept authentication immediately. */
1258 if (options.password_authentication &&
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001259#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11001260 (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001261#endif /* KRB4 */
Damien Miller95def091999-11-25 00:26:21 +11001262 auth_password(pw, "")) {
1263 /* Authentication with empty password succeeded. */
1264 log("Login for user %s from %.100s, accepted without authentication.",
1265 pw->pw_name, get_remote_ipaddr());
1266 } else {
1267 /* Loop until the user has been authenticated or the
1268 connection is closed, do_authloop() returns only if
1269 authentication is successfull */
1270 do_authloop(pw);
1271 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001272
Damien Miller95def091999-11-25 00:26:21 +11001273 /* Check if the user is logging in as root and root logins are disallowed. */
1274 if (pw->pw_uid == 0 && !options.permit_root_login) {
1275 if (forced_command)
1276 log("Root login accepted for forced command.");
1277 else
1278 packet_disconnect("ROOT LOGIN REFUSED FROM %.200s",
1279 get_canonical_hostname());
1280 }
1281 /* The user has been authenticated and accepted. */
1282 packet_start(SSH_SMSG_SUCCESS);
1283 packet_send();
1284 packet_write_wait();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001285
Damien Miller95def091999-11-25 00:26:21 +11001286 /* Perform session preparation. */
1287 do_authenticated(pw);
Damien Miller2ccf6611999-11-15 15:25:10 +11001288}
1289
Damien Miller95def091999-11-25 00:26:21 +11001290#define AUTH_FAIL_MAX 6
1291#define AUTH_FAIL_LOG (AUTH_FAIL_MAX/2)
1292#define AUTH_FAIL_MSG "Too many authentication failures for %.100s"
Damien Miller2ccf6611999-11-15 15:25:10 +11001293
Damien Miller95def091999-11-25 00:26:21 +11001294/*
1295 * read packets and try to authenticate local user *pw.
1296 * return if authentication is successfull
1297 */
Damien Miller2ccf6611999-11-15 15:25:10 +11001298void
Damien Miller95def091999-11-25 00:26:21 +11001299do_authloop(struct passwd * pw)
Damien Miller2ccf6611999-11-15 15:25:10 +11001300{
Damien Miller95def091999-11-25 00:26:21 +11001301 int attempt = 0;
1302 unsigned int bits;
1303 BIGNUM *client_host_key_e, *client_host_key_n;
1304 BIGNUM *n;
1305 char *client_user = NULL, *password = NULL;
1306 char user[1024];
1307 int plen, dlen, nlen, ulen, elen;
1308 int type = 0;
1309 void (*authlog) (const char *fmt,...) = verbose;
Damien Miller3bd49ec1999-11-15 15:40:55 +11001310#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001311 int pam_retval;
Damien Miller3bd49ec1999-11-15 15:40:55 +11001312#endif /* HAVE_LIBPAM */
Damien Miller2ccf6611999-11-15 15:25:10 +11001313
Damien Miller95def091999-11-25 00:26:21 +11001314 /* Indicate that authentication is needed. */
1315 packet_start(SSH_SMSG_FAILURE);
1316 packet_send();
1317 packet_write_wait();
Damien Miller2ccf6611999-11-15 15:25:10 +11001318
Damien Miller95def091999-11-25 00:26:21 +11001319 for (attempt = 1;; attempt++) {
1320 int authenticated = 0;
1321 strlcpy(user, "", sizeof user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001322
Damien Miller95def091999-11-25 00:26:21 +11001323 /* Get a packet from the client. */
1324 type = packet_read(&plen);
1325
1326 /* Process the packet. */
1327 switch (type) {
Damien Miller2ccf6611999-11-15 15:25:10 +11001328#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11001329 case SSH_CMSG_HAVE_KERBEROS_TGT:
1330 if (!options.kerberos_tgt_passing) {
1331 /* packet_get_all(); */
1332 verbose("Kerberos tgt passing disabled.");
1333 break;
1334 } else {
1335 /* Accept Kerberos tgt. */
1336 char *tgt = packet_get_string(&dlen);
1337 packet_integrity_check(plen, 4 + dlen, type);
1338 if (!auth_kerberos_tgt(pw, tgt))
1339 verbose("Kerberos tgt REFUSED for %s", pw->pw_name);
1340 xfree(tgt);
1341 }
1342 continue;
1343
1344 case SSH_CMSG_HAVE_AFS_TOKEN:
1345 if (!options.afs_token_passing || !k_hasafs()) {
1346 /* packet_get_all(); */
1347 verbose("AFS token passing disabled.");
1348 break;
1349 } else {
1350 /* Accept AFS token. */
1351 char *token_string = packet_get_string(&dlen);
1352 packet_integrity_check(plen, 4 + dlen, type);
1353 if (!auth_afs_token(pw, token_string))
1354 verbose("AFS token REFUSED for %s", pw->pw_name);
1355 xfree(token_string);
1356 }
1357 continue;
Damien Miller2ccf6611999-11-15 15:25:10 +11001358#endif /* AFS */
Damien Miller2ccf6611999-11-15 15:25:10 +11001359#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11001360 case SSH_CMSG_AUTH_KERBEROS:
1361 if (!options.kerberos_authentication) {
1362 /* packet_get_all(); */
1363 verbose("Kerberos authentication disabled.");
1364 break;
1365 } else {
1366 /* Try Kerberos v4 authentication. */
1367 KTEXT_ST auth;
1368 char *tkt_user = NULL;
1369 char *kdata = packet_get_string((unsigned int *) &auth.length);
1370 packet_integrity_check(plen, 4 + auth.length, type);
Damien Miller2ccf6611999-11-15 15:25:10 +11001371
Damien Miller95def091999-11-25 00:26:21 +11001372 if (auth.length < MAX_KTXT_LEN)
1373 memcpy(auth.dat, kdata, auth.length);
1374 xfree(kdata);
1375
1376 authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
1377
1378 if (authenticated) {
1379 snprintf(user, sizeof user, " tktuser %s", tkt_user);
1380 xfree(tkt_user);
1381 }
1382 }
1383 break;
Damien Miller2ccf6611999-11-15 15:25:10 +11001384#endif /* KRB4 */
Damien Miller2ccf6611999-11-15 15:25:10 +11001385
Damien Miller95def091999-11-25 00:26:21 +11001386 case SSH_CMSG_AUTH_RHOSTS:
1387 if (!options.rhosts_authentication) {
1388 verbose("Rhosts authentication disabled.");
1389 break;
1390 }
Damien Miller5428f641999-11-25 11:54:57 +11001391 /*
1392 * Get client user name. Note that we just have to
1393 * trust the client; this is one reason why rhosts
1394 * authentication is insecure. (Another is
1395 * IP-spoofing on a local network.)
1396 */
Damien Miller95def091999-11-25 00:26:21 +11001397 client_user = packet_get_string(&ulen);
1398 packet_integrity_check(plen, 4 + ulen, type);
1399
1400 /* Try to authenticate using /etc/hosts.equiv and
1401 .rhosts. */
1402 authenticated = auth_rhosts(pw, client_user);
1403
1404 snprintf(user, sizeof user, " ruser %s", client_user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001405#ifndef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001406 xfree(client_user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001407#endif /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001408 break;
Damien Miller7e8e8201999-11-16 13:37:16 +11001409
Damien Miller95def091999-11-25 00:26:21 +11001410 case SSH_CMSG_AUTH_RHOSTS_RSA:
1411 if (!options.rhosts_rsa_authentication) {
1412 verbose("Rhosts with RSA authentication disabled.");
1413 break;
1414 }
Damien Miller5428f641999-11-25 11:54:57 +11001415 /*
1416 * Get client user name. Note that we just have to
1417 * trust the client; root on the client machine can
1418 * claim to be any user.
1419 */
Damien Miller95def091999-11-25 00:26:21 +11001420 client_user = packet_get_string(&ulen);
1421
1422 /* Get the client host key. */
1423 client_host_key_e = BN_new();
1424 client_host_key_n = BN_new();
1425 bits = packet_get_int();
1426 packet_get_bignum(client_host_key_e, &elen);
1427 packet_get_bignum(client_host_key_n, &nlen);
1428
1429 if (bits != BN_num_bits(client_host_key_n))
1430 error("Warning: keysize mismatch for client_host_key: "
1431 "actual %d, announced %d", BN_num_bits(client_host_key_n), bits);
1432 packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1433
1434 authenticated = auth_rhosts_rsa(pw, client_user,
1435 client_host_key_e, client_host_key_n);
1436 BN_clear_free(client_host_key_e);
1437 BN_clear_free(client_host_key_n);
1438
1439 snprintf(user, sizeof user, " ruser %s", client_user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001440#ifndef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001441 xfree(client_user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001442#endif /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001443 break;
Damien Miller81428f91999-11-18 09:28:11 +11001444
Damien Miller95def091999-11-25 00:26:21 +11001445 case SSH_CMSG_AUTH_RSA:
1446 if (!options.rsa_authentication) {
1447 verbose("RSA authentication disabled.");
1448 break;
1449 }
1450 /* RSA authentication requested. */
1451 n = BN_new();
1452 packet_get_bignum(n, &nlen);
1453 packet_integrity_check(plen, nlen, type);
1454 authenticated = auth_rsa(pw, n);
1455 BN_clear_free(n);
1456 break;
1457
1458 case SSH_CMSG_AUTH_PASSWORD:
1459 if (!options.password_authentication) {
1460 verbose("Password authentication disabled.");
1461 break;
1462 }
Damien Miller5428f641999-11-25 11:54:57 +11001463 /*
1464 * Read user password. It is in plain text, but was
1465 * transmitted over the encrypted channel so it is
1466 * not visible to an outside observer.
1467 */
Damien Miller95def091999-11-25 00:26:21 +11001468 password = packet_get_string(&dlen);
1469 packet_integrity_check(plen, 4 + dlen, type);
1470
Damien Miller06230761999-10-28 14:03:14 +10001471#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001472 /* Do PAM auth with password */
1473 pampasswd = password;
1474 pam_retval = pam_authenticate((pam_handle_t *)pamh, 0);
1475 if (pam_retval == PAM_SUCCESS) {
1476 log("PAM Password authentication accepted for user \"%.100s\"", pw->pw_name);
1477 authenticated = 1;
1478 break;
1479 }
Damien Miller3bd49ec1999-11-15 15:40:55 +11001480
Damien Miller95def091999-11-25 00:26:21 +11001481 log("PAM Password authentication for \"%.100s\" failed: %s",
1482 pw->pw_name, PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
1483 break;
Damien Miller2ccf6611999-11-15 15:25:10 +11001484#else /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001485 /* Try authentication with the password. */
1486 authenticated = auth_password(pw, password);
Damien Miller2ccf6611999-11-15 15:25:10 +11001487
Damien Miller95def091999-11-25 00:26:21 +11001488 memset(password, 0, strlen(password));
1489 xfree(password);
1490 break;
Damien Miller2ccf6611999-11-15 15:25:10 +11001491#endif /* HAVE_LIBPAM */
Damien Miller2ccf6611999-11-15 15:25:10 +11001492
Damien Miller95def091999-11-25 00:26:21 +11001493#ifdef SKEY
1494 case SSH_CMSG_AUTH_TIS:
1495 debug("rcvd SSH_CMSG_AUTH_TIS");
1496 if (options.skey_authentication == 1) {
1497 char *skeyinfo = skey_keyinfo(pw->pw_name);
1498 if (skeyinfo == NULL) {
1499 debug("generating fake skeyinfo for %.100s.", pw->pw_name);
1500 skeyinfo = skey_fake_keyinfo(pw->pw_name);
1501 }
1502 if (skeyinfo != NULL) {
Damien Miller5428f641999-11-25 11:54:57 +11001503 /* we send our s/key- in tis-challenge messages */
Damien Miller95def091999-11-25 00:26:21 +11001504 debug("sending challenge '%s'", skeyinfo);
1505 packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1506 packet_put_string(skeyinfo, strlen(skeyinfo));
1507 packet_send();
1508 packet_write_wait();
1509 continue;
1510 }
1511 }
1512 break;
1513 case SSH_CMSG_AUTH_TIS_RESPONSE:
1514 debug("rcvd SSH_CMSG_AUTH_TIS_RESPONSE");
1515 if (options.skey_authentication == 1) {
1516 char *response = packet_get_string(&dlen);
1517 debug("skey response == '%s'", response);
1518 packet_integrity_check(plen, 4 + dlen, type);
1519 authenticated = (skey_haskey(pw->pw_name) == 0 &&
1520 skey_passcheck(pw->pw_name, response) != -1);
1521 xfree(response);
1522 }
1523 break;
1524#else
1525 case SSH_CMSG_AUTH_TIS:
1526 /* TIS Authentication is unsupported */
1527 log("TIS authentication unsupported.");
1528 break;
1529#endif
1530
1531 default:
Damien Miller5428f641999-11-25 11:54:57 +11001532 /*
1533 * Any unknown messages will be ignored (and failure
1534 * returned) during authentication.
1535 */
Damien Miller95def091999-11-25 00:26:21 +11001536 log("Unknown message during authentication: type %d", type);
1537 break;
1538 }
1539
1540 /* Raise logging level */
1541 if (authenticated ||
1542 attempt == AUTH_FAIL_LOG ||
1543 type == SSH_CMSG_AUTH_PASSWORD)
1544 authlog = log;
1545
1546 authlog("%s %s for %.200s from %.200s port %d%s",
1547 authenticated ? "Accepted" : "Failed",
1548 get_authname(type),
1549 pw->pw_uid == 0 ? "ROOT" : pw->pw_name,
1550 get_remote_ipaddr(),
1551 get_remote_port(),
1552 user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001553
Damien Millereabf3411999-12-07 14:56:27 +11001554#ifndef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001555 if (authenticated)
1556 return;
1557
1558 if (attempt > AUTH_FAIL_MAX)
1559 packet_disconnect(AUTH_FAIL_MSG, pw->pw_name);
Damien Millereabf3411999-12-07 14:56:27 +11001560#else /* HAVE_LIBPAM */
1561 if (authenticated) {
1562 do_pam_account_and_session(pw->pw_name, client_user);
1563
1564 /* Clean up */
1565 if (client_user != NULL)
1566 xfree(client_user);
1567
1568 if (password != NULL) {
1569 memset(password, 0, strlen(password));
1570 xfree(password);
1571 }
1572
1573 return;
1574 }
1575
1576 if (attempt > AUTH_FAIL_MAX) {
1577 /* Clean up */
1578 if (client_user != NULL)
1579 xfree(client_user);
1580
1581 if (password != NULL) {
1582 memset(password, 0, strlen(password));
1583 xfree(password);
1584 }
1585
1586 packet_disconnect(AUTH_FAIL_MSG, pw->pw_name);
1587 }
1588#endif /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001589
1590 /* Send a message indicating that the authentication attempt failed. */
1591 packet_start(SSH_SMSG_FAILURE);
1592 packet_send();
1593 packet_write_wait();
1594 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001595}
1596
Damien Miller95def091999-11-25 00:26:21 +11001597/*
1598 * The user does not exist or access is denied,
1599 * but fake indication that authentication is needed.
1600 */
Damien Miller2ccf6611999-11-15 15:25:10 +11001601void
1602do_fake_authloop(char *user)
Damien Miller3d112ef1999-10-28 13:20:30 +10001603{
Damien Miller95def091999-11-25 00:26:21 +11001604 int attempt = 0;
Damien Miller2ccf6611999-11-15 15:25:10 +11001605
Damien Miller95def091999-11-25 00:26:21 +11001606 log("Faking authloop for illegal user %.200s from %.200s port %d",
1607 user,
1608 get_remote_ipaddr(),
1609 get_remote_port());
Damien Miller3d112ef1999-10-28 13:20:30 +10001610
Damien Miller95def091999-11-25 00:26:21 +11001611 /* Indicate that authentication is needed. */
1612 packet_start(SSH_SMSG_FAILURE);
1613 packet_send();
1614 packet_write_wait();
1615
Damien Miller5428f641999-11-25 11:54:57 +11001616 /*
1617 * Keep reading packets, and always respond with a failure. This is
1618 * to avoid disclosing whether such a user really exists.
1619 */
Damien Miller95def091999-11-25 00:26:21 +11001620 for (attempt = 1;; attempt++) {
Damien Miller5428f641999-11-25 11:54:57 +11001621 /* Read a packet. This will not return if the client disconnects. */
Damien Miller95def091999-11-25 00:26:21 +11001622 int plen;
1623 int type = packet_read(&plen);
Damien Miller2ccf6611999-11-15 15:25:10 +11001624#ifdef SKEY
Damien Miller95def091999-11-25 00:26:21 +11001625 int dlen;
1626 char *password, *skeyinfo;
1627 if (options.password_authentication &&
1628 options.skey_authentication == 1 &&
1629 type == SSH_CMSG_AUTH_PASSWORD &&
1630 (password = packet_get_string(&dlen)) != NULL &&
1631 dlen == 5 &&
1632 strncasecmp(password, "s/key", 5) == 0 &&
1633 (skeyinfo = skey_fake_keyinfo(user)) != NULL) {
1634 /* Send a fake s/key challenge. */
1635 packet_send_debug(skeyinfo);
1636 }
Damien Miller2ccf6611999-11-15 15:25:10 +11001637#endif
Damien Miller95def091999-11-25 00:26:21 +11001638 if (attempt > AUTH_FAIL_MAX)
1639 packet_disconnect(AUTH_FAIL_MSG, user);
1640
Damien Miller5428f641999-11-25 11:54:57 +11001641 /*
1642 * Send failure. This should be indistinguishable from a
1643 * failed authentication.
1644 */
Damien Miller95def091999-11-25 00:26:21 +11001645 packet_start(SSH_SMSG_FAILURE);
1646 packet_send();
1647 packet_write_wait();
1648 }
1649 /* NOTREACHED */
1650 abort();
Damien Miller3d112ef1999-10-28 13:20:30 +10001651}
1652
Damien Miller2ccf6611999-11-15 15:25:10 +11001653
Damien Miller95def091999-11-25 00:26:21 +11001654/*
1655 * Remove local Xauthority file.
1656 */
Damien Miller5ce662a1999-11-11 17:57:39 +11001657static void
1658xauthfile_cleanup_proc(void *ignore)
1659{
Damien Miller95def091999-11-25 00:26:21 +11001660 debug("xauthfile_cleanup_proc called");
Damien Miller5ce662a1999-11-11 17:57:39 +11001661
Damien Miller95def091999-11-25 00:26:21 +11001662 if (xauthfile != NULL) {
1663 unlink(xauthfile);
1664 xfree(xauthfile);
1665 xauthfile = NULL;
1666 }
Damien Miller5ce662a1999-11-11 17:57:39 +11001667}
1668
Damien Miller95def091999-11-25 00:26:21 +11001669/*
1670 * Prepares for an interactive session. This is called after the user has
1671 * been successfully authenticated. During this message exchange, pseudo
1672 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1673 * are requested, etc.
1674 */
1675void
1676do_authenticated(struct passwd * pw)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001677{
Damien Miller95def091999-11-25 00:26:21 +11001678 int type;
1679 int compression_level = 0, enable_compression_after_reply = 0;
1680 int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1;
1681 int row, col, xpixel, ypixel, screen;
1682 char ttyname[64];
1683 char *command, *term = NULL, *display = NULL, *proto = NULL,
1684 *data = NULL;
1685 struct group *grp;
1686 gid_t tty_gid;
1687 mode_t tty_mode;
1688 int n_bytes;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001689
Damien Miller5428f641999-11-25 11:54:57 +11001690 /*
1691 * Cancel the alarm we set to limit the time taken for
1692 * authentication.
1693 */
Damien Miller95def091999-11-25 00:26:21 +11001694 alarm(0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001695
Damien Miller5428f641999-11-25 11:54:57 +11001696 /*
1697 * Inform the channel mechanism that we are the server side and that
1698 * the client may request to connect to any port at all. (The user
1699 * could do it anyway, and we wouldn\'t know what is permitted except
1700 * by the client telling us, so we can equally well trust the client
1701 * not to request anything bogus.)
1702 */
Damien Miller95def091999-11-25 00:26:21 +11001703 channel_permit_all_opens();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001704
Damien Miller5428f641999-11-25 11:54:57 +11001705 /*
1706 * We stay in this loop until the client requests to execute a shell
1707 * or a command.
1708 */
Damien Miller95def091999-11-25 00:26:21 +11001709 while (1) {
1710 int plen, dlen;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001711
Damien Miller95def091999-11-25 00:26:21 +11001712 /* Get a packet from the client. */
1713 type = packet_read(&plen);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001714
Damien Miller95def091999-11-25 00:26:21 +11001715 /* Process the packet. */
1716 switch (type) {
1717 case SSH_CMSG_REQUEST_COMPRESSION:
1718 packet_integrity_check(plen, 4, type);
1719 compression_level = packet_get_int();
1720 if (compression_level < 1 || compression_level > 9) {
1721 packet_send_debug("Received illegal compression level %d.",
1722 compression_level);
1723 goto fail;
1724 }
1725 /* Enable compression after we have responded with SUCCESS. */
1726 enable_compression_after_reply = 1;
1727 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001728
Damien Miller95def091999-11-25 00:26:21 +11001729 case SSH_CMSG_REQUEST_PTY:
1730 if (no_pty_flag) {
1731 debug("Allocating a pty not permitted for this authentication.");
1732 goto fail;
1733 }
1734 if (have_pty)
1735 packet_disconnect("Protocol error: you already have a pty.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001736
Damien Miller95def091999-11-25 00:26:21 +11001737 debug("Allocating pty.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001738
Damien Miller95def091999-11-25 00:26:21 +11001739 /* Allocate a pty and open it. */
1740 if (!pty_allocate(&ptyfd, &ttyfd, ttyname)) {
1741 error("Failed to allocate pty.");
1742 goto fail;
1743 }
1744 /* Determine the group to make the owner of the tty. */
1745 grp = getgrnam("tty");
1746 if (grp) {
1747 tty_gid = grp->gr_gid;
1748 tty_mode = S_IRUSR | S_IWUSR | S_IWGRP;
1749 } else {
1750 tty_gid = pw->pw_gid;
1751 tty_mode = S_IRUSR | S_IWUSR | S_IWGRP | S_IWOTH;
1752 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001753
Damien Miller95def091999-11-25 00:26:21 +11001754 /* Change ownership of the tty. */
1755 if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
1756 fatal("chown(%.100s, %d, %d) failed: %.100s",
1757 ttyname, pw->pw_uid, tty_gid, strerror(errno));
1758 if (chmod(ttyname, tty_mode) < 0)
1759 fatal("chmod(%.100s, 0%o) failed: %.100s",
1760 ttyname, tty_mode, strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001761
Damien Miller95def091999-11-25 00:26:21 +11001762 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
1763 term = packet_get_string(&dlen);
1764 packet_integrity_check(dlen, strlen(term), type);
1765 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
1766 /* Remaining bytes */
1767 n_bytes = plen - (4 + dlen + 4 * 4);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001768
Damien Miller95def091999-11-25 00:26:21 +11001769 if (strcmp(term, "") == 0)
1770 term = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001771
Damien Miller95def091999-11-25 00:26:21 +11001772 /* Get window size from the packet. */
1773 row = packet_get_int();
1774 col = packet_get_int();
1775 xpixel = packet_get_int();
1776 ypixel = packet_get_int();
1777 pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001778
Damien Miller95def091999-11-25 00:26:21 +11001779 /* Get tty modes from the packet. */
1780 tty_parse_modes(ttyfd, &n_bytes);
1781 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001782
Damien Miller95def091999-11-25 00:26:21 +11001783 /* Indicate that we now have a pty. */
1784 have_pty = 1;
1785 break;
1786
1787 case SSH_CMSG_X11_REQUEST_FORWARDING:
1788 if (!options.x11_forwarding) {
1789 packet_send_debug("X11 forwarding disabled in server configuration file.");
1790 goto fail;
1791 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001792#ifdef XAUTH_PATH
Damien Miller95def091999-11-25 00:26:21 +11001793 if (no_x11_forwarding_flag) {
1794 packet_send_debug("X11 forwarding not permitted for this authentication.");
1795 goto fail;
1796 }
1797 debug("Received request for X11 forwarding with auth spoofing.");
1798 if (display)
1799 packet_disconnect("Protocol error: X11 display already set.");
1800 {
1801 int proto_len, data_len;
1802 proto = packet_get_string(&proto_len);
1803 data = packet_get_string(&data_len);
1804 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
1805 }
1806 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1807 screen = packet_get_int();
1808 else
1809 screen = 0;
1810 display = x11_create_display_inet(screen);
1811 if (!display)
1812 goto fail;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001813
Damien Miller95def091999-11-25 00:26:21 +11001814 /* Setup to always have a local .Xauthority. */
1815 xauthfile = xmalloc(MAXPATHLEN);
1816 snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX");
1817
1818 if ((xauthfd = mkstemp(xauthfile)) != -1) {
1819 fchown(xauthfd, pw->pw_uid, pw->pw_gid);
1820 close(xauthfd);
1821 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
1822 } else {
1823 xfree(xauthfile);
1824 xauthfile = NULL;
1825 }
1826 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001827#else /* XAUTH_PATH */
Damien Miller95def091999-11-25 00:26:21 +11001828 packet_send_debug("No xauth program; cannot forward with spoofing.");
1829 goto fail;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001830#endif /* XAUTH_PATH */
1831
Damien Miller95def091999-11-25 00:26:21 +11001832 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1833 if (no_agent_forwarding_flag) {
1834 debug("Authentication agent forwarding not permitted for this authentication.");
1835 goto fail;
1836 }
1837 debug("Received authentication agent forwarding request.");
1838 auth_input_request_forwarding(pw);
1839 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001840
Damien Miller95def091999-11-25 00:26:21 +11001841 case SSH_CMSG_PORT_FORWARD_REQUEST:
1842 if (no_port_forwarding_flag) {
1843 debug("Port forwarding not permitted for this authentication.");
1844 goto fail;
1845 }
1846 debug("Received TCP/IP port forwarding request.");
1847 channel_input_port_forward_request(pw->pw_uid == 0);
1848 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001849
Damien Miller95def091999-11-25 00:26:21 +11001850 case SSH_CMSG_MAX_PACKET_SIZE:
1851 if (packet_set_maxsize(packet_get_int()) < 0)
1852 goto fail;
1853 break;
Damien Miller6162d121999-11-21 13:23:52 +11001854
Damien Miller95def091999-11-25 00:26:21 +11001855 case SSH_CMSG_EXEC_SHELL:
1856 /* Set interactive/non-interactive mode. */
1857 packet_set_interactive(have_pty || display != NULL,
1858 options.keepalives);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001859
Damien Miller95def091999-11-25 00:26:21 +11001860 if (forced_command != NULL)
1861 goto do_forced_command;
1862 debug("Forking shell.");
1863 packet_integrity_check(plen, 0, type);
1864 if (have_pty)
1865 do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1866 else
1867 do_exec_no_pty(NULL, pw, display, proto, data);
1868 return;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001869
Damien Miller95def091999-11-25 00:26:21 +11001870 case SSH_CMSG_EXEC_CMD:
1871 /* Set interactive/non-interactive mode. */
1872 packet_set_interactive(have_pty || display != NULL,
1873 options.keepalives);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001874
Damien Miller95def091999-11-25 00:26:21 +11001875 if (forced_command != NULL)
1876 goto do_forced_command;
1877 /* Get command from the packet. */
1878 {
1879 int dlen;
1880 command = packet_get_string(&dlen);
1881 debug("Executing command '%.500s'", command);
1882 packet_integrity_check(plen, 4 + dlen, type);
1883 }
1884 if (have_pty)
1885 do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1886 else
1887 do_exec_no_pty(command, pw, display, proto, data);
1888 xfree(command);
1889 return;
1890
1891 default:
Damien Miller5428f641999-11-25 11:54:57 +11001892 /*
1893 * Any unknown messages in this phase are ignored,
1894 * and a failure message is returned.
1895 */
Damien Miller95def091999-11-25 00:26:21 +11001896 log("Unknown packet type received after authentication: %d", type);
1897 goto fail;
1898 }
1899
1900 /* The request was successfully processed. */
1901 packet_start(SSH_SMSG_SUCCESS);
1902 packet_send();
1903 packet_write_wait();
1904
1905 /* Enable compression now that we have replied if appropriate. */
1906 if (enable_compression_after_reply) {
1907 enable_compression_after_reply = 0;
1908 packet_start_compression(compression_level);
1909 }
1910 continue;
1911
1912fail:
1913 /* The request failed. */
1914 packet_start(SSH_SMSG_FAILURE);
1915 packet_send();
1916 packet_write_wait();
1917 continue;
1918
1919do_forced_command:
Damien Miller5428f641999-11-25 11:54:57 +11001920 /*
1921 * There is a forced command specified for this login.
1922 * Execute it.
1923 */
Damien Miller95def091999-11-25 00:26:21 +11001924 debug("Executing forced command: %.900s", forced_command);
1925 if (have_pty)
1926 do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1927 else
1928 do_exec_no_pty(forced_command, pw, display, proto, data);
1929 return;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001930 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001931}
1932
Damien Miller95def091999-11-25 00:26:21 +11001933/*
1934 * This is called to fork and execute a command when we have no tty. This
1935 * will call do_child from the child, and server_loop from the parent after
1936 * setting up file descriptors and such.
1937 */
1938void
1939do_exec_no_pty(const char *command, struct passwd * pw,
1940 const char *display, const char *auth_proto,
1941 const char *auth_data)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001942{
Damien Miller95def091999-11-25 00:26:21 +11001943 int pid;
1944
1945#ifdef USE_PIPES
1946 int pin[2], pout[2], perr[2];
1947 /* Allocate pipes for communicating with the program. */
1948 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1949 packet_disconnect("Could not create pipes: %.100s",
1950 strerror(errno));
1951#else /* USE_PIPES */
1952 int inout[2], err[2];
1953 /* Uses socket pairs to communicate with the program. */
1954 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
1955 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
1956 packet_disconnect("Could not create socket pairs: %.100s",
1957 strerror(errno));
1958#endif /* USE_PIPES */
1959
1960 setproctitle("%s@notty", pw->pw_name);
1961
1962 /* Fork the child. */
1963 if ((pid = fork()) == 0) {
1964 /* Child. Reinitialize the log since the pid has changed. */
1965 log_init(av0, options.log_level, options.log_facility, log_stderr);
1966
Damien Miller5428f641999-11-25 11:54:57 +11001967 /*
1968 * Create a new session and process group since the 4.4BSD
1969 * setlogin() affects the entire process group.
1970 */
Damien Miller95def091999-11-25 00:26:21 +11001971 if (setsid() < 0)
1972 error("setsid failed: %.100s", strerror(errno));
1973
1974#ifdef USE_PIPES
Damien Miller5428f641999-11-25 11:54:57 +11001975 /*
1976 * Redirect stdin. We close the parent side of the socket
1977 * pair, and make the child side the standard input.
1978 */
Damien Miller95def091999-11-25 00:26:21 +11001979 close(pin[1]);
1980 if (dup2(pin[0], 0) < 0)
1981 perror("dup2 stdin");
1982 close(pin[0]);
1983
1984 /* Redirect stdout. */
1985 close(pout[0]);
1986 if (dup2(pout[1], 1) < 0)
1987 perror("dup2 stdout");
1988 close(pout[1]);
1989
1990 /* Redirect stderr. */
1991 close(perr[0]);
1992 if (dup2(perr[1], 2) < 0)
1993 perror("dup2 stderr");
1994 close(perr[1]);
1995#else /* USE_PIPES */
Damien Miller5428f641999-11-25 11:54:57 +11001996 /*
1997 * Redirect stdin, stdout, and stderr. Stdin and stdout will
1998 * use the same socket, as some programs (particularly rdist)
1999 * seem to depend on it.
2000 */
Damien Miller95def091999-11-25 00:26:21 +11002001 close(inout[1]);
2002 close(err[1]);
2003 if (dup2(inout[0], 0) < 0) /* stdin */
2004 perror("dup2 stdin");
2005 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
2006 perror("dup2 stdout");
2007 if (dup2(err[0], 2) < 0) /* stderr */
2008 perror("dup2 stderr");
2009#endif /* USE_PIPES */
2010
2011 /* Do processing for the child (exec command etc). */
2012 do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
2013 /* NOTREACHED */
2014 }
2015 if (pid < 0)
2016 packet_disconnect("fork failed: %.100s", strerror(errno));
2017#ifdef USE_PIPES
2018 /* We are the parent. Close the child sides of the pipes. */
2019 close(pin[0]);
2020 close(pout[1]);
2021 close(perr[1]);
2022
2023 /* Enter the interactive session. */
2024 server_loop(pid, pin[1], pout[0], perr[0]);
2025 /* server_loop has closed pin[1], pout[1], and perr[1]. */
2026#else /* USE_PIPES */
2027 /* We are the parent. Close the child sides of the socket pairs. */
2028 close(inout[0]);
2029 close(err[0]);
2030
Damien Miller5428f641999-11-25 11:54:57 +11002031 /*
2032 * Enter the interactive session. Note: server_loop must be able to
2033 * handle the case that fdin and fdout are the same.
2034 */
Damien Miller95def091999-11-25 00:26:21 +11002035 server_loop(pid, inout[1], inout[1], err[1]);
2036 /* server_loop has closed inout[1] and err[1]. */
2037#endif /* USE_PIPES */
2038}
2039
2040struct pty_cleanup_context {
2041 const char *ttyname;
2042 int pid;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002043};
2044
Damien Miller95def091999-11-25 00:26:21 +11002045/*
2046 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
2047 * dropped connection).
2048 */
2049void
2050pty_cleanup_proc(void *context)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002051{
Damien Miller95def091999-11-25 00:26:21 +11002052 struct pty_cleanup_context *cu = context;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002053
Damien Miller95def091999-11-25 00:26:21 +11002054 debug("pty_cleanup_proc called");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002055
Damien Miller95def091999-11-25 00:26:21 +11002056 /* Record that the user has logged out. */
2057 record_logout(cu->pid, cu->ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002058
Damien Miller95def091999-11-25 00:26:21 +11002059 /* Release the pseudo-tty. */
2060 pty_release(cu->ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002061}
2062
Damien Miller95def091999-11-25 00:26:21 +11002063/*
2064 * This is called to fork and execute a command when we have a tty. This
2065 * will call do_child from the child, and server_loop from the parent after
2066 * setting up file descriptors, controlling tty, updating wtmp, utmp,
2067 * lastlog, and other such operations.
2068 */
2069void
2070do_exec_pty(const char *command, int ptyfd, int ttyfd,
2071 const char *ttyname, struct passwd * pw, const char *term,
2072 const char *display, const char *auth_proto,
2073 const char *auth_data)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002074{
Damien Miller95def091999-11-25 00:26:21 +11002075 int pid, fdout;
2076 const char *hostname;
2077 time_t last_login_time;
2078 char buf[100], *time_string;
2079 FILE *f;
2080 char line[256];
2081 struct stat st;
2082 int quiet_login;
2083 struct sockaddr_in from;
2084 int fromlen;
2085 struct pty_cleanup_context cleanup_context;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002086
Damien Miller95def091999-11-25 00:26:21 +11002087 /* Get remote host name. */
2088 hostname = get_canonical_hostname();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002089
Damien Miller5428f641999-11-25 11:54:57 +11002090 /*
2091 * Get the time when the user last logged in. Buf will be set to
2092 * contain the hostname the last login was from.
2093 */
Damien Miller95def091999-11-25 00:26:21 +11002094 if (!options.use_login) {
2095 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
2096 buf, sizeof(buf));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002097 }
Damien Miller95def091999-11-25 00:26:21 +11002098 setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002099
Damien Miller95def091999-11-25 00:26:21 +11002100 /* Fork the child. */
2101 if ((pid = fork()) == 0) {
2102 pid = getpid();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002103
Damien Miller95def091999-11-25 00:26:21 +11002104 /* Child. Reinitialize the log because the pid has
2105 changed. */
2106 log_init(av0, options.log_level, options.log_facility, log_stderr);
2107
2108 /* Close the master side of the pseudo tty. */
2109 close(ptyfd);
2110
2111 /* Make the pseudo tty our controlling tty. */
2112 pty_make_controlling_tty(&ttyfd, ttyname);
2113
2114 /* Redirect stdin from the pseudo tty. */
2115 if (dup2(ttyfd, fileno(stdin)) < 0)
2116 error("dup2 stdin failed: %.100s", strerror(errno));
2117
2118 /* Redirect stdout to the pseudo tty. */
2119 if (dup2(ttyfd, fileno(stdout)) < 0)
2120 error("dup2 stdin failed: %.100s", strerror(errno));
2121
2122 /* Redirect stderr to the pseudo tty. */
2123 if (dup2(ttyfd, fileno(stderr)) < 0)
2124 error("dup2 stdin failed: %.100s", strerror(errno));
2125
2126 /* Close the extra descriptor for the pseudo tty. */
2127 close(ttyfd);
2128
Damien Miller5428f641999-11-25 11:54:57 +11002129 /*
2130 * Get IP address of client. This is needed because we want
2131 * to record where the user logged in from. If the
2132 * connection is not a socket, let the ip address be 0.0.0.0.
2133 */
Damien Miller95def091999-11-25 00:26:21 +11002134 memset(&from, 0, sizeof(from));
2135 if (packet_get_connection_in() == packet_get_connection_out()) {
2136 fromlen = sizeof(from);
2137 if (getpeername(packet_get_connection_in(),
2138 (struct sockaddr *) & from, &fromlen) < 0) {
2139 debug("getpeername: %.100s", strerror(errno));
2140 fatal_cleanup();
2141 }
2142 }
2143 /* Record that there was a login on that terminal. */
2144 record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
2145 &from);
2146
2147 /* Check if .hushlogin exists. */
2148 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2149 quiet_login = stat(line, &st) >= 0;
Damien Miller356a0b01999-11-08 15:30:59 +11002150
2151#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11002152 /* output the results of the pamconv() */
2153 if (!quiet_login && pamconv_msg != NULL)
2154 fprintf(stderr, pamconv_msg);
Damien Miller356a0b01999-11-08 15:30:59 +11002155#endif
Damien Miller95def091999-11-25 00:26:21 +11002156
Damien Miller5428f641999-11-25 11:54:57 +11002157 /*
2158 * If the user has logged in before, display the time of last
2159 * login. However, don't display anything extra if a command
2160 * has been specified (so that ssh can be used to execute
2161 * commands on a remote machine without users knowing they
2162 * are going to another machine). Login(1) will do this for
2163 * us as well, so check if login(1) is used
2164 */
Damien Miller95def091999-11-25 00:26:21 +11002165 if (command == NULL && last_login_time != 0 && !quiet_login &&
2166 !options.use_login) {
2167 /* Convert the date to a string. */
2168 time_string = ctime(&last_login_time);
2169 /* Remove the trailing newline. */
2170 if (strchr(time_string, '\n'))
2171 *strchr(time_string, '\n') = 0;
2172 /* Display the last login time. Host if displayed
2173 if known. */
2174 if (strcmp(buf, "") == 0)
2175 printf("Last login: %s\r\n", time_string);
2176 else
2177 printf("Last login: %s from %s\r\n", time_string, buf);
2178 }
Damien Miller5428f641999-11-25 11:54:57 +11002179 /*
2180 * Print /etc/motd unless a command was specified or printing
2181 * it was disabled in server options or login(1) will be
2182 * used. Note that some machines appear to print it in
2183 * /etc/profile or similar.
2184 */
Damien Miller95def091999-11-25 00:26:21 +11002185 if (command == NULL && options.print_motd && !quiet_login &&
2186 !options.use_login) {
2187 /* Print /etc/motd if it exists. */
2188 f = fopen("/etc/motd", "r");
2189 if (f) {
2190 while (fgets(line, sizeof(line), f))
2191 fputs(line, stdout);
2192 fclose(f);
2193 }
2194 }
2195 /* Do common processing for the child, such as execing the command. */
2196 do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
2197 /* NOTREACHED */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002198 }
Damien Miller95def091999-11-25 00:26:21 +11002199 if (pid < 0)
2200 packet_disconnect("fork failed: %.100s", strerror(errno));
2201 /* Parent. Close the slave side of the pseudo tty. */
2202 close(ttyfd);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002203
Damien Miller5428f641999-11-25 11:54:57 +11002204 /*
2205 * Create another descriptor of the pty master side for use as the
2206 * standard input. We could use the original descriptor, but this
2207 * simplifies code in server_loop. The descriptor is bidirectional.
2208 */
Damien Miller95def091999-11-25 00:26:21 +11002209 fdout = dup(ptyfd);
2210 if (fdout < 0)
2211 packet_disconnect("dup failed: %.100s", strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002212
Damien Miller5428f641999-11-25 11:54:57 +11002213 /*
2214 * Add a cleanup function to clear the utmp entry and record logout
2215 * time in case we call fatal() (e.g., the connection gets closed).
2216 */
Damien Miller95def091999-11-25 00:26:21 +11002217 cleanup_context.pid = pid;
2218 cleanup_context.ttyname = ttyname;
2219 fatal_add_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002220
Damien Miller95def091999-11-25 00:26:21 +11002221 /* Enter interactive session. */
2222 server_loop(pid, ptyfd, fdout, -1);
2223 /* server_loop has not closed ptyfd and fdout. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002224
Damien Miller95def091999-11-25 00:26:21 +11002225 /* Cancel the cleanup function. */
2226 fatal_remove_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002227
Damien Miller95def091999-11-25 00:26:21 +11002228 /* Record that the user has logged out. */
2229 record_logout(pid, ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002230
Damien Miller95def091999-11-25 00:26:21 +11002231 /* Release the pseudo-tty. */
2232 pty_release(ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002233
Damien Miller5428f641999-11-25 11:54:57 +11002234 /*
2235 * Close the server side of the socket pairs. We must do this after
2236 * the pty cleanup, so that another process doesn't get this pty
2237 * while we're still cleaning up.
2238 */
Damien Miller95def091999-11-25 00:26:21 +11002239 close(ptyfd);
2240 close(fdout);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002241}
2242
Damien Miller95def091999-11-25 00:26:21 +11002243/*
2244 * Sets the value of the given variable in the environment. If the variable
2245 * already exists, its value is overriden.
2246 */
2247void
2248child_set_env(char ***envp, unsigned int *envsizep, const char *name,
2249 const char *value)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002250{
Damien Miller95def091999-11-25 00:26:21 +11002251 unsigned int i, namelen;
2252 char **env;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002253
Damien Miller5428f641999-11-25 11:54:57 +11002254 /*
2255 * Find the slot where the value should be stored. If the variable
2256 * already exists, we reuse the slot; otherwise we append a new slot
2257 * at the end of the array, expanding if necessary.
2258 */
Damien Miller95def091999-11-25 00:26:21 +11002259 env = *envp;
2260 namelen = strlen(name);
2261 for (i = 0; env[i]; i++)
2262 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2263 break;
2264 if (env[i]) {
Damien Miller5428f641999-11-25 11:54:57 +11002265 /* Reuse the slot. */
Damien Miller95def091999-11-25 00:26:21 +11002266 xfree(env[i]);
2267 } else {
Damien Miller5428f641999-11-25 11:54:57 +11002268 /* New variable. Expand if necessary. */
Damien Miller95def091999-11-25 00:26:21 +11002269 if (i >= (*envsizep) - 1) {
2270 (*envsizep) += 50;
2271 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2272 }
2273 /* Need to set the NULL pointer at end of array beyond the new slot. */
2274 env[i + 1] = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002275 }
2276
Damien Miller95def091999-11-25 00:26:21 +11002277 /* Allocate space and format the variable in the appropriate slot. */
2278 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2279 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002280}
2281
Damien Miller95def091999-11-25 00:26:21 +11002282/*
2283 * Reads environment variables from the given file and adds/overrides them
2284 * into the environment. If the file does not exist, this does nothing.
2285 * Otherwise, it must consist of empty lines, comments (line starts with '#')
2286 * and assignments of the form name=value. No other forms are allowed.
2287 */
2288void
2289read_environment_file(char ***env, unsigned int *envsize,
2290 const char *filename)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002291{
Damien Miller95def091999-11-25 00:26:21 +11002292 FILE *f;
2293 char buf[4096];
2294 char *cp, *value;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002295
Damien Miller95def091999-11-25 00:26:21 +11002296 f = fopen(filename, "r");
2297 if (!f)
2298 return;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002299
Damien Miller95def091999-11-25 00:26:21 +11002300 while (fgets(buf, sizeof(buf), f)) {
Damien Miller5428f641999-11-25 11:54:57 +11002301 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
2302 ;
Damien Miller95def091999-11-25 00:26:21 +11002303 if (!*cp || *cp == '#' || *cp == '\n')
2304 continue;
Damien Miller95def091999-11-25 00:26:21 +11002305 if (strchr(cp, '\n'))
2306 *strchr(cp, '\n') = '\0';
Damien Miller95def091999-11-25 00:26:21 +11002307 value = strchr(cp, '=');
2308 if (value == NULL) {
2309 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
2310 continue;
2311 }
Damien Miller5428f641999-11-25 11:54:57 +11002312 /* Replace the equals sign by nul, and advance value to the value string. */
Damien Miller95def091999-11-25 00:26:21 +11002313 *value = '\0';
2314 value++;
Damien Miller95def091999-11-25 00:26:21 +11002315 child_set_env(env, envsize, cp, value);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002316 }
Damien Miller95def091999-11-25 00:26:21 +11002317 fclose(f);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002318}
2319
Damien Miller95def091999-11-25 00:26:21 +11002320/*
2321 * Performs common processing for the child, such as setting up the
2322 * environment, closing extra file descriptors, setting the user and group
2323 * ids, and executing the command or shell.
2324 */
2325void
2326do_child(const char *command, struct passwd * pw, const char *term,
2327 const char *display, const char *auth_proto,
2328 const char *auth_data, const char *ttyname)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002329{
Damien Miller95def091999-11-25 00:26:21 +11002330 const char *shell, *cp = NULL;
2331 char buf[256];
2332 FILE *f;
2333 unsigned int envsize, i;
2334 char **env;
2335 extern char **environ;
2336 struct stat st;
2337 char *argv[10];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002338
Damien Miller356a0b01999-11-08 15:30:59 +11002339#ifndef HAVE_LIBPAM /* pam_nologin handles this */
Damien Miller95def091999-11-25 00:26:21 +11002340 /* Check /etc/nologin. */
2341 f = fopen("/etc/nologin", "r");
2342 if (f) {
2343 /* /etc/nologin exists. Print its contents and exit. */
2344 while (fgets(buf, sizeof(buf), f))
2345 fputs(buf, stderr);
2346 fclose(f);
2347 if (pw->pw_uid != 0)
2348 exit(254);
2349 }
Damien Miller776af5d1999-11-12 08:49:09 +11002350#endif /* HAVE_LIBPAM */
2351
2352#ifdef HAVE_SETLOGIN
Damien Miller95def091999-11-25 00:26:21 +11002353 /* Set login name in the kernel. */
2354 if (setlogin(pw->pw_name) < 0)
2355 error("setlogin failed: %s", strerror(errno));
Damien Miller776af5d1999-11-12 08:49:09 +11002356#endif /* HAVE_SETLOGIN */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002357
Damien Miller95def091999-11-25 00:26:21 +11002358 /* Set uid, gid, and groups. */
2359 /* Login(1) does this as well, and it needs uid 0 for the "-h"
2360 switch, so we let login(1) to this for us. */
2361 if (!options.use_login) {
2362 if (getuid() == 0 || geteuid() == 0) {
2363 if (setgid(pw->pw_gid) < 0) {
2364 perror("setgid");
2365 exit(1);
2366 }
2367 /* Initialize the group list. */
2368 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
2369 perror("initgroups");
2370 exit(1);
2371 }
2372 endgrent();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002373
Damien Miller95def091999-11-25 00:26:21 +11002374 /* Permanently switch to the desired uid. */
2375 permanently_set_uid(pw->pw_uid);
2376 }
2377 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
2378 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
2379 }
Damien Miller5428f641999-11-25 11:54:57 +11002380 /*
2381 * Get the shell from the password data. An empty shell field is
2382 * legal, and means /bin/sh.
2383 */
Damien Miller95def091999-11-25 00:26:21 +11002384 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002385
2386#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11002387 /* Try to get AFS tokens for the local cell. */
2388 if (k_hasafs()) {
2389 char cell[64];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002390
Damien Miller95def091999-11-25 00:26:21 +11002391 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
2392 krb_afslog(cell, 0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002393
Damien Miller95def091999-11-25 00:26:21 +11002394 krb_afslog(0, 0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002395 }
Damien Miller95def091999-11-25 00:26:21 +11002396#endif /* AFS */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002397
Damien Miller5428f641999-11-25 11:54:57 +11002398 /* Initialize the environment. */
Damien Miller95def091999-11-25 00:26:21 +11002399 envsize = 100;
2400 env = xmalloc(envsize * sizeof(char *));
2401 env[0] = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002402
Damien Miller95def091999-11-25 00:26:21 +11002403 if (!options.use_login) {
2404 /* Set basic environment. */
2405 child_set_env(&env, &envsize, "USER", pw->pw_name);
2406 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
2407 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2408 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002409
Damien Miller95def091999-11-25 00:26:21 +11002410 snprintf(buf, sizeof buf, "%.200s/%.50s",
2411 _PATH_MAILDIR, pw->pw_name);
2412 child_set_env(&env, &envsize, "MAIL", buf);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002413
Damien Miller95def091999-11-25 00:26:21 +11002414 /* Normal systems set SHELL by default. */
2415 child_set_env(&env, &envsize, "SHELL", shell);
2416 }
Damien Miller95def091999-11-25 00:26:21 +11002417 if (getenv("TZ"))
2418 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
2419
2420 /* Set custom environment options from RSA authentication. */
2421 while (custom_environment) {
2422 struct envstring *ce = custom_environment;
2423 char *s = ce->s;
2424 int i;
2425 for (i = 0; s[i] != '=' && s[i]; i++);
2426 if (s[i] == '=') {
2427 s[i] = 0;
2428 child_set_env(&env, &envsize, s, s + i + 1);
2429 }
2430 custom_environment = ce->next;
2431 xfree(ce->s);
2432 xfree(ce);
2433 }
2434
Damien Miller95def091999-11-25 00:26:21 +11002435 snprintf(buf, sizeof buf, "%.50s %d %d",
2436 get_remote_ipaddr(), get_remote_port(), options.port);
2437 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2438
Damien Miller95def091999-11-25 00:26:21 +11002439 if (ttyname)
2440 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
Damien Miller95def091999-11-25 00:26:21 +11002441 if (term)
2442 child_set_env(&env, &envsize, "TERM", term);
Damien Miller95def091999-11-25 00:26:21 +11002443 if (display)
2444 child_set_env(&env, &envsize, "DISPLAY", display);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002445
2446#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11002447 {
2448 extern char *ticket;
2449
2450 if (ticket)
2451 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2452 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002453#endif /* KRB4 */
2454
Damien Miller94388161999-10-29 09:57:31 +10002455#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11002456 /* Pull in any environment variables that may have been set by PAM. */
2457 {
2458 char *equals, var_name[512], var_val[512];
2459 char **pam_env = pam_getenvlist((pam_handle_t *)pamh);
2460 int i;
2461 for(i = 0; pam_env && pam_env[i]; i++) {
2462 equals = strstr(pam_env[i], "=");
2463 if ((strlen(pam_env[i]) < (sizeof(var_name) - 1)) && (equals != NULL))
2464 {
Damien Millerdc33fc31999-12-04 20:24:48 +11002465 debug("PAM environment: %s=%s", var_name, var_val);
Damien Miller95def091999-11-25 00:26:21 +11002466 memset(var_name, '\0', sizeof(var_name));
2467 memset(var_val, '\0', sizeof(var_val));
2468 strncpy(var_name, pam_env[i], equals - pam_env[i]);
2469 strcpy(var_val, equals + 1);
2470 child_set_env(&env, &envsize, var_name, var_val);
2471 }
2472 }
2473 }
Damien Miller94388161999-10-29 09:57:31 +10002474#endif /* HAVE_LIBPAM */
2475
Damien Miller95def091999-11-25 00:26:21 +11002476 if (xauthfile)
2477 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002478
Damien Miller95def091999-11-25 00:26:21 +11002479 if (auth_get_socket_name() != NULL)
2480 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
2481 auth_get_socket_name());
Damien Miller776af5d1999-11-12 08:49:09 +11002482
Damien Miller5428f641999-11-25 11:54:57 +11002483 /* read $HOME/.ssh/environment. */
Damien Miller95def091999-11-25 00:26:21 +11002484 if (!options.use_login) {
2485 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
2486 read_environment_file(&env, &envsize, buf);
2487 }
Damien Miller95def091999-11-25 00:26:21 +11002488 if (debug_flag) {
Damien Miller5428f641999-11-25 11:54:57 +11002489 /* dump the environment */
Damien Miller95def091999-11-25 00:26:21 +11002490 fprintf(stderr, "Environment:\n");
2491 for (i = 0; env[i]; i++)
2492 fprintf(stderr, " %.200s\n", env[i]);
2493 }
Damien Miller5428f641999-11-25 11:54:57 +11002494 /*
2495 * Close the connection descriptors; note that this is the child, and
2496 * the server will still have the socket open, and it is important
2497 * that we do not shutdown it. Note that the descriptors cannot be
2498 * closed before building the environment, as we call
2499 * get_remote_ipaddr there.
2500 */
Damien Miller95def091999-11-25 00:26:21 +11002501 if (packet_get_connection_in() == packet_get_connection_out())
2502 close(packet_get_connection_in());
2503 else {
2504 close(packet_get_connection_in());
2505 close(packet_get_connection_out());
2506 }
Damien Miller5428f641999-11-25 11:54:57 +11002507 /*
2508 * Close all descriptors related to channels. They will still remain
2509 * open in the parent.
2510 */
2511 /* XXX better use close-on-exec? -markus */
Damien Miller95def091999-11-25 00:26:21 +11002512 channel_close_all();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002513
Damien Miller5428f641999-11-25 11:54:57 +11002514 /*
2515 * Close any extra file descriptors. Note that there may still be
2516 * descriptors left by system functions. They will be closed later.
2517 */
Damien Miller95def091999-11-25 00:26:21 +11002518 endpwent();
2519 endhostent();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002520
Damien Miller5428f641999-11-25 11:54:57 +11002521 /*
2522 * Close any extra open file descriptors so that we don\'t have them
2523 * hanging around in clients. Note that we want to do this after
2524 * initgroups, because at least on Solaris 2.3 it leaves file
2525 * descriptors open.
2526 */
Damien Miller95def091999-11-25 00:26:21 +11002527 for (i = 3; i < 64; i++)
2528 close(i);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002529
Damien Miller95def091999-11-25 00:26:21 +11002530 /* Change current directory to the user\'s home directory. */
2531 if (chdir(pw->pw_dir) < 0)
2532 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2533 pw->pw_dir, strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002534
Damien Miller5428f641999-11-25 11:54:57 +11002535 /*
2536 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
2537 * xauth are run in the proper environment.
2538 */
Damien Miller95def091999-11-25 00:26:21 +11002539 environ = env;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002540
Damien Miller5428f641999-11-25 11:54:57 +11002541 /*
2542 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
2543 * in this order).
2544 */
Damien Miller95def091999-11-25 00:26:21 +11002545 if (!options.use_login) {
2546 if (stat(SSH_USER_RC, &st) >= 0) {
2547 if (debug_flag)
2548 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002549
Damien Miller95def091999-11-25 00:26:21 +11002550 f = popen("/bin/sh " SSH_USER_RC, "w");
2551 if (f) {
2552 if (auth_proto != NULL && auth_data != NULL)
2553 fprintf(f, "%s %s\n", auth_proto, auth_data);
2554 pclose(f);
2555 } else
2556 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2557 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
2558 if (debug_flag)
2559 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002560
Damien Miller95def091999-11-25 00:26:21 +11002561 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2562 if (f) {
2563 if (auth_proto != NULL && auth_data != NULL)
2564 fprintf(f, "%s %s\n", auth_proto, auth_data);
2565 pclose(f);
2566 } else
2567 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2568 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002569#ifdef XAUTH_PATH
Damien Miller95def091999-11-25 00:26:21 +11002570 else {
Damien Miller5428f641999-11-25 11:54:57 +11002571 /* Add authority data to .Xauthority if appropriate. */
Damien Miller95def091999-11-25 00:26:21 +11002572 if (auth_proto != NULL && auth_data != NULL) {
2573 if (debug_flag)
2574 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2575 XAUTH_PATH, display, auth_proto, auth_data);
2576
2577 f = popen(XAUTH_PATH " -q -", "w");
2578 if (f) {
2579 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
2580 fclose(f);
2581 } else
2582 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2583 }
2584 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002585#endif /* XAUTH_PATH */
2586
Damien Miller95def091999-11-25 00:26:21 +11002587 /* Get the last component of the shell name. */
2588 cp = strrchr(shell, '/');
2589 if (cp)
2590 cp++;
2591 else
2592 cp = shell;
2593 }
Damien Miller5428f641999-11-25 11:54:57 +11002594 /*
2595 * If we have no command, execute the shell. In this case, the shell
2596 * name to be passed in argv[0] is preceded by '-' to indicate that
2597 * this is a login shell.
2598 */
Damien Miller95def091999-11-25 00:26:21 +11002599 if (!command) {
2600 if (!options.use_login) {
2601 char buf[256];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002602
Damien Miller5428f641999-11-25 11:54:57 +11002603 /*
2604 * Check for mail if we have a tty and it was enabled
2605 * in server options.
2606 */
Damien Miller95def091999-11-25 00:26:21 +11002607 if (ttyname && options.check_mail) {
2608 char *mailbox;
2609 struct stat mailstat;
2610 mailbox = getenv("MAIL");
2611 if (mailbox != NULL) {
2612 if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
2613 printf("No mail.\n");
2614 else if (mailstat.st_mtime < mailstat.st_atime)
2615 printf("You have mail.\n");
2616 else
2617 printf("You have new mail.\n");
2618 }
2619 }
2620 /* Start the shell. Set initial character to '-'. */
2621 buf[0] = '-';
2622 strncpy(buf + 1, cp, sizeof(buf) - 1);
2623 buf[sizeof(buf) - 1] = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002624
Damien Miller95def091999-11-25 00:26:21 +11002625 /* Execute the shell. */
2626 argv[0] = buf;
2627 argv[1] = NULL;
2628 execve(shell, argv, env);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002629
Damien Miller95def091999-11-25 00:26:21 +11002630 /* Executing the shell failed. */
2631 perror(shell);
2632 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002633
Damien Miller95def091999-11-25 00:26:21 +11002634 } else {
2635 /* Launch login(1). */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002636
Damien Miller95def091999-11-25 00:26:21 +11002637 execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(),
2638 "-p", "-f", "--", pw->pw_name, NULL);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002639
Damien Miller95def091999-11-25 00:26:21 +11002640 /* Login couldn't be executed, die. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002641
Damien Miller95def091999-11-25 00:26:21 +11002642 perror("login");
2643 exit(1);
2644 }
2645 }
Damien Miller5428f641999-11-25 11:54:57 +11002646 /*
2647 * Execute the command using the user's shell. This uses the -c
2648 * option to execute the command.
2649 */
Damien Miller95def091999-11-25 00:26:21 +11002650 argv[0] = (char *) cp;
2651 argv[1] = "-c";
2652 argv[2] = (char *) command;
2653 argv[3] = NULL;
2654 execve(shell, argv, env);
2655 perror(shell);
2656 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002657}