blob: 55608c0a4b09d058bd6e2cf12374405b0bfa1211 [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 Miller50945fa1999-12-09 10:31:37 +110014RCSID("$Id: sshd.c,v 1.37 1999/12/08 23:31:37 damien Exp $");
15
16#include <poll.h>
Damien Millerd4a8b7e1999-10-27 13:42:43 +100017
18#include "xmalloc.h"
19#include "rsa.h"
20#include "ssh.h"
21#include "pty.h"
22#include "packet.h"
23#include "buffer.h"
24#include "cipher.h"
25#include "mpaux.h"
26#include "servconf.h"
27#include "uidswap.h"
28#include "compat.h"
29
30#ifdef LIBWRAP
31#include <tcpd.h>
32#include <syslog.h>
33int allow_severity = LOG_INFO;
34int deny_severity = LOG_WARNING;
35#endif /* LIBWRAP */
36
37#ifndef O_NOCTTY
38#define O_NOCTTY 0
39#endif
40
Damien Millerd4a8b7e1999-10-27 13:42:43 +100041/* Local Xauthority file. */
Damien Miller5ce662a1999-11-11 17:57:39 +110042static char *xauthfile = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +100043
44/* Server configuration options. */
45ServerOptions options;
46
47/* Name of the server configuration file. */
48char *config_file_name = SERVER_CONFIG_FILE;
49
Damien Miller95def091999-11-25 00:26:21 +110050/*
51 * Debug mode flag. This can be set on the command line. If debug
52 * mode is enabled, extra debugging output will be sent to the system
53 * log, the daemon will not go to background, and will exit after processing
54 * the first connection.
55 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100056int debug_flag = 0;
57
58/* Flag indicating that the daemon is being started from inetd. */
59int inetd_flag = 0;
60
Damien Miller5ce662a1999-11-11 17:57:39 +110061/* debug goes to stderr unless inetd_flag is set */
62int log_stderr = 0;
63
Damien Millerd4a8b7e1999-10-27 13:42:43 +100064/* argv[0] without path. */
65char *av0;
66
67/* Saved arguments to main(). */
68char **saved_argv;
69
Damien Miller5428f641999-11-25 11:54:57 +110070/*
71 * This is set to the socket that the server is listening; this is used in
72 * the SIGHUP signal handler.
73 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100074int listen_sock;
75
Damien Miller5428f641999-11-25 11:54:57 +110076/*
77 * the client's version string, passed by sshd2 in compat mode. if != NULL,
78 * sshd will skip the version-number exchange
79 */
Damien Miller95def091999-11-25 00:26:21 +110080char *client_version_string = NULL;
81
82/* Flags set in auth-rsa from authorized_keys flags. These are set in auth-rsa.c. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100083int no_port_forwarding_flag = 0;
84int no_agent_forwarding_flag = 0;
85int no_x11_forwarding_flag = 0;
86int no_pty_flag = 0;
Damien Miller95def091999-11-25 00:26:21 +110087
88/* RSA authentication "command=" option. */
89char *forced_command = NULL;
90
91/* RSA authentication "environment=" options. */
92struct envstring *custom_environment = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +100093
94/* Session id for the current session. */
95unsigned char session_id[16];
96
Damien Miller5428f641999-11-25 11:54:57 +110097/*
98 * Any really sensitive data in the application is contained in this
99 * structure. The idea is that this structure could be locked into memory so
100 * that the pages do not get written into swap. However, there are some
101 * problems. The private key contains BIGNUMs, and we do not (in principle)
102 * have access to the internals of them, and locking just the structure is
103 * not very useful. Currently, memory locking is not implemented.
104 */
Damien Miller95def091999-11-25 00:26:21 +1100105struct {
106 RSA *private_key; /* Private part of server key. */
107 RSA *host_key; /* Private part of host key. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000108} sensitive_data;
109
Damien Miller5428f641999-11-25 11:54:57 +1100110/*
111 * Flag indicating whether the current session key has been used. This flag
112 * is set whenever the key is used, and cleared when the key is regenerated.
113 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000114int key_used = 0;
115
116/* This is set to true when SIGHUP is received. */
117int received_sighup = 0;
118
119/* Public side of the server key. This value is regenerated regularly with
120 the private key. */
121RSA *public_key;
122
123/* Prototypes for various functions defined later in this file. */
Damien Miller2ccf6611999-11-15 15:25:10 +1100124void do_connection();
125void do_authentication(char *user);
Damien Miller95def091999-11-25 00:26:21 +1100126void do_authloop(struct passwd * pw);
Damien Miller2ccf6611999-11-15 15:25:10 +1100127void do_fake_authloop(char *user);
Damien Miller95def091999-11-25 00:26:21 +1100128void do_authenticated(struct passwd * pw);
129void do_exec_pty(const char *command, int ptyfd, int ttyfd,
130 const char *ttyname, struct passwd * pw, const char *term,
131 const char *display, const char *auth_proto,
132 const char *auth_data);
133void do_exec_no_pty(const char *command, struct passwd * pw,
134 const char *display, const char *auth_proto,
135 const char *auth_data);
136void do_child(const char *command, struct passwd * pw, const char *term,
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000137 const char *display, const char *auth_proto,
138 const char *auth_data, const char *ttyname);
Damien Miller2ccf6611999-11-15 15:25:10 +1100139
Damien Miller06230761999-10-28 14:03:14 +1000140#ifdef HAVE_LIBPAM
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000141static int pamconv(int num_msg, const struct pam_message **msg,
Damien Miller95def091999-11-25 00:26:21 +1100142 struct pam_response **resp, void *appdata_ptr);
Damien Millerbf1c9b21999-12-09 10:16:54 +1100143void do_pam_account(char *username, char *remote_user);
144void do_pam_session(char *username, char *ttyname);
Damien Miller332e67f1999-10-27 23:42:05 +1000145void pam_cleanup_proc(void *context);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000146
147static struct pam_conv conv = {
Damien Miller95def091999-11-25 00:26:21 +1100148 pamconv,
149 NULL
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000150};
Damien Miller332e67f1999-10-27 23:42:05 +1000151struct pam_handle_t *pamh = NULL;
152const char *pampasswd = NULL;
Damien Miller356a0b01999-11-08 15:30:59 +1100153char *pamconv_msg = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000154
155static int pamconv(int num_msg, const struct pam_message **msg,
Damien Miller9072e181999-11-25 10:42:08 +1100156 struct pam_response **resp, void *appdata_ptr)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000157{
Damien Miller95def091999-11-25 00:26:21 +1100158 struct pam_response *reply;
159 int count;
160 size_t msg_len;
161 char *p;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000162
Damien Miller95def091999-11-25 00:26:21 +1100163 /* PAM will free this later */
164 reply = malloc(num_msg * sizeof(*reply));
165 if (reply == NULL)
166 return PAM_CONV_ERR;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000167
Damien Miller95def091999-11-25 00:26:21 +1100168 for(count = 0; count < num_msg; count++) {
169 switch (msg[count]->msg_style) {
170 case PAM_PROMPT_ECHO_OFF:
171 if (pampasswd == NULL) {
172 free(reply);
173 return PAM_CONV_ERR;
174 }
175 reply[count].resp_retcode = PAM_SUCCESS;
176 reply[count].resp = xstrdup(pampasswd);
177 break;
Damien Miller5bbbd361999-11-19 07:56:21 +1100178
Damien Miller95def091999-11-25 00:26:21 +1100179 case PAM_TEXT_INFO:
180 reply[count].resp_retcode = PAM_SUCCESS;
181 reply[count].resp = xstrdup("");
182
183 if (msg[count]->msg == NULL)
184 break;
185
186 debug("Adding PAM message: %s", msg[count]->msg);
187
188 msg_len = strlen(msg[count]->msg);
189 if (pamconv_msg) {
190 size_t n = strlen(pamconv_msg);
191 pamconv_msg = xrealloc(pamconv_msg, n + msg_len + 2);
192 p = pamconv_msg + n;
193 } else {
194 pamconv_msg = p = xmalloc(msg_len + 2);
195 }
196 memcpy(p, msg[count]->msg, msg_len);
197 p[msg_len] = '\n';
198 p[msg_len + 1] = '\0';
199 break;
200
201 case PAM_PROMPT_ECHO_ON:
202 case PAM_ERROR_MSG:
203 default:
204 free(reply);
205 return PAM_CONV_ERR;
206 }
Damien Miller356a0b01999-11-08 15:30:59 +1100207 }
Damien Miller332e67f1999-10-27 23:42:05 +1000208
Damien Miller95def091999-11-25 00:26:21 +1100209 *resp = reply;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000210
Damien Miller95def091999-11-25 00:26:21 +1100211 return PAM_SUCCESS;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000212}
213
214void pam_cleanup_proc(void *context)
215{
Damien Miller95def091999-11-25 00:26:21 +1100216 int pam_retval;
217
218 if (pamh != NULL)
219 {
220 pam_retval = pam_close_session((pam_handle_t *)pamh, 0);
221 if (pam_retval != PAM_SUCCESS) {
222 log("Cannot close PAM session: %.200s",
223 PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
224 }
225
226 pam_retval = pam_end((pam_handle_t *)pamh, pam_retval);
227 if (pam_retval != PAM_SUCCESS) {
228 log("Cannot release PAM authentication: %.200s",
229 PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
230 }
231 }
Damien Miller332e67f1999-10-27 23:42:05 +1000232}
233
Damien Millerbf1c9b21999-12-09 10:16:54 +1100234void do_pam_account(char *username, char *remote_user)
Damien Miller332e67f1999-10-27 23:42:05 +1000235{
Damien Miller95def091999-11-25 00:26:21 +1100236 int pam_retval;
Damien Miller332e67f1999-10-27 23:42:05 +1000237
Damien Millerdc33fc31999-12-04 20:24:48 +1100238 debug("PAM setting rhost to \"%.200s\"", get_canonical_hostname());
239 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RHOST,
240 get_canonical_hostname());
241 if (pam_retval != PAM_SUCCESS) {
242 log("PAM set rhost failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
243 do_fake_authloop(username);
Damien Miller95def091999-11-25 00:26:21 +1100244 }
245
246 if (remote_user != NULL) {
247 debug("PAM setting ruser to \"%.200s\"", remote_user);
248 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RUSER, remote_user);
249 if (pam_retval != PAM_SUCCESS) {
250 log("PAM set ruser failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
251 do_fake_authloop(username);
252 }
253 }
254
255 pam_retval = pam_acct_mgmt((pam_handle_t *)pamh, 0);
256 if (pam_retval != PAM_SUCCESS) {
257 log("PAM rejected by account configuration: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
258 do_fake_authloop(username);
259 }
Damien Millerbf1c9b21999-12-09 10:16:54 +1100260}
261
262void do_pam_session(char *username, char *ttyname)
263{
264 int pam_retval;
265
266 if (ttyname != NULL) {
267 debug("PAM setting tty to \"%.200s\"", ttyname);
268 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_TTY, ttyname);
269 if (pam_retval != PAM_SUCCESS)
270 fatal("PAM set tty failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
271 }
Damien Miller95def091999-11-25 00:26:21 +1100272
273 pam_retval = pam_open_session((pam_handle_t *)pamh, 0);
Damien Millerbf1c9b21999-12-09 10:16:54 +1100274 if (pam_retval != PAM_SUCCESS)
275 fatal("PAM session setup failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000276}
Damien Miller06230761999-10-28 14:03:14 +1000277#endif /* HAVE_LIBPAM */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000278
Damien Miller95def091999-11-25 00:26:21 +1100279/*
280 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
281 * the effect is to reread the configuration file (and to regenerate
282 * the server key).
283 */
284void
285sighup_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000286{
Damien Miller95def091999-11-25 00:26:21 +1100287 received_sighup = 1;
288 signal(SIGHUP, sighup_handler);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000289}
290
Damien Miller95def091999-11-25 00:26:21 +1100291/*
292 * Called from the main program after receiving SIGHUP.
293 * Restarts the server.
294 */
295void
296sighup_restart()
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000297{
Damien Miller95def091999-11-25 00:26:21 +1100298 log("Received SIGHUP; restarting.");
299 close(listen_sock);
300 execv(saved_argv[0], saved_argv);
301 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
302 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000303}
304
Damien Miller95def091999-11-25 00:26:21 +1100305/*
306 * Generic signal handler for terminating signals in the master daemon.
307 * These close the listen socket; not closing it seems to cause "Address
308 * already in use" problems on some machines, which is inconvenient.
309 */
310void
311sigterm_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000312{
Damien Miller95def091999-11-25 00:26:21 +1100313 log("Received signal %d; terminating.", sig);
314 close(listen_sock);
315 exit(255);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000316}
317
Damien Miller95def091999-11-25 00:26:21 +1100318/*
319 * SIGCHLD handler. This is called whenever a child dies. This will then
320 * reap any zombies left by exited c.
321 */
322void
323main_sigchld_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000324{
Damien Miller95def091999-11-25 00:26:21 +1100325 int save_errno = errno;
326 int status;
Damien Miller431f66b1999-11-21 18:31:57 +1100327
Damien Miller95def091999-11-25 00:26:21 +1100328 while (waitpid(-1, &status, WNOHANG) > 0)
329 ;
Damien Miller431f66b1999-11-21 18:31:57 +1100330
Damien Miller95def091999-11-25 00:26:21 +1100331 signal(SIGCHLD, main_sigchld_handler);
332 errno = save_errno;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000333}
334
Damien Miller95def091999-11-25 00:26:21 +1100335/*
336 * Signal handler for the alarm after the login grace period has expired.
337 */
338void
339grace_alarm_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000340{
Damien Miller95def091999-11-25 00:26:21 +1100341 /* Close the connection. */
342 packet_close();
343
344 /* Log error and exit. */
345 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000346}
347
Damien Miller95def091999-11-25 00:26:21 +1100348/*
349 * convert ssh auth msg type into description
350 */
351char *
352get_authname(int type)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000353{
Damien Miller95def091999-11-25 00:26:21 +1100354 switch (type) {
355 case SSH_CMSG_AUTH_PASSWORD:
356 return "password";
357 case SSH_CMSG_AUTH_RSA:
358 return "rsa";
359 case SSH_CMSG_AUTH_RHOSTS_RSA:
360 return "rhosts-rsa";
361 case SSH_CMSG_AUTH_RHOSTS:
362 return "rhosts";
363#ifdef KRB4
364 case SSH_CMSG_AUTH_KERBEROS:
365 return "kerberos";
366#endif
367#ifdef SKEY
368 case SSH_CMSG_AUTH_TIS_RESPONSE:
369 return "s/key";
370#endif
371 }
372 fatal("get_authname: unknown auth %d: internal error", type);
373 return NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000374}
375
Damien Miller95def091999-11-25 00:26:21 +1100376/*
377 * Signal handler for the key regeneration alarm. Note that this
378 * alarm only occurs in the daemon waiting for connections, and it does not
379 * do anything with the private key or random state before forking.
380 * Thus there should be no concurrency control/asynchronous execution
381 * problems.
382 */
383void
384key_regeneration_alarm(int sig)
385{
386 int save_errno = errno;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000387
Damien Miller95def091999-11-25 00:26:21 +1100388 /* Check if we should generate a new key. */
389 if (key_used) {
390 /* This should really be done in the background. */
391 log("Generating new %d bit RSA key.", options.server_key_bits);
392
393 if (sensitive_data.private_key != NULL)
394 RSA_free(sensitive_data.private_key);
395 sensitive_data.private_key = RSA_new();
396
397 if (public_key != NULL)
398 RSA_free(public_key);
399 public_key = RSA_new();
400
401 rsa_generate_key(sensitive_data.private_key, public_key,
402 options.server_key_bits);
403 arc4random_stir();
404 key_used = 0;
405 log("RSA key generation complete.");
406 }
407 /* Reschedule the alarm. */
408 signal(SIGALRM, key_regeneration_alarm);
409 alarm(options.key_regeneration_time);
410 errno = save_errno;
411}
412
413/*
414 * Main program for the daemon.
415 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000416int
417main(int ac, char **av)
418{
Damien Miller95def091999-11-25 00:26:21 +1100419 extern char *optarg;
420 extern int optind;
421 int opt, aux, sock_in, sock_out, newsock, i, pid, on = 1;
422 int remote_major, remote_minor;
423 int silentrsa = 0;
Damien Miller50945fa1999-12-09 10:31:37 +1100424 struct pollfd fds;
Damien Miller95def091999-11-25 00:26:21 +1100425 struct sockaddr_in sin;
426 char buf[100]; /* Must not be larger than remote_version. */
427 char remote_version[100]; /* Must be at least as big as buf. */
428 const char *remote_ip;
429 int remote_port;
430 char *comment;
431 FILE *f;
432 struct linger linger;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000433
Damien Miller95def091999-11-25 00:26:21 +1100434 /* Save argv[0]. */
435 saved_argv = av;
436 if (strchr(av[0], '/'))
437 av0 = strrchr(av[0], '/') + 1;
438 else
439 av0 = av[0];
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000440
Damien Miller95def091999-11-25 00:26:21 +1100441 /* Initialize configuration options to their default values. */
442 initialize_server_options(&options);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000443
Damien Miller95def091999-11-25 00:26:21 +1100444 /* Parse command-line arguments. */
445 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ")) != EOF) {
446 switch (opt) {
447 case 'f':
448 config_file_name = optarg;
449 break;
450 case 'd':
451 debug_flag = 1;
452 options.log_level = SYSLOG_LEVEL_DEBUG;
453 break;
454 case 'i':
455 inetd_flag = 1;
456 break;
457 case 'Q':
458 silentrsa = 1;
459 break;
460 case 'q':
461 options.log_level = SYSLOG_LEVEL_QUIET;
462 break;
463 case 'b':
464 options.server_key_bits = atoi(optarg);
465 break;
466 case 'p':
467 options.port = atoi(optarg);
468 break;
469 case 'g':
470 options.login_grace_time = atoi(optarg);
471 break;
472 case 'k':
473 options.key_regeneration_time = atoi(optarg);
474 break;
475 case 'h':
476 options.host_key_file = optarg;
477 break;
478 case 'V':
479 client_version_string = optarg;
480 /* only makes sense with inetd_flag, i.e. no listen() */
481 inetd_flag = 1;
482 break;
483 case '?':
484 default:
485 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
486 fprintf(stderr, "Usage: %s [options]\n", av0);
487 fprintf(stderr, "Options:\n");
Damien Miller5428f641999-11-25 11:54:57 +1100488 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE);
Damien Miller95def091999-11-25 00:26:21 +1100489 fprintf(stderr, " -d Debugging mode\n");
490 fprintf(stderr, " -i Started from inetd\n");
491 fprintf(stderr, " -q Quiet (no logging)\n");
492 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
493 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
494 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
495 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
496 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
497 HOST_KEY_FILE);
498 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000499 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000500 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000501
Damien Miller95def091999-11-25 00:26:21 +1100502 /* check if RSA support exists */
503 if (rsa_alive() == 0) {
504 if (silentrsa == 0)
505 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
506 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
507 exit(1);
508 }
509 /* Read server configuration options from the configuration file. */
510 read_server_config(&options, config_file_name);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000511
Damien Miller95def091999-11-25 00:26:21 +1100512 /* Fill in default values for those options not explicitly set. */
513 fill_default_server_options(&options);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000514
Damien Miller95def091999-11-25 00:26:21 +1100515 /* Check certain values for sanity. */
516 if (options.server_key_bits < 512 ||
517 options.server_key_bits > 32768) {
518 fprintf(stderr, "Bad server key size.\n");
519 exit(1);
520 }
521 if (options.port < 1 || options.port > 65535) {
522 fprintf(stderr, "Bad port number.\n");
523 exit(1);
524 }
525 /* Check that there are no remaining arguments. */
526 if (optind < ac) {
527 fprintf(stderr, "Extra argument %s.\n", av[optind]);
528 exit(1);
529 }
530 /* Force logging to stderr while loading the private host key
531 unless started from inetd */
532 log_init(av0, options.log_level, options.log_facility, !inetd_flag);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000533
Damien Miller95def091999-11-25 00:26:21 +1100534 debug("sshd version %.100s", SSH_VERSION);
Damien Miller2ccf6611999-11-15 15:25:10 +1100535
Damien Miller95def091999-11-25 00:26:21 +1100536 sensitive_data.host_key = RSA_new();
537 errno = 0;
538 /* Load the host key. It must have empty passphrase. */
539 if (!load_private_key(options.host_key_file, "",
540 sensitive_data.host_key, &comment)) {
541 error("Could not load host key: %.200s: %.100s",
542 options.host_key_file, strerror(errno));
543 exit(1);
544 }
545 xfree(comment);
546
547 /* Initialize the log (it is reinitialized below in case we
548 forked). */
549 if (debug_flag && !inetd_flag)
550 log_stderr = 1;
551 log_init(av0, options.log_level, options.log_facility, log_stderr);
552
553 /* If not in debugging mode, and not started from inetd,
554 disconnect from the controlling terminal, and fork. The
555 original process exits. */
556 if (!debug_flag && !inetd_flag) {
557#ifdef TIOCNOTTY
558 int fd;
559#endif /* TIOCNOTTY */
560 if (daemon(0, 0) < 0)
561 fatal("daemon() failed: %.200s", strerror(errno));
562
563 /* Disconnect from the controlling tty. */
564#ifdef TIOCNOTTY
565 fd = open("/dev/tty", O_RDWR | O_NOCTTY);
566 if (fd >= 0) {
567 (void) ioctl(fd, TIOCNOTTY, NULL);
568 close(fd);
569 }
570#endif /* TIOCNOTTY */
571 }
572 /* Reinitialize the log (because of the fork above). */
573 log_init(av0, options.log_level, options.log_facility, log_stderr);
574
575 /* Check that server and host key lengths differ sufficiently.
576 This is necessary to make double encryption work with rsaref.
577 Oh, I hate software patents. I dont know if this can go? Niels */
578 if (options.server_key_bits >
579 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
580 options.server_key_bits <
581 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
582 options.server_key_bits =
583 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
584 debug("Forcing server key to %d bits to make it differ from host key.",
585 options.server_key_bits);
586 }
587 /* Do not display messages to stdout in RSA code. */
588 rsa_set_verbose(0);
589
590 /* Initialize the random number generator. */
591 arc4random_stir();
592
593 /* Chdir to the root directory so that the current disk can be
594 unmounted if desired. */
595 chdir("/");
596
597 /* Close connection cleanly after attack. */
598 cipher_attack_detected = packet_disconnect;
599
600 /* Start listening for a socket, unless started from inetd. */
601 if (inetd_flag) {
602 int s1, s2;
603 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
604 s2 = dup(s1);
605 sock_in = dup(0);
606 sock_out = dup(1);
607 /* We intentionally do not close the descriptors 0, 1, and 2
608 as our code for setting the descriptors won\'t work
609 if ttyfd happens to be one of those. */
610 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
611
612 public_key = RSA_new();
613 sensitive_data.private_key = RSA_new();
614
615 log("Generating %d bit RSA key.", options.server_key_bits);
616 rsa_generate_key(sensitive_data.private_key, public_key,
617 options.server_key_bits);
618 arc4random_stir();
619 log("RSA key generation complete.");
620 } else {
621 /* Create socket for listening. */
622 listen_sock = socket(AF_INET, SOCK_STREAM, 0);
623 if (listen_sock < 0)
624 fatal("socket: %.100s", strerror(errno));
625
626 /* Set socket options. We try to make the port reusable
627 and have it close as fast as possible without waiting
628 in unnecessary wait states on close. */
629 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on,
630 sizeof(on));
631 linger.l_onoff = 1;
632 linger.l_linger = 5;
633 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, (void *) &linger,
634 sizeof(linger));
635
Damien Miller95def091999-11-25 00:26:21 +1100636 memset(&sin, 0, sizeof(sin));
637 sin.sin_family = AF_INET;
638 sin.sin_addr = options.listen_addr;
639 sin.sin_port = htons(options.port);
640
Damien Miller95def091999-11-25 00:26:21 +1100641 if (bind(listen_sock, (struct sockaddr *) & sin, sizeof(sin)) < 0) {
642 error("bind: %.100s", strerror(errno));
643 shutdown(listen_sock, SHUT_RDWR);
644 close(listen_sock);
645 fatal("Bind to port %d failed.", options.port);
646 }
647 if (!debug_flag) {
Damien Miller5428f641999-11-25 11:54:57 +1100648 /*
649 * Record our pid in /etc/sshd_pid to make it easier
650 * to kill the correct sshd. We don\'t want to do
651 * this before the bind above because the bind will
652 * fail if there already is a daemon, and this will
653 * overwrite any old pid in the file.
654 */
Damien Miller95def091999-11-25 00:26:21 +1100655 f = fopen(SSH_DAEMON_PID_FILE, "w");
656 if (f) {
657 fprintf(f, "%u\n", (unsigned int) getpid());
658 fclose(f);
659 }
660 }
661
662 log("Server listening on port %d.", options.port);
663 if (listen(listen_sock, 5) < 0)
664 fatal("listen: %.100s", strerror(errno));
665
666 public_key = RSA_new();
667 sensitive_data.private_key = RSA_new();
668
669 log("Generating %d bit RSA key.", options.server_key_bits);
670 rsa_generate_key(sensitive_data.private_key, public_key,
671 options.server_key_bits);
672 arc4random_stir();
673 log("RSA key generation complete.");
674
675 /* Schedule server key regeneration alarm. */
676 signal(SIGALRM, key_regeneration_alarm);
677 alarm(options.key_regeneration_time);
678
679 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
680 signal(SIGHUP, sighup_handler);
681 signal(SIGTERM, sigterm_handler);
682 signal(SIGQUIT, sigterm_handler);
683
684 /* Arrange SIGCHLD to be caught. */
685 signal(SIGCHLD, main_sigchld_handler);
686
Damien Miller5428f641999-11-25 11:54:57 +1100687 /*
688 * Stay listening for connections until the system crashes or
689 * the daemon is killed with a signal.
690 */
Damien Miller95def091999-11-25 00:26:21 +1100691 for (;;) {
692 if (received_sighup)
693 sighup_restart();
Damien Miller50945fa1999-12-09 10:31:37 +1100694 /* Wait in poll until there is a connection. */
695 memset(&fds, 0, sizeof(fds));
696 fds.fd = listen_sock;
697 fds.events = POLLIN;
698 if (poll(&fds, 1, -1) == -1) {
699 if (errno == EINTR)
700 continue;
701 fatal("poll: %.100s", strerror(errno));
702 /*NOTREACHED*/
703 }
704 if (fds.revents == 0)
705 continue;
Damien Miller95def091999-11-25 00:26:21 +1100706 aux = sizeof(sin);
707 newsock = accept(listen_sock, (struct sockaddr *) & sin, &aux);
708 if (received_sighup)
709 sighup_restart();
710 if (newsock < 0) {
711 if (errno == EINTR)
712 continue;
713 error("accept: %.100s", strerror(errno));
714 continue;
715 }
Damien Miller5428f641999-11-25 11:54:57 +1100716 /*
717 * Got connection. Fork a child to handle it, unless
718 * we are in debugging mode.
719 */
Damien Miller95def091999-11-25 00:26:21 +1100720 if (debug_flag) {
Damien Miller5428f641999-11-25 11:54:57 +1100721 /*
722 * In debugging mode. Close the listening
723 * socket, and start processing the
724 * connection without forking.
725 */
Damien Miller95def091999-11-25 00:26:21 +1100726 debug("Server will not fork when running in debugging mode.");
727 close(listen_sock);
728 sock_in = newsock;
729 sock_out = newsock;
730 pid = getpid();
731 break;
732 } else {
Damien Miller5428f641999-11-25 11:54:57 +1100733 /*
734 * Normal production daemon. Fork, and have
735 * the child process the connection. The
736 * parent continues listening.
737 */
Damien Miller95def091999-11-25 00:26:21 +1100738 if ((pid = fork()) == 0) {
Damien Miller5428f641999-11-25 11:54:57 +1100739 /*
740 * Child. Close the listening socket, and start using the
741 * accepted socket. Reinitialize logging (since our pid has
742 * changed). We break out of the loop to handle the connection.
743 */
Damien Miller95def091999-11-25 00:26:21 +1100744 close(listen_sock);
745 sock_in = newsock;
746 sock_out = newsock;
747 log_init(av0, options.log_level, options.log_facility, log_stderr);
748 break;
749 }
750 }
751
752 /* Parent. Stay in the loop. */
753 if (pid < 0)
754 error("fork: %.100s", strerror(errno));
755 else
756 debug("Forked child %d.", pid);
757
758 /* Mark that the key has been used (it was "given" to the child). */
759 key_used = 1;
760
761 arc4random_stir();
762
763 /* Close the new socket (the child is now taking care of it). */
764 close(newsock);
765 }
766 }
767
768 /* This is the child processing a new connection. */
769
Damien Miller5428f641999-11-25 11:54:57 +1100770 /*
771 * Disable the key regeneration alarm. We will not regenerate the
772 * key since we are no longer in a position to give it to anyone. We
773 * will not restart on SIGHUP since it no longer makes sense.
774 */
Damien Miller95def091999-11-25 00:26:21 +1100775 alarm(0);
776 signal(SIGALRM, SIG_DFL);
777 signal(SIGHUP, SIG_DFL);
778 signal(SIGTERM, SIG_DFL);
779 signal(SIGQUIT, SIG_DFL);
780 signal(SIGCHLD, SIG_DFL);
781
Damien Miller5428f641999-11-25 11:54:57 +1100782 /*
783 * Set socket options for the connection. We want the socket to
784 * close as fast as possible without waiting for anything. If the
785 * connection is not a socket, these will do nothing.
786 */
787 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
Damien Miller95def091999-11-25 00:26:21 +1100788 linger.l_onoff = 1;
789 linger.l_linger = 5;
790 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
791
Damien Miller5428f641999-11-25 11:54:57 +1100792 /*
793 * Register our connection. This turns encryption off because we do
794 * not have a key.
795 */
Damien Miller95def091999-11-25 00:26:21 +1100796 packet_set_connection(sock_in, sock_out);
797
798 remote_port = get_remote_port();
799 remote_ip = get_remote_ipaddr();
800
801 /* Check whether logins are denied from this host. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000802#ifdef LIBWRAP
Damien Miller95def091999-11-25 00:26:21 +1100803 {
804 struct request_info req;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000805
Damien Miller95def091999-11-25 00:26:21 +1100806 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
807 fromhost(&req);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000808
Damien Miller95def091999-11-25 00:26:21 +1100809 if (!hosts_access(&req)) {
810 close(sock_in);
811 close(sock_out);
812 refuse(&req);
813 }
814 verbose("Connection from %.500s port %d", eval_client(&req), remote_port);
815 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000816#else
Damien Miller95def091999-11-25 00:26:21 +1100817 /* Log the connection. */
818 verbose("Connection from %.500s port %d", remote_ip, remote_port);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000819#endif /* LIBWRAP */
820
Damien Miller5428f641999-11-25 11:54:57 +1100821 /*
822 * We don\'t want to listen forever unless the other side
823 * successfully authenticates itself. So we set up an alarm which is
824 * cleared after successful authentication. A limit of zero
825 * indicates no limit. Note that we don\'t set the alarm in debugging
826 * mode; it is just annoying to have the server exit just when you
827 * are about to discover the bug.
828 */
Damien Miller95def091999-11-25 00:26:21 +1100829 signal(SIGALRM, grace_alarm_handler);
830 if (!debug_flag)
831 alarm(options.login_grace_time);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000832
Damien Miller95def091999-11-25 00:26:21 +1100833 if (client_version_string != NULL) {
834 /* we are exec'ed by sshd2, so skip exchange of protocol version */
835 strlcpy(buf, client_version_string, sizeof(buf));
836 } else {
837 /* Send our protocol version identification. */
838 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
839 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
Damien Miller037a0dc1999-12-07 15:38:31 +1100840 if (atomicio(write, sock_out, buf, strlen(buf)) != strlen(buf))
Damien Miller95def091999-11-25 00:26:21 +1100841 fatal("Could not write ident string to %s.", get_remote_ipaddr());
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000842
Damien Miller95def091999-11-25 00:26:21 +1100843 /* Read other side\'s version identification. */
844 for (i = 0; i < sizeof(buf) - 1; i++) {
845 if (read(sock_in, &buf[i], 1) != 1)
846 fatal("Did not receive ident string from %s.", get_remote_ipaddr());
847 if (buf[i] == '\r') {
848 buf[i] = '\n';
849 buf[i + 1] = 0;
850 break;
851 }
852 if (buf[i] == '\n') {
853 /* buf[i] == '\n' */
854 buf[i + 1] = 0;
855 break;
856 }
857 }
858 buf[sizeof(buf) - 1] = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000859 }
Damien Miller95def091999-11-25 00:26:21 +1100860
Damien Miller5428f641999-11-25 11:54:57 +1100861 /*
862 * Check that the versions match. In future this might accept
863 * several versions and set appropriate flags to handle them.
864 */
Damien Miller95def091999-11-25 00:26:21 +1100865 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
Damien Miller037a0dc1999-12-07 15:38:31 +1100866 remote_version) != 3) {
867 char *s = "Protocol mismatch.\n";
868
869 (void) atomicio(write, sock_out, s, strlen(s));
Damien Miller95def091999-11-25 00:26:21 +1100870 close(sock_in);
871 close(sock_out);
872 fatal("Bad protocol version identification '%.100s' from %s",
873 buf, get_remote_ipaddr());
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000874 }
Damien Miller95def091999-11-25 00:26:21 +1100875 debug("Client protocol version %d.%d; client software version %.100s",
876 remote_major, remote_minor, remote_version);
877 if (remote_major != PROTOCOL_MAJOR) {
Damien Miller037a0dc1999-12-07 15:38:31 +1100878 char *s = "Protocol major versions differ.\n";
879
880 (void) atomicio(write, sock_out, s, strlen(s));
Damien Miller95def091999-11-25 00:26:21 +1100881 close(sock_in);
882 close(sock_out);
883 fatal("Protocol major versions differ for %s: %d vs. %d",
884 get_remote_ipaddr(),
885 PROTOCOL_MAJOR, remote_major);
886 }
887 /* Check that the client has sufficiently high software version. */
888 if (remote_major == 1 && remote_minor < 3)
889 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 +1000890
Damien Miller95def091999-11-25 00:26:21 +1100891 if (remote_major == 1 && remote_minor == 3) {
892 enable_compat13();
893 if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
894 debug("Agent forwarding disabled, remote version is not compatible.");
895 no_agent_forwarding_flag = 1;
896 }
897 }
Damien Miller5428f641999-11-25 11:54:57 +1100898 /*
899 * Check that the connection comes from a privileged port. Rhosts-
900 * and Rhosts-RSA-Authentication only make sense from priviledged
901 * programs. Of course, if the intruder has root access on his local
902 * machine, he can connect from any port. So do not use these
903 * authentication methods from machines that you do not trust.
904 */
Damien Miller95def091999-11-25 00:26:21 +1100905 if (remote_port >= IPPORT_RESERVED ||
906 remote_port < IPPORT_RESERVED / 2) {
907 options.rhosts_authentication = 0;
908 options.rhosts_rsa_authentication = 0;
909 }
910 packet_set_nonblocking();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000911
Damien Miller95def091999-11-25 00:26:21 +1100912 /* Handle the connection. */
913 do_connection();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000914
915#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +1100916 /* Cleanup user's ticket cache file. */
917 if (options.kerberos_ticket_cleanup)
918 (void) dest_tkt();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000919#endif /* KRB4 */
920
Damien Miller95def091999-11-25 00:26:21 +1100921 /* Cleanup user's local Xauthority file. */
922 if (xauthfile)
923 unlink(xauthfile);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000924
Damien Miller95def091999-11-25 00:26:21 +1100925 /* The connection has been terminated. */
926 verbose("Closing connection to %.100s", remote_ip);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000927
Damien Miller06230761999-10-28 14:03:14 +1000928#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +1100929 {
930 int retval;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000931
Damien Miller95def091999-11-25 00:26:21 +1100932 if (pamh != NULL) {
933 debug("Closing PAM session.");
934 retval = pam_close_session((pam_handle_t *)pamh, 0);
935
936 debug("Terminating PAM library.");
937 if (pam_end((pam_handle_t *)pamh, retval) != PAM_SUCCESS)
938 log("Cannot release PAM authentication.");
939
940 fatal_remove_cleanup(&pam_cleanup_proc, NULL);
941 }
942 }
Damien Miller06230761999-10-28 14:03:14 +1000943#endif /* HAVE_LIBPAM */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000944
Damien Miller95def091999-11-25 00:26:21 +1100945 packet_close();
946 exit(0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000947}
948
Damien Miller95def091999-11-25 00:26:21 +1100949/*
950 * Process an incoming connection. Protocol version identifiers have already
951 * been exchanged. This sends server key and performs the key exchange.
952 * Server and host keys will no longer be needed after this functions.
953 */
Damien Miller2ccf6611999-11-15 15:25:10 +1100954void
955do_connection()
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000956{
Damien Miller95def091999-11-25 00:26:21 +1100957 int i, len;
958 BIGNUM *session_key_int;
959 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
960 unsigned char check_bytes[8];
961 char *user;
962 unsigned int cipher_type, auth_mask, protocol_flags;
963 int plen, slen;
964 u_int32_t rand = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000965
Damien Miller5428f641999-11-25 11:54:57 +1100966 /*
967 * Generate check bytes that the client must send back in the user
968 * packet in order for it to be accepted; this is used to defy ip
969 * spoofing attacks. Note that this only works against somebody
970 * doing IP spoofing from a remote machine; any machine on the local
971 * network can still see outgoing packets and catch the random
972 * cookie. This only affects rhosts authentication, and this is one
973 * of the reasons why it is inherently insecure.
974 */
Damien Miller95def091999-11-25 00:26:21 +1100975 for (i = 0; i < 8; i++) {
976 if (i % 4 == 0)
977 rand = arc4random();
978 check_bytes[i] = rand & 0xff;
979 rand >>= 8;
980 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000981
Damien Miller5428f641999-11-25 11:54:57 +1100982 /*
983 * Send our public key. We include in the packet 64 bits of random
984 * data that must be matched in the reply in order to prevent IP
985 * spoofing.
986 */
Damien Miller95def091999-11-25 00:26:21 +1100987 packet_start(SSH_SMSG_PUBLIC_KEY);
988 for (i = 0; i < 8; i++)
989 packet_put_char(check_bytes[i]);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000990
Damien Miller95def091999-11-25 00:26:21 +1100991 /* Store our public server RSA key. */
992 packet_put_int(BN_num_bits(public_key->n));
993 packet_put_bignum(public_key->e);
994 packet_put_bignum(public_key->n);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000995
Damien Miller95def091999-11-25 00:26:21 +1100996 /* Store our public host RSA key. */
997 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
998 packet_put_bignum(sensitive_data.host_key->e);
999 packet_put_bignum(sensitive_data.host_key->n);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001000
Damien Miller95def091999-11-25 00:26:21 +11001001 /* Put protocol flags. */
1002 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001003
Damien Miller95def091999-11-25 00:26:21 +11001004 /* Declare which ciphers we support. */
1005 packet_put_int(cipher_mask());
1006
1007 /* Declare supported authentication types. */
1008 auth_mask = 0;
1009 if (options.rhosts_authentication)
1010 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1011 if (options.rhosts_rsa_authentication)
1012 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1013 if (options.rsa_authentication)
1014 auth_mask |= 1 << SSH_AUTH_RSA;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001015#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11001016 if (options.kerberos_authentication)
1017 auth_mask |= 1 << SSH_AUTH_KERBEROS;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001018#endif
1019#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11001020 if (options.kerberos_tgt_passing)
1021 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1022 if (options.afs_token_passing)
1023 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001024#endif
Damien Miller95def091999-11-25 00:26:21 +11001025#ifdef SKEY
1026 if (options.skey_authentication == 1)
1027 auth_mask |= 1 << SSH_AUTH_TIS;
1028#endif
1029 if (options.password_authentication)
1030 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1031 packet_put_int(auth_mask);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001032
Damien Miller95def091999-11-25 00:26:21 +11001033 /* Send the packet and wait for it to be sent. */
1034 packet_send();
1035 packet_write_wait();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001036
Damien Miller95def091999-11-25 00:26:21 +11001037 debug("Sent %d bit public key and %d bit host key.",
1038 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001039
Damien Miller95def091999-11-25 00:26:21 +11001040 /* Read clients reply (cipher type and session key). */
1041 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001042
Damien Miller50945fa1999-12-09 10:31:37 +11001043 /* Get cipher type and check whether we accept this. */
Damien Miller95def091999-11-25 00:26:21 +11001044 cipher_type = packet_get_char();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001045
Damien Miller50945fa1999-12-09 10:31:37 +11001046 if (!(cipher_mask() & (1 << cipher_type)))
1047 packet_disconnect("Warning: client selects unsupported cipher.");
1048
Damien Miller95def091999-11-25 00:26:21 +11001049 /* Get check bytes from the packet. These must match those we
1050 sent earlier with the public key packet. */
1051 for (i = 0; i < 8; i++)
1052 if (check_bytes[i] != packet_get_char())
1053 packet_disconnect("IP Spoofing check bytes do not match.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001054
Damien Miller95def091999-11-25 00:26:21 +11001055 debug("Encryption type: %.200s", cipher_name(cipher_type));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001056
Damien Miller95def091999-11-25 00:26:21 +11001057 /* Get the encrypted integer. */
1058 session_key_int = BN_new();
1059 packet_get_bignum(session_key_int, &slen);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001060
Damien Miller95def091999-11-25 00:26:21 +11001061 protocol_flags = packet_get_int();
1062 packet_set_protocol_flags(protocol_flags);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001063
Damien Miller95def091999-11-25 00:26:21 +11001064 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001065
Damien Miller5428f641999-11-25 11:54:57 +11001066 /*
1067 * Decrypt it using our private server key and private host key (key
1068 * with larger modulus first).
1069 */
Damien Miller95def091999-11-25 00:26:21 +11001070 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1071 /* Private key has bigger modulus. */
1072 if (BN_num_bits(sensitive_data.private_key->n) <
1073 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1074 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1075 get_remote_ipaddr(),
1076 BN_num_bits(sensitive_data.private_key->n),
1077 BN_num_bits(sensitive_data.host_key->n),
1078 SSH_KEY_BITS_RESERVED);
1079 }
1080 rsa_private_decrypt(session_key_int, session_key_int,
1081 sensitive_data.private_key);
1082 rsa_private_decrypt(session_key_int, session_key_int,
1083 sensitive_data.host_key);
1084 } else {
1085 /* Host key has bigger modulus (or they are equal). */
1086 if (BN_num_bits(sensitive_data.host_key->n) <
1087 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1088 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1089 get_remote_ipaddr(),
1090 BN_num_bits(sensitive_data.host_key->n),
1091 BN_num_bits(sensitive_data.private_key->n),
1092 SSH_KEY_BITS_RESERVED);
1093 }
1094 rsa_private_decrypt(session_key_int, session_key_int,
1095 sensitive_data.host_key);
1096 rsa_private_decrypt(session_key_int, session_key_int,
1097 sensitive_data.private_key);
1098 }
Damien Miller356a0b01999-11-08 15:30:59 +11001099
Damien Miller95def091999-11-25 00:26:21 +11001100 compute_session_id(session_id, check_bytes,
1101 sensitive_data.host_key->n,
1102 sensitive_data.private_key->n);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001103
Damien Miller5428f641999-11-25 11:54:57 +11001104 /*
1105 * Extract session key from the decrypted integer. The key is in the
1106 * least significant 256 bits of the integer; the first byte of the
1107 * key is in the highest bits.
1108 */
Damien Miller95def091999-11-25 00:26:21 +11001109 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1110 len = BN_num_bytes(session_key_int);
1111 if (len < 0 || len > sizeof(session_key))
1112 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1113 get_remote_ipaddr(),
1114 len, sizeof(session_key));
1115 memset(session_key, 0, sizeof(session_key));
1116 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001117
Damien Miller95def091999-11-25 00:26:21 +11001118 /* Xor the first 16 bytes of the session key with the session id. */
1119 for (i = 0; i < 16; i++)
1120 session_key[i] ^= session_id[i];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001121
Damien Miller95def091999-11-25 00:26:21 +11001122 /* Destroy the decrypted integer. It is no longer needed. */
1123 BN_clear_free(session_key_int);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001124
Damien Miller95def091999-11-25 00:26:21 +11001125 /* Set the session key. From this on all communications will be encrypted. */
1126 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001127
Damien Miller95def091999-11-25 00:26:21 +11001128 /* Destroy our copy of the session key. It is no longer needed. */
1129 memset(session_key, 0, sizeof(session_key));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001130
Damien Miller95def091999-11-25 00:26:21 +11001131 debug("Received session key; encryption turned on.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001132
Damien Miller95def091999-11-25 00:26:21 +11001133 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1134 packet_start(SSH_SMSG_SUCCESS);
1135 packet_send();
1136 packet_write_wait();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001137
Damien Miller95def091999-11-25 00:26:21 +11001138 /* Get the name of the user that we wish to log in as. */
1139 packet_read_expect(&plen, SSH_CMSG_USER);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001140
Damien Miller95def091999-11-25 00:26:21 +11001141 /* Get the user name. */
1142 {
1143 int ulen;
1144 user = packet_get_string(&ulen);
1145 packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
1146 }
1147
1148 /* Destroy the private and public keys. They will no longer be needed. */
1149 RSA_free(public_key);
1150 RSA_free(sensitive_data.private_key);
1151 RSA_free(sensitive_data.host_key);
1152
1153 setproctitle("%s", user);
1154 /* Do the authentication. */
1155 do_authentication(user);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001156}
1157
Damien Miller95def091999-11-25 00:26:21 +11001158/*
1159 * Check if the user is allowed to log in via ssh. If user is listed in
1160 * DenyUsers or user's primary group is listed in DenyGroups, false will
1161 * be returned. If AllowUsers isn't empty and user isn't listed there, or
1162 * if AllowGroups isn't empty and user isn't listed there, false will be
1163 * returned. Otherwise true is returned.
1164 * XXX This function should also check if user has a valid shell
1165 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001166static int
Damien Miller95def091999-11-25 00:26:21 +11001167allowed_user(struct passwd * pw)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001168{
Damien Miller95def091999-11-25 00:26:21 +11001169 struct group *grp;
1170 int i;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001171
Damien Miller95def091999-11-25 00:26:21 +11001172 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1173 if (!pw)
1174 return 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001175
Damien Miller95def091999-11-25 00:26:21 +11001176 /* XXX Should check for valid login shell */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001177
Damien Miller95def091999-11-25 00:26:21 +11001178 /* Return false if user is listed in DenyUsers */
1179 if (options.num_deny_users > 0) {
1180 if (!pw->pw_name)
1181 return 0;
1182 for (i = 0; i < options.num_deny_users; i++)
1183 if (match_pattern(pw->pw_name, options.deny_users[i]))
1184 return 0;
1185 }
Damien Miller5428f641999-11-25 11:54:57 +11001186 /* Return false if AllowUsers isn't empty and user isn't listed there */
Damien Miller95def091999-11-25 00:26:21 +11001187 if (options.num_allow_users > 0) {
1188 if (!pw->pw_name)
1189 return 0;
1190 for (i = 0; i < options.num_allow_users; i++)
1191 if (match_pattern(pw->pw_name, options.allow_users[i]))
1192 break;
1193 /* i < options.num_allow_users iff we break for loop */
1194 if (i >= options.num_allow_users)
1195 return 0;
1196 }
1197 /* Get the primary group name if we need it. Return false if it fails */
1198 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
1199 grp = getgrgid(pw->pw_gid);
1200 if (!grp)
1201 return 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001202
Damien Miller95def091999-11-25 00:26:21 +11001203 /* Return false if user's group is listed in DenyGroups */
1204 if (options.num_deny_groups > 0) {
1205 if (!grp->gr_name)
1206 return 0;
1207 for (i = 0; i < options.num_deny_groups; i++)
1208 if (match_pattern(grp->gr_name, options.deny_groups[i]))
1209 return 0;
1210 }
Damien Miller5428f641999-11-25 11:54:57 +11001211 /*
1212 * Return false if AllowGroups isn't empty and user's group
1213 * isn't listed there
1214 */
Damien Miller95def091999-11-25 00:26:21 +11001215 if (options.num_allow_groups > 0) {
1216 if (!grp->gr_name)
1217 return 0;
1218 for (i = 0; i < options.num_allow_groups; i++)
1219 if (match_pattern(grp->gr_name, options.allow_groups[i]))
1220 break;
1221 /* i < options.num_allow_groups iff we break for
1222 loop */
1223 if (i >= options.num_allow_groups)
1224 return 0;
1225 }
1226 }
1227 /* We found no reason not to let this user try to log on... */
1228 return 1;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001229}
1230
Damien Miller95def091999-11-25 00:26:21 +11001231/*
1232 * Performs authentication of an incoming connection. Session key has already
1233 * been exchanged and encryption is enabled. User is the user name to log
1234 * in as (received from the client).
1235 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001236void
Damien Miller2ccf6611999-11-15 15:25:10 +11001237do_authentication(char *user)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001238{
Damien Miller95def091999-11-25 00:26:21 +11001239 struct passwd *pw, pwcopy;
Damien Miller2ccf6611999-11-15 15:25:10 +11001240
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001241#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11001242 /* If machine has AFS, set process authentication group. */
1243 if (k_hasafs()) {
1244 k_setpag();
1245 k_unlog();
1246 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001247#endif /* AFS */
Damien Miller95def091999-11-25 00:26:21 +11001248
1249 /* Verify that the user is a valid user. */
1250 pw = getpwnam(user);
1251 if (!pw || !allowed_user(pw))
1252 do_fake_authloop(user);
1253
1254 /* Take a copy of the returned structure. */
1255 memset(&pwcopy, 0, sizeof(pwcopy));
1256 pwcopy.pw_name = xstrdup(pw->pw_name);
1257 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1258 pwcopy.pw_uid = pw->pw_uid;
1259 pwcopy.pw_gid = pw->pw_gid;
1260 pwcopy.pw_dir = xstrdup(pw->pw_dir);
1261 pwcopy.pw_shell = xstrdup(pw->pw_shell);
1262 pw = &pwcopy;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001263
Damien Miller06230761999-10-28 14:03:14 +10001264#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001265 {
1266 int pam_retval;
Damien Miller2ccf6611999-11-15 15:25:10 +11001267
Damien Miller95def091999-11-25 00:26:21 +11001268 debug("Starting up PAM with username \"%.200s\"", pw->pw_name);
Damien Miller2ccf6611999-11-15 15:25:10 +11001269
Damien Miller95def091999-11-25 00:26:21 +11001270 pam_retval = pam_start("sshd", pw->pw_name, &conv, (pam_handle_t**)&pamh);
1271 if (pam_retval != PAM_SUCCESS)
1272 fatal("PAM initialisation failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
1273
1274 fatal_add_cleanup(&pam_cleanup_proc, NULL);
1275 }
Damien Miller06230761999-10-28 14:03:14 +10001276#endif
Damien Miller3d112ef1999-10-28 13:20:30 +10001277
Damien Miller5428f641999-11-25 11:54:57 +11001278 /*
1279 * If we are not running as root, the user must have the same uid as
1280 * the server.
1281 */
Damien Miller95def091999-11-25 00:26:21 +11001282 if (getuid() != 0 && pw->pw_uid != getuid())
1283 packet_disconnect("Cannot change user when server not running as root.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001284
Damien Miller95def091999-11-25 00:26:21 +11001285 debug("Attempting authentication for %.100s.", user);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001286
Damien Miller95def091999-11-25 00:26:21 +11001287 /* If the user has no password, accept authentication immediately. */
1288 if (options.password_authentication &&
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001289#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11001290 (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001291#endif /* KRB4 */
Damien Miller95def091999-11-25 00:26:21 +11001292 auth_password(pw, "")) {
1293 /* Authentication with empty password succeeded. */
1294 log("Login for user %s from %.100s, accepted without authentication.",
1295 pw->pw_name, get_remote_ipaddr());
1296 } else {
1297 /* Loop until the user has been authenticated or the
1298 connection is closed, do_authloop() returns only if
1299 authentication is successfull */
1300 do_authloop(pw);
1301 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001302
Damien Miller95def091999-11-25 00:26:21 +11001303 /* Check if the user is logging in as root and root logins are disallowed. */
1304 if (pw->pw_uid == 0 && !options.permit_root_login) {
1305 if (forced_command)
1306 log("Root login accepted for forced command.");
1307 else
1308 packet_disconnect("ROOT LOGIN REFUSED FROM %.200s",
1309 get_canonical_hostname());
1310 }
1311 /* The user has been authenticated and accepted. */
1312 packet_start(SSH_SMSG_SUCCESS);
1313 packet_send();
1314 packet_write_wait();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001315
Damien Miller95def091999-11-25 00:26:21 +11001316 /* Perform session preparation. */
1317 do_authenticated(pw);
Damien Miller2ccf6611999-11-15 15:25:10 +11001318}
1319
Damien Miller95def091999-11-25 00:26:21 +11001320#define AUTH_FAIL_MAX 6
1321#define AUTH_FAIL_LOG (AUTH_FAIL_MAX/2)
1322#define AUTH_FAIL_MSG "Too many authentication failures for %.100s"
Damien Miller2ccf6611999-11-15 15:25:10 +11001323
Damien Miller95def091999-11-25 00:26:21 +11001324/*
1325 * read packets and try to authenticate local user *pw.
1326 * return if authentication is successfull
1327 */
Damien Miller2ccf6611999-11-15 15:25:10 +11001328void
Damien Miller95def091999-11-25 00:26:21 +11001329do_authloop(struct passwd * pw)
Damien Miller2ccf6611999-11-15 15:25:10 +11001330{
Damien Miller95def091999-11-25 00:26:21 +11001331 int attempt = 0;
1332 unsigned int bits;
1333 BIGNUM *client_host_key_e, *client_host_key_n;
1334 BIGNUM *n;
1335 char *client_user = NULL, *password = NULL;
1336 char user[1024];
1337 int plen, dlen, nlen, ulen, elen;
1338 int type = 0;
1339 void (*authlog) (const char *fmt,...) = verbose;
Damien Miller3bd49ec1999-11-15 15:40:55 +11001340#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001341 int pam_retval;
Damien Miller3bd49ec1999-11-15 15:40:55 +11001342#endif /* HAVE_LIBPAM */
Damien Miller2ccf6611999-11-15 15:25:10 +11001343
Damien Miller95def091999-11-25 00:26:21 +11001344 /* Indicate that authentication is needed. */
1345 packet_start(SSH_SMSG_FAILURE);
1346 packet_send();
1347 packet_write_wait();
Damien Miller2ccf6611999-11-15 15:25:10 +11001348
Damien Miller95def091999-11-25 00:26:21 +11001349 for (attempt = 1;; attempt++) {
1350 int authenticated = 0;
1351 strlcpy(user, "", sizeof user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001352
Damien Miller95def091999-11-25 00:26:21 +11001353 /* Get a packet from the client. */
1354 type = packet_read(&plen);
1355
1356 /* Process the packet. */
1357 switch (type) {
Damien Miller2ccf6611999-11-15 15:25:10 +11001358#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11001359 case SSH_CMSG_HAVE_KERBEROS_TGT:
1360 if (!options.kerberos_tgt_passing) {
1361 /* packet_get_all(); */
1362 verbose("Kerberos tgt passing disabled.");
1363 break;
1364 } else {
1365 /* Accept Kerberos tgt. */
1366 char *tgt = packet_get_string(&dlen);
1367 packet_integrity_check(plen, 4 + dlen, type);
1368 if (!auth_kerberos_tgt(pw, tgt))
1369 verbose("Kerberos tgt REFUSED for %s", pw->pw_name);
1370 xfree(tgt);
1371 }
1372 continue;
1373
1374 case SSH_CMSG_HAVE_AFS_TOKEN:
1375 if (!options.afs_token_passing || !k_hasafs()) {
1376 /* packet_get_all(); */
1377 verbose("AFS token passing disabled.");
1378 break;
1379 } else {
1380 /* Accept AFS token. */
1381 char *token_string = packet_get_string(&dlen);
1382 packet_integrity_check(plen, 4 + dlen, type);
1383 if (!auth_afs_token(pw, token_string))
1384 verbose("AFS token REFUSED for %s", pw->pw_name);
1385 xfree(token_string);
1386 }
1387 continue;
Damien Miller2ccf6611999-11-15 15:25:10 +11001388#endif /* AFS */
Damien Miller2ccf6611999-11-15 15:25:10 +11001389#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11001390 case SSH_CMSG_AUTH_KERBEROS:
1391 if (!options.kerberos_authentication) {
1392 /* packet_get_all(); */
1393 verbose("Kerberos authentication disabled.");
1394 break;
1395 } else {
1396 /* Try Kerberos v4 authentication. */
1397 KTEXT_ST auth;
1398 char *tkt_user = NULL;
1399 char *kdata = packet_get_string((unsigned int *) &auth.length);
1400 packet_integrity_check(plen, 4 + auth.length, type);
Damien Miller2ccf6611999-11-15 15:25:10 +11001401
Damien Miller95def091999-11-25 00:26:21 +11001402 if (auth.length < MAX_KTXT_LEN)
1403 memcpy(auth.dat, kdata, auth.length);
1404 xfree(kdata);
1405
1406 authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
1407
1408 if (authenticated) {
1409 snprintf(user, sizeof user, " tktuser %s", tkt_user);
1410 xfree(tkt_user);
1411 }
1412 }
1413 break;
Damien Miller2ccf6611999-11-15 15:25:10 +11001414#endif /* KRB4 */
Damien Miller2ccf6611999-11-15 15:25:10 +11001415
Damien Miller95def091999-11-25 00:26:21 +11001416 case SSH_CMSG_AUTH_RHOSTS:
1417 if (!options.rhosts_authentication) {
1418 verbose("Rhosts authentication disabled.");
1419 break;
1420 }
Damien Miller5428f641999-11-25 11:54:57 +11001421 /*
1422 * Get client user name. Note that we just have to
1423 * trust the client; this is one reason why rhosts
1424 * authentication is insecure. (Another is
1425 * IP-spoofing on a local network.)
1426 */
Damien Miller95def091999-11-25 00:26:21 +11001427 client_user = packet_get_string(&ulen);
1428 packet_integrity_check(plen, 4 + ulen, type);
1429
1430 /* Try to authenticate using /etc/hosts.equiv and
1431 .rhosts. */
1432 authenticated = auth_rhosts(pw, client_user);
1433
1434 snprintf(user, sizeof user, " ruser %s", client_user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001435#ifndef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001436 xfree(client_user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001437#endif /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001438 break;
Damien Miller7e8e8201999-11-16 13:37:16 +11001439
Damien Miller95def091999-11-25 00:26:21 +11001440 case SSH_CMSG_AUTH_RHOSTS_RSA:
1441 if (!options.rhosts_rsa_authentication) {
1442 verbose("Rhosts with RSA authentication disabled.");
1443 break;
1444 }
Damien Miller5428f641999-11-25 11:54:57 +11001445 /*
1446 * Get client user name. Note that we just have to
1447 * trust the client; root on the client machine can
1448 * claim to be any user.
1449 */
Damien Miller95def091999-11-25 00:26:21 +11001450 client_user = packet_get_string(&ulen);
1451
1452 /* Get the client host key. */
1453 client_host_key_e = BN_new();
1454 client_host_key_n = BN_new();
1455 bits = packet_get_int();
1456 packet_get_bignum(client_host_key_e, &elen);
1457 packet_get_bignum(client_host_key_n, &nlen);
1458
1459 if (bits != BN_num_bits(client_host_key_n))
1460 error("Warning: keysize mismatch for client_host_key: "
1461 "actual %d, announced %d", BN_num_bits(client_host_key_n), bits);
1462 packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1463
1464 authenticated = auth_rhosts_rsa(pw, client_user,
1465 client_host_key_e, client_host_key_n);
1466 BN_clear_free(client_host_key_e);
1467 BN_clear_free(client_host_key_n);
1468
1469 snprintf(user, sizeof user, " ruser %s", client_user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001470#ifndef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001471 xfree(client_user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001472#endif /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001473 break;
Damien Miller81428f91999-11-18 09:28:11 +11001474
Damien Miller95def091999-11-25 00:26:21 +11001475 case SSH_CMSG_AUTH_RSA:
1476 if (!options.rsa_authentication) {
1477 verbose("RSA authentication disabled.");
1478 break;
1479 }
1480 /* RSA authentication requested. */
1481 n = BN_new();
1482 packet_get_bignum(n, &nlen);
1483 packet_integrity_check(plen, nlen, type);
1484 authenticated = auth_rsa(pw, n);
1485 BN_clear_free(n);
1486 break;
1487
1488 case SSH_CMSG_AUTH_PASSWORD:
1489 if (!options.password_authentication) {
1490 verbose("Password authentication disabled.");
1491 break;
1492 }
Damien Miller5428f641999-11-25 11:54:57 +11001493 /*
1494 * Read user password. It is in plain text, but was
1495 * transmitted over the encrypted channel so it is
1496 * not visible to an outside observer.
1497 */
Damien Miller95def091999-11-25 00:26:21 +11001498 password = packet_get_string(&dlen);
1499 packet_integrity_check(plen, 4 + dlen, type);
1500
Damien Miller06230761999-10-28 14:03:14 +10001501#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001502 /* Do PAM auth with password */
1503 pampasswd = password;
1504 pam_retval = pam_authenticate((pam_handle_t *)pamh, 0);
1505 if (pam_retval == PAM_SUCCESS) {
1506 log("PAM Password authentication accepted for user \"%.100s\"", pw->pw_name);
Damien Millerbf1c9b21999-12-09 10:16:54 +11001507 memset(password, 0, strlen(password));
1508 xfree(password);
Damien Miller95def091999-11-25 00:26:21 +11001509 authenticated = 1;
1510 break;
1511 }
Damien Miller3bd49ec1999-11-15 15:40:55 +11001512
Damien Miller95def091999-11-25 00:26:21 +11001513 log("PAM Password authentication for \"%.100s\" failed: %s",
1514 pw->pw_name, PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
Damien Millerbf1c9b21999-12-09 10:16:54 +11001515 memset(password, 0, strlen(password));
1516 xfree(password);
Damien Miller95def091999-11-25 00:26:21 +11001517 break;
Damien Miller2ccf6611999-11-15 15:25:10 +11001518#else /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001519 /* Try authentication with the password. */
1520 authenticated = auth_password(pw, password);
Damien Miller2ccf6611999-11-15 15:25:10 +11001521
Damien Miller95def091999-11-25 00:26:21 +11001522 memset(password, 0, strlen(password));
1523 xfree(password);
1524 break;
Damien Miller2ccf6611999-11-15 15:25:10 +11001525#endif /* HAVE_LIBPAM */
Damien Miller2ccf6611999-11-15 15:25:10 +11001526
Damien Miller95def091999-11-25 00:26:21 +11001527#ifdef SKEY
1528 case SSH_CMSG_AUTH_TIS:
1529 debug("rcvd SSH_CMSG_AUTH_TIS");
1530 if (options.skey_authentication == 1) {
1531 char *skeyinfo = skey_keyinfo(pw->pw_name);
1532 if (skeyinfo == NULL) {
1533 debug("generating fake skeyinfo for %.100s.", pw->pw_name);
1534 skeyinfo = skey_fake_keyinfo(pw->pw_name);
1535 }
1536 if (skeyinfo != NULL) {
Damien Miller5428f641999-11-25 11:54:57 +11001537 /* we send our s/key- in tis-challenge messages */
Damien Miller95def091999-11-25 00:26:21 +11001538 debug("sending challenge '%s'", skeyinfo);
1539 packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1540 packet_put_string(skeyinfo, strlen(skeyinfo));
1541 packet_send();
1542 packet_write_wait();
1543 continue;
1544 }
1545 }
1546 break;
1547 case SSH_CMSG_AUTH_TIS_RESPONSE:
1548 debug("rcvd SSH_CMSG_AUTH_TIS_RESPONSE");
1549 if (options.skey_authentication == 1) {
1550 char *response = packet_get_string(&dlen);
1551 debug("skey response == '%s'", response);
1552 packet_integrity_check(plen, 4 + dlen, type);
1553 authenticated = (skey_haskey(pw->pw_name) == 0 &&
1554 skey_passcheck(pw->pw_name, response) != -1);
1555 xfree(response);
1556 }
1557 break;
1558#else
1559 case SSH_CMSG_AUTH_TIS:
1560 /* TIS Authentication is unsupported */
1561 log("TIS authentication unsupported.");
1562 break;
1563#endif
1564
1565 default:
Damien Miller5428f641999-11-25 11:54:57 +11001566 /*
1567 * Any unknown messages will be ignored (and failure
1568 * returned) during authentication.
1569 */
Damien Miller95def091999-11-25 00:26:21 +11001570 log("Unknown message during authentication: type %d", type);
1571 break;
1572 }
1573
1574 /* Raise logging level */
1575 if (authenticated ||
1576 attempt == AUTH_FAIL_LOG ||
1577 type == SSH_CMSG_AUTH_PASSWORD)
1578 authlog = log;
1579
1580 authlog("%s %s for %.200s from %.200s port %d%s",
1581 authenticated ? "Accepted" : "Failed",
1582 get_authname(type),
1583 pw->pw_uid == 0 ? "ROOT" : pw->pw_name,
1584 get_remote_ipaddr(),
1585 get_remote_port(),
1586 user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001587
Damien Millereabf3411999-12-07 14:56:27 +11001588#ifndef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001589 if (authenticated)
1590 return;
1591
1592 if (attempt > AUTH_FAIL_MAX)
1593 packet_disconnect(AUTH_FAIL_MSG, pw->pw_name);
Damien Millereabf3411999-12-07 14:56:27 +11001594#else /* HAVE_LIBPAM */
1595 if (authenticated) {
Damien Millerbf1c9b21999-12-09 10:16:54 +11001596 do_pam_account(pw->pw_name, client_user);
Damien Millereabf3411999-12-07 14:56:27 +11001597
Damien Millereabf3411999-12-07 14:56:27 +11001598 if (client_user != NULL)
1599 xfree(client_user);
1600
Damien Millereabf3411999-12-07 14:56:27 +11001601 return;
1602 }
1603
1604 if (attempt > AUTH_FAIL_MAX) {
Damien Millereabf3411999-12-07 14:56:27 +11001605 if (client_user != NULL)
1606 xfree(client_user);
1607
Damien Millereabf3411999-12-07 14:56:27 +11001608 packet_disconnect(AUTH_FAIL_MSG, pw->pw_name);
1609 }
1610#endif /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001611
1612 /* Send a message indicating that the authentication attempt failed. */
1613 packet_start(SSH_SMSG_FAILURE);
1614 packet_send();
1615 packet_write_wait();
1616 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001617}
1618
Damien Miller95def091999-11-25 00:26:21 +11001619/*
1620 * The user does not exist or access is denied,
1621 * but fake indication that authentication is needed.
1622 */
Damien Miller2ccf6611999-11-15 15:25:10 +11001623void
1624do_fake_authloop(char *user)
Damien Miller3d112ef1999-10-28 13:20:30 +10001625{
Damien Miller95def091999-11-25 00:26:21 +11001626 int attempt = 0;
Damien Miller2ccf6611999-11-15 15:25:10 +11001627
Damien Miller95def091999-11-25 00:26:21 +11001628 log("Faking authloop for illegal user %.200s from %.200s port %d",
1629 user,
1630 get_remote_ipaddr(),
1631 get_remote_port());
Damien Miller3d112ef1999-10-28 13:20:30 +10001632
Damien Miller95def091999-11-25 00:26:21 +11001633 /* Indicate that authentication is needed. */
1634 packet_start(SSH_SMSG_FAILURE);
1635 packet_send();
1636 packet_write_wait();
1637
Damien Miller5428f641999-11-25 11:54:57 +11001638 /*
1639 * Keep reading packets, and always respond with a failure. This is
1640 * to avoid disclosing whether such a user really exists.
1641 */
Damien Miller95def091999-11-25 00:26:21 +11001642 for (attempt = 1;; attempt++) {
Damien Miller5428f641999-11-25 11:54:57 +11001643 /* Read a packet. This will not return if the client disconnects. */
Damien Miller95def091999-11-25 00:26:21 +11001644 int plen;
1645 int type = packet_read(&plen);
Damien Miller2ccf6611999-11-15 15:25:10 +11001646#ifdef SKEY
Damien Miller95def091999-11-25 00:26:21 +11001647 int dlen;
1648 char *password, *skeyinfo;
1649 if (options.password_authentication &&
1650 options.skey_authentication == 1 &&
1651 type == SSH_CMSG_AUTH_PASSWORD &&
1652 (password = packet_get_string(&dlen)) != NULL &&
1653 dlen == 5 &&
1654 strncasecmp(password, "s/key", 5) == 0 &&
1655 (skeyinfo = skey_fake_keyinfo(user)) != NULL) {
1656 /* Send a fake s/key challenge. */
1657 packet_send_debug(skeyinfo);
1658 }
Damien Miller2ccf6611999-11-15 15:25:10 +11001659#endif
Damien Miller95def091999-11-25 00:26:21 +11001660 if (attempt > AUTH_FAIL_MAX)
1661 packet_disconnect(AUTH_FAIL_MSG, user);
1662
Damien Miller5428f641999-11-25 11:54:57 +11001663 /*
1664 * Send failure. This should be indistinguishable from a
1665 * failed authentication.
1666 */
Damien Miller95def091999-11-25 00:26:21 +11001667 packet_start(SSH_SMSG_FAILURE);
1668 packet_send();
1669 packet_write_wait();
1670 }
1671 /* NOTREACHED */
1672 abort();
Damien Miller3d112ef1999-10-28 13:20:30 +10001673}
1674
Damien Miller2ccf6611999-11-15 15:25:10 +11001675
Damien Miller95def091999-11-25 00:26:21 +11001676/*
1677 * Remove local Xauthority file.
1678 */
Damien Miller5ce662a1999-11-11 17:57:39 +11001679static void
1680xauthfile_cleanup_proc(void *ignore)
1681{
Damien Miller95def091999-11-25 00:26:21 +11001682 debug("xauthfile_cleanup_proc called");
Damien Miller5ce662a1999-11-11 17:57:39 +11001683
Damien Miller95def091999-11-25 00:26:21 +11001684 if (xauthfile != NULL) {
1685 unlink(xauthfile);
1686 xfree(xauthfile);
1687 xauthfile = NULL;
1688 }
Damien Miller5ce662a1999-11-11 17:57:39 +11001689}
1690
Damien Miller95def091999-11-25 00:26:21 +11001691/*
1692 * Prepares for an interactive session. This is called after the user has
1693 * been successfully authenticated. During this message exchange, pseudo
1694 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1695 * are requested, etc.
1696 */
1697void
1698do_authenticated(struct passwd * pw)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001699{
Damien Miller95def091999-11-25 00:26:21 +11001700 int type;
1701 int compression_level = 0, enable_compression_after_reply = 0;
1702 int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1;
1703 int row, col, xpixel, ypixel, screen;
1704 char ttyname[64];
1705 char *command, *term = NULL, *display = NULL, *proto = NULL,
1706 *data = NULL;
1707 struct group *grp;
1708 gid_t tty_gid;
1709 mode_t tty_mode;
1710 int n_bytes;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001711
Damien Miller5428f641999-11-25 11:54:57 +11001712 /*
1713 * Cancel the alarm we set to limit the time taken for
1714 * authentication.
1715 */
Damien Miller95def091999-11-25 00:26:21 +11001716 alarm(0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001717
Damien Miller5428f641999-11-25 11:54:57 +11001718 /*
1719 * Inform the channel mechanism that we are the server side and that
1720 * the client may request to connect to any port at all. (The user
1721 * could do it anyway, and we wouldn\'t know what is permitted except
1722 * by the client telling us, so we can equally well trust the client
1723 * not to request anything bogus.)
1724 */
Damien Miller95def091999-11-25 00:26:21 +11001725 channel_permit_all_opens();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001726
Damien Miller5428f641999-11-25 11:54:57 +11001727 /*
1728 * We stay in this loop until the client requests to execute a shell
1729 * or a command.
1730 */
Damien Miller95def091999-11-25 00:26:21 +11001731 while (1) {
1732 int plen, dlen;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001733
Damien Miller95def091999-11-25 00:26:21 +11001734 /* Get a packet from the client. */
1735 type = packet_read(&plen);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001736
Damien Miller95def091999-11-25 00:26:21 +11001737 /* Process the packet. */
1738 switch (type) {
1739 case SSH_CMSG_REQUEST_COMPRESSION:
1740 packet_integrity_check(plen, 4, type);
1741 compression_level = packet_get_int();
1742 if (compression_level < 1 || compression_level > 9) {
1743 packet_send_debug("Received illegal compression level %d.",
1744 compression_level);
1745 goto fail;
1746 }
1747 /* Enable compression after we have responded with SUCCESS. */
1748 enable_compression_after_reply = 1;
1749 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001750
Damien Miller95def091999-11-25 00:26:21 +11001751 case SSH_CMSG_REQUEST_PTY:
1752 if (no_pty_flag) {
1753 debug("Allocating a pty not permitted for this authentication.");
1754 goto fail;
1755 }
1756 if (have_pty)
1757 packet_disconnect("Protocol error: you already have a pty.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001758
Damien Miller95def091999-11-25 00:26:21 +11001759 debug("Allocating pty.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001760
Damien Miller95def091999-11-25 00:26:21 +11001761 /* Allocate a pty and open it. */
Damien Miller037a0dc1999-12-07 15:38:31 +11001762 if (!pty_allocate(&ptyfd, &ttyfd, ttyname,
1763 sizeof(ttyname))) {
Damien Miller95def091999-11-25 00:26:21 +11001764 error("Failed to allocate pty.");
1765 goto fail;
1766 }
1767 /* Determine the group to make the owner of the tty. */
1768 grp = getgrnam("tty");
1769 if (grp) {
1770 tty_gid = grp->gr_gid;
1771 tty_mode = S_IRUSR | S_IWUSR | S_IWGRP;
1772 } else {
1773 tty_gid = pw->pw_gid;
1774 tty_mode = S_IRUSR | S_IWUSR | S_IWGRP | S_IWOTH;
1775 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001776
Damien Miller95def091999-11-25 00:26:21 +11001777 /* Change ownership of the tty. */
1778 if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
1779 fatal("chown(%.100s, %d, %d) failed: %.100s",
1780 ttyname, pw->pw_uid, tty_gid, strerror(errno));
1781 if (chmod(ttyname, tty_mode) < 0)
1782 fatal("chmod(%.100s, 0%o) failed: %.100s",
1783 ttyname, tty_mode, strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001784
Damien Miller95def091999-11-25 00:26:21 +11001785 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
1786 term = packet_get_string(&dlen);
1787 packet_integrity_check(dlen, strlen(term), type);
1788 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
1789 /* Remaining bytes */
1790 n_bytes = plen - (4 + dlen + 4 * 4);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001791
Damien Miller95def091999-11-25 00:26:21 +11001792 if (strcmp(term, "") == 0)
1793 term = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001794
Damien Miller95def091999-11-25 00:26:21 +11001795 /* Get window size from the packet. */
1796 row = packet_get_int();
1797 col = packet_get_int();
1798 xpixel = packet_get_int();
1799 ypixel = packet_get_int();
1800 pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001801
Damien Miller95def091999-11-25 00:26:21 +11001802 /* Get tty modes from the packet. */
1803 tty_parse_modes(ttyfd, &n_bytes);
1804 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001805
Damien Miller95def091999-11-25 00:26:21 +11001806 /* Indicate that we now have a pty. */
1807 have_pty = 1;
Damien Millerbf1c9b21999-12-09 10:16:54 +11001808
1809#ifdef HAVE_LIBPAM
1810 /* do the pam_open_session since we have the pty */
1811 do_pam_session(pw->pw_name,ttyname);
1812#endif /* HAVE_LIBPAM */
1813
Damien Miller95def091999-11-25 00:26:21 +11001814 break;
1815
1816 case SSH_CMSG_X11_REQUEST_FORWARDING:
1817 if (!options.x11_forwarding) {
1818 packet_send_debug("X11 forwarding disabled in server configuration file.");
1819 goto fail;
1820 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001821#ifdef XAUTH_PATH
Damien Miller95def091999-11-25 00:26:21 +11001822 if (no_x11_forwarding_flag) {
1823 packet_send_debug("X11 forwarding not permitted for this authentication.");
1824 goto fail;
1825 }
1826 debug("Received request for X11 forwarding with auth spoofing.");
1827 if (display)
1828 packet_disconnect("Protocol error: X11 display already set.");
1829 {
1830 int proto_len, data_len;
1831 proto = packet_get_string(&proto_len);
1832 data = packet_get_string(&data_len);
1833 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
1834 }
1835 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1836 screen = packet_get_int();
1837 else
1838 screen = 0;
1839 display = x11_create_display_inet(screen);
1840 if (!display)
1841 goto fail;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001842
Damien Miller95def091999-11-25 00:26:21 +11001843 /* Setup to always have a local .Xauthority. */
1844 xauthfile = xmalloc(MAXPATHLEN);
1845 snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX");
1846
1847 if ((xauthfd = mkstemp(xauthfile)) != -1) {
1848 fchown(xauthfd, pw->pw_uid, pw->pw_gid);
1849 close(xauthfd);
1850 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
1851 } else {
1852 xfree(xauthfile);
1853 xauthfile = NULL;
1854 }
1855 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001856#else /* XAUTH_PATH */
Damien Miller95def091999-11-25 00:26:21 +11001857 packet_send_debug("No xauth program; cannot forward with spoofing.");
1858 goto fail;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001859#endif /* XAUTH_PATH */
1860
Damien Miller95def091999-11-25 00:26:21 +11001861 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1862 if (no_agent_forwarding_flag) {
1863 debug("Authentication agent forwarding not permitted for this authentication.");
1864 goto fail;
1865 }
1866 debug("Received authentication agent forwarding request.");
1867 auth_input_request_forwarding(pw);
1868 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001869
Damien Miller95def091999-11-25 00:26:21 +11001870 case SSH_CMSG_PORT_FORWARD_REQUEST:
1871 if (no_port_forwarding_flag) {
1872 debug("Port forwarding not permitted for this authentication.");
1873 goto fail;
1874 }
1875 debug("Received TCP/IP port forwarding request.");
1876 channel_input_port_forward_request(pw->pw_uid == 0);
1877 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001878
Damien Miller95def091999-11-25 00:26:21 +11001879 case SSH_CMSG_MAX_PACKET_SIZE:
1880 if (packet_set_maxsize(packet_get_int()) < 0)
1881 goto fail;
1882 break;
Damien Miller6162d121999-11-21 13:23:52 +11001883
Damien Miller95def091999-11-25 00:26:21 +11001884 case SSH_CMSG_EXEC_SHELL:
1885 /* Set interactive/non-interactive mode. */
1886 packet_set_interactive(have_pty || display != NULL,
1887 options.keepalives);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001888
Damien Miller95def091999-11-25 00:26:21 +11001889 if (forced_command != NULL)
1890 goto do_forced_command;
1891 debug("Forking shell.");
1892 packet_integrity_check(plen, 0, type);
1893 if (have_pty)
1894 do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1895 else
1896 do_exec_no_pty(NULL, pw, display, proto, data);
1897 return;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001898
Damien Miller95def091999-11-25 00:26:21 +11001899 case SSH_CMSG_EXEC_CMD:
1900 /* Set interactive/non-interactive mode. */
1901 packet_set_interactive(have_pty || display != NULL,
1902 options.keepalives);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001903
Damien Miller95def091999-11-25 00:26:21 +11001904 if (forced_command != NULL)
1905 goto do_forced_command;
1906 /* Get command from the packet. */
1907 {
1908 int dlen;
1909 command = packet_get_string(&dlen);
1910 debug("Executing command '%.500s'", command);
1911 packet_integrity_check(plen, 4 + dlen, type);
1912 }
1913 if (have_pty)
1914 do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1915 else
1916 do_exec_no_pty(command, pw, display, proto, data);
1917 xfree(command);
1918 return;
1919
1920 default:
Damien Miller5428f641999-11-25 11:54:57 +11001921 /*
1922 * Any unknown messages in this phase are ignored,
1923 * and a failure message is returned.
1924 */
Damien Miller95def091999-11-25 00:26:21 +11001925 log("Unknown packet type received after authentication: %d", type);
1926 goto fail;
1927 }
1928
1929 /* The request was successfully processed. */
1930 packet_start(SSH_SMSG_SUCCESS);
1931 packet_send();
1932 packet_write_wait();
1933
1934 /* Enable compression now that we have replied if appropriate. */
1935 if (enable_compression_after_reply) {
1936 enable_compression_after_reply = 0;
1937 packet_start_compression(compression_level);
1938 }
1939 continue;
1940
1941fail:
1942 /* The request failed. */
1943 packet_start(SSH_SMSG_FAILURE);
1944 packet_send();
1945 packet_write_wait();
1946 continue;
1947
1948do_forced_command:
Damien Miller5428f641999-11-25 11:54:57 +11001949 /*
1950 * There is a forced command specified for this login.
1951 * Execute it.
1952 */
Damien Miller95def091999-11-25 00:26:21 +11001953 debug("Executing forced command: %.900s", forced_command);
1954 if (have_pty)
1955 do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1956 else
1957 do_exec_no_pty(forced_command, pw, display, proto, data);
1958 return;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001959 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001960}
1961
Damien Miller95def091999-11-25 00:26:21 +11001962/*
1963 * This is called to fork and execute a command when we have no tty. This
1964 * will call do_child from the child, and server_loop from the parent after
1965 * setting up file descriptors and such.
1966 */
1967void
1968do_exec_no_pty(const char *command, struct passwd * pw,
1969 const char *display, const char *auth_proto,
1970 const char *auth_data)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001971{
Damien Miller95def091999-11-25 00:26:21 +11001972 int pid;
1973
1974#ifdef USE_PIPES
1975 int pin[2], pout[2], perr[2];
1976 /* Allocate pipes for communicating with the program. */
1977 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1978 packet_disconnect("Could not create pipes: %.100s",
1979 strerror(errno));
1980#else /* USE_PIPES */
1981 int inout[2], err[2];
1982 /* Uses socket pairs to communicate with the program. */
1983 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
1984 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
1985 packet_disconnect("Could not create socket pairs: %.100s",
1986 strerror(errno));
1987#endif /* USE_PIPES */
1988
1989 setproctitle("%s@notty", pw->pw_name);
1990
1991 /* Fork the child. */
1992 if ((pid = fork()) == 0) {
1993 /* Child. Reinitialize the log since the pid has changed. */
1994 log_init(av0, options.log_level, options.log_facility, log_stderr);
1995
Damien Miller5428f641999-11-25 11:54:57 +11001996 /*
1997 * Create a new session and process group since the 4.4BSD
1998 * setlogin() affects the entire process group.
1999 */
Damien Miller95def091999-11-25 00:26:21 +11002000 if (setsid() < 0)
2001 error("setsid failed: %.100s", strerror(errno));
2002
2003#ifdef USE_PIPES
Damien Miller5428f641999-11-25 11:54:57 +11002004 /*
2005 * Redirect stdin. We close the parent side of the socket
2006 * pair, and make the child side the standard input.
2007 */
Damien Miller95def091999-11-25 00:26:21 +11002008 close(pin[1]);
2009 if (dup2(pin[0], 0) < 0)
2010 perror("dup2 stdin");
2011 close(pin[0]);
2012
2013 /* Redirect stdout. */
2014 close(pout[0]);
2015 if (dup2(pout[1], 1) < 0)
2016 perror("dup2 stdout");
2017 close(pout[1]);
2018
2019 /* Redirect stderr. */
2020 close(perr[0]);
2021 if (dup2(perr[1], 2) < 0)
2022 perror("dup2 stderr");
2023 close(perr[1]);
2024#else /* USE_PIPES */
Damien Miller5428f641999-11-25 11:54:57 +11002025 /*
2026 * Redirect stdin, stdout, and stderr. Stdin and stdout will
2027 * use the same socket, as some programs (particularly rdist)
2028 * seem to depend on it.
2029 */
Damien Miller95def091999-11-25 00:26:21 +11002030 close(inout[1]);
2031 close(err[1]);
2032 if (dup2(inout[0], 0) < 0) /* stdin */
2033 perror("dup2 stdin");
2034 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
2035 perror("dup2 stdout");
2036 if (dup2(err[0], 2) < 0) /* stderr */
2037 perror("dup2 stderr");
2038#endif /* USE_PIPES */
2039
2040 /* Do processing for the child (exec command etc). */
2041 do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
2042 /* NOTREACHED */
2043 }
2044 if (pid < 0)
2045 packet_disconnect("fork failed: %.100s", strerror(errno));
2046#ifdef USE_PIPES
2047 /* We are the parent. Close the child sides of the pipes. */
2048 close(pin[0]);
2049 close(pout[1]);
2050 close(perr[1]);
2051
2052 /* Enter the interactive session. */
2053 server_loop(pid, pin[1], pout[0], perr[0]);
2054 /* server_loop has closed pin[1], pout[1], and perr[1]. */
2055#else /* USE_PIPES */
2056 /* We are the parent. Close the child sides of the socket pairs. */
2057 close(inout[0]);
2058 close(err[0]);
2059
Damien Miller5428f641999-11-25 11:54:57 +11002060 /*
2061 * Enter the interactive session. Note: server_loop must be able to
2062 * handle the case that fdin and fdout are the same.
2063 */
Damien Miller95def091999-11-25 00:26:21 +11002064 server_loop(pid, inout[1], inout[1], err[1]);
2065 /* server_loop has closed inout[1] and err[1]. */
2066#endif /* USE_PIPES */
2067}
2068
2069struct pty_cleanup_context {
2070 const char *ttyname;
2071 int pid;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002072};
2073
Damien Miller95def091999-11-25 00:26:21 +11002074/*
2075 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
2076 * dropped connection).
2077 */
2078void
2079pty_cleanup_proc(void *context)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002080{
Damien Miller95def091999-11-25 00:26:21 +11002081 struct pty_cleanup_context *cu = context;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002082
Damien Miller95def091999-11-25 00:26:21 +11002083 debug("pty_cleanup_proc called");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002084
Damien Miller95def091999-11-25 00:26:21 +11002085 /* Record that the user has logged out. */
2086 record_logout(cu->pid, cu->ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002087
Damien Miller95def091999-11-25 00:26:21 +11002088 /* Release the pseudo-tty. */
2089 pty_release(cu->ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002090}
2091
Damien Miller95def091999-11-25 00:26:21 +11002092/*
2093 * This is called to fork and execute a command when we have a tty. This
2094 * will call do_child from the child, and server_loop from the parent after
2095 * setting up file descriptors, controlling tty, updating wtmp, utmp,
2096 * lastlog, and other such operations.
2097 */
2098void
2099do_exec_pty(const char *command, int ptyfd, int ttyfd,
2100 const char *ttyname, struct passwd * pw, const char *term,
2101 const char *display, const char *auth_proto,
2102 const char *auth_data)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002103{
Damien Miller95def091999-11-25 00:26:21 +11002104 int pid, fdout;
2105 const char *hostname;
2106 time_t last_login_time;
2107 char buf[100], *time_string;
2108 FILE *f;
2109 char line[256];
2110 struct stat st;
2111 int quiet_login;
2112 struct sockaddr_in from;
2113 int fromlen;
2114 struct pty_cleanup_context cleanup_context;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002115
Damien Miller95def091999-11-25 00:26:21 +11002116 /* Get remote host name. */
2117 hostname = get_canonical_hostname();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002118
Damien Miller5428f641999-11-25 11:54:57 +11002119 /*
2120 * Get the time when the user last logged in. Buf will be set to
2121 * contain the hostname the last login was from.
2122 */
Damien Miller95def091999-11-25 00:26:21 +11002123 if (!options.use_login) {
2124 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
2125 buf, sizeof(buf));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002126 }
Damien Miller95def091999-11-25 00:26:21 +11002127 setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002128
Damien Miller95def091999-11-25 00:26:21 +11002129 /* Fork the child. */
2130 if ((pid = fork()) == 0) {
2131 pid = getpid();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002132
Damien Miller95def091999-11-25 00:26:21 +11002133 /* Child. Reinitialize the log because the pid has
2134 changed. */
2135 log_init(av0, options.log_level, options.log_facility, log_stderr);
2136
2137 /* Close the master side of the pseudo tty. */
2138 close(ptyfd);
2139
2140 /* Make the pseudo tty our controlling tty. */
2141 pty_make_controlling_tty(&ttyfd, ttyname);
2142
2143 /* Redirect stdin from the pseudo tty. */
2144 if (dup2(ttyfd, fileno(stdin)) < 0)
2145 error("dup2 stdin failed: %.100s", strerror(errno));
2146
2147 /* Redirect stdout to the pseudo tty. */
2148 if (dup2(ttyfd, fileno(stdout)) < 0)
2149 error("dup2 stdin failed: %.100s", strerror(errno));
2150
2151 /* Redirect stderr to the pseudo tty. */
2152 if (dup2(ttyfd, fileno(stderr)) < 0)
2153 error("dup2 stdin failed: %.100s", strerror(errno));
2154
2155 /* Close the extra descriptor for the pseudo tty. */
2156 close(ttyfd);
2157
Damien Miller5428f641999-11-25 11:54:57 +11002158 /*
2159 * Get IP address of client. This is needed because we want
2160 * to record where the user logged in from. If the
2161 * connection is not a socket, let the ip address be 0.0.0.0.
2162 */
Damien Miller95def091999-11-25 00:26:21 +11002163 memset(&from, 0, sizeof(from));
2164 if (packet_get_connection_in() == packet_get_connection_out()) {
2165 fromlen = sizeof(from);
2166 if (getpeername(packet_get_connection_in(),
2167 (struct sockaddr *) & from, &fromlen) < 0) {
2168 debug("getpeername: %.100s", strerror(errno));
2169 fatal_cleanup();
2170 }
2171 }
2172 /* Record that there was a login on that terminal. */
2173 record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
2174 &from);
2175
2176 /* Check if .hushlogin exists. */
2177 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2178 quiet_login = stat(line, &st) >= 0;
Damien Miller356a0b01999-11-08 15:30:59 +11002179
2180#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11002181 /* output the results of the pamconv() */
2182 if (!quiet_login && pamconv_msg != NULL)
2183 fprintf(stderr, pamconv_msg);
Damien Miller356a0b01999-11-08 15:30:59 +11002184#endif
Damien Miller95def091999-11-25 00:26:21 +11002185
Damien Miller5428f641999-11-25 11:54:57 +11002186 /*
2187 * If the user has logged in before, display the time of last
2188 * login. However, don't display anything extra if a command
2189 * has been specified (so that ssh can be used to execute
2190 * commands on a remote machine without users knowing they
2191 * are going to another machine). Login(1) will do this for
2192 * us as well, so check if login(1) is used
2193 */
Damien Miller95def091999-11-25 00:26:21 +11002194 if (command == NULL && last_login_time != 0 && !quiet_login &&
2195 !options.use_login) {
2196 /* Convert the date to a string. */
2197 time_string = ctime(&last_login_time);
2198 /* Remove the trailing newline. */
2199 if (strchr(time_string, '\n'))
2200 *strchr(time_string, '\n') = 0;
2201 /* Display the last login time. Host if displayed
2202 if known. */
2203 if (strcmp(buf, "") == 0)
2204 printf("Last login: %s\r\n", time_string);
2205 else
2206 printf("Last login: %s from %s\r\n", time_string, buf);
2207 }
Damien Miller5428f641999-11-25 11:54:57 +11002208 /*
2209 * Print /etc/motd unless a command was specified or printing
2210 * it was disabled in server options or login(1) will be
2211 * used. Note that some machines appear to print it in
2212 * /etc/profile or similar.
2213 */
Damien Miller95def091999-11-25 00:26:21 +11002214 if (command == NULL && options.print_motd && !quiet_login &&
2215 !options.use_login) {
2216 /* Print /etc/motd if it exists. */
2217 f = fopen("/etc/motd", "r");
2218 if (f) {
2219 while (fgets(line, sizeof(line), f))
2220 fputs(line, stdout);
2221 fclose(f);
2222 }
2223 }
2224 /* Do common processing for the child, such as execing the command. */
2225 do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
2226 /* NOTREACHED */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002227 }
Damien Miller95def091999-11-25 00:26:21 +11002228 if (pid < 0)
2229 packet_disconnect("fork failed: %.100s", strerror(errno));
2230 /* Parent. Close the slave side of the pseudo tty. */
2231 close(ttyfd);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002232
Damien Miller5428f641999-11-25 11:54:57 +11002233 /*
2234 * Create another descriptor of the pty master side for use as the
2235 * standard input. We could use the original descriptor, but this
2236 * simplifies code in server_loop. The descriptor is bidirectional.
2237 */
Damien Miller95def091999-11-25 00:26:21 +11002238 fdout = dup(ptyfd);
2239 if (fdout < 0)
2240 packet_disconnect("dup failed: %.100s", strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002241
Damien Miller5428f641999-11-25 11:54:57 +11002242 /*
2243 * Add a cleanup function to clear the utmp entry and record logout
2244 * time in case we call fatal() (e.g., the connection gets closed).
2245 */
Damien Miller95def091999-11-25 00:26:21 +11002246 cleanup_context.pid = pid;
2247 cleanup_context.ttyname = ttyname;
2248 fatal_add_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002249
Damien Miller95def091999-11-25 00:26:21 +11002250 /* Enter interactive session. */
2251 server_loop(pid, ptyfd, fdout, -1);
2252 /* server_loop has not closed ptyfd and fdout. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002253
Damien Miller95def091999-11-25 00:26:21 +11002254 /* Cancel the cleanup function. */
2255 fatal_remove_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002256
Damien Miller95def091999-11-25 00:26:21 +11002257 /* Record that the user has logged out. */
2258 record_logout(pid, ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002259
Damien Miller95def091999-11-25 00:26:21 +11002260 /* Release the pseudo-tty. */
2261 pty_release(ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002262
Damien Miller5428f641999-11-25 11:54:57 +11002263 /*
2264 * Close the server side of the socket pairs. We must do this after
2265 * the pty cleanup, so that another process doesn't get this pty
2266 * while we're still cleaning up.
2267 */
Damien Miller95def091999-11-25 00:26:21 +11002268 close(ptyfd);
2269 close(fdout);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002270}
2271
Damien Miller95def091999-11-25 00:26:21 +11002272/*
2273 * Sets the value of the given variable in the environment. If the variable
2274 * already exists, its value is overriden.
2275 */
2276void
2277child_set_env(char ***envp, unsigned int *envsizep, const char *name,
2278 const char *value)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002279{
Damien Miller95def091999-11-25 00:26:21 +11002280 unsigned int i, namelen;
2281 char **env;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002282
Damien Miller5428f641999-11-25 11:54:57 +11002283 /*
2284 * Find the slot where the value should be stored. If the variable
2285 * already exists, we reuse the slot; otherwise we append a new slot
2286 * at the end of the array, expanding if necessary.
2287 */
Damien Miller95def091999-11-25 00:26:21 +11002288 env = *envp;
2289 namelen = strlen(name);
2290 for (i = 0; env[i]; i++)
2291 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2292 break;
2293 if (env[i]) {
Damien Miller5428f641999-11-25 11:54:57 +11002294 /* Reuse the slot. */
Damien Miller95def091999-11-25 00:26:21 +11002295 xfree(env[i]);
2296 } else {
Damien Miller5428f641999-11-25 11:54:57 +11002297 /* New variable. Expand if necessary. */
Damien Miller95def091999-11-25 00:26:21 +11002298 if (i >= (*envsizep) - 1) {
2299 (*envsizep) += 50;
2300 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2301 }
2302 /* Need to set the NULL pointer at end of array beyond the new slot. */
2303 env[i + 1] = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002304 }
2305
Damien Miller95def091999-11-25 00:26:21 +11002306 /* Allocate space and format the variable in the appropriate slot. */
2307 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2308 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002309}
2310
Damien Miller95def091999-11-25 00:26:21 +11002311/*
2312 * Reads environment variables from the given file and adds/overrides them
2313 * into the environment. If the file does not exist, this does nothing.
2314 * Otherwise, it must consist of empty lines, comments (line starts with '#')
2315 * and assignments of the form name=value. No other forms are allowed.
2316 */
2317void
2318read_environment_file(char ***env, unsigned int *envsize,
2319 const char *filename)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002320{
Damien Miller95def091999-11-25 00:26:21 +11002321 FILE *f;
2322 char buf[4096];
2323 char *cp, *value;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002324
Damien Miller95def091999-11-25 00:26:21 +11002325 f = fopen(filename, "r");
2326 if (!f)
2327 return;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002328
Damien Miller95def091999-11-25 00:26:21 +11002329 while (fgets(buf, sizeof(buf), f)) {
Damien Miller5428f641999-11-25 11:54:57 +11002330 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
2331 ;
Damien Miller95def091999-11-25 00:26:21 +11002332 if (!*cp || *cp == '#' || *cp == '\n')
2333 continue;
Damien Miller95def091999-11-25 00:26:21 +11002334 if (strchr(cp, '\n'))
2335 *strchr(cp, '\n') = '\0';
Damien Miller95def091999-11-25 00:26:21 +11002336 value = strchr(cp, '=');
2337 if (value == NULL) {
2338 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
2339 continue;
2340 }
Damien Miller5428f641999-11-25 11:54:57 +11002341 /* Replace the equals sign by nul, and advance value to the value string. */
Damien Miller95def091999-11-25 00:26:21 +11002342 *value = '\0';
2343 value++;
Damien Miller95def091999-11-25 00:26:21 +11002344 child_set_env(env, envsize, cp, value);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002345 }
Damien Miller95def091999-11-25 00:26:21 +11002346 fclose(f);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002347}
2348
Damien Miller95def091999-11-25 00:26:21 +11002349/*
2350 * Performs common processing for the child, such as setting up the
2351 * environment, closing extra file descriptors, setting the user and group
2352 * ids, and executing the command or shell.
2353 */
2354void
2355do_child(const char *command, struct passwd * pw, const char *term,
2356 const char *display, const char *auth_proto,
2357 const char *auth_data, const char *ttyname)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002358{
Damien Miller95def091999-11-25 00:26:21 +11002359 const char *shell, *cp = NULL;
2360 char buf[256];
2361 FILE *f;
2362 unsigned int envsize, i;
2363 char **env;
2364 extern char **environ;
2365 struct stat st;
2366 char *argv[10];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002367
Damien Miller356a0b01999-11-08 15:30:59 +11002368#ifndef HAVE_LIBPAM /* pam_nologin handles this */
Damien Miller95def091999-11-25 00:26:21 +11002369 /* Check /etc/nologin. */
2370 f = fopen("/etc/nologin", "r");
2371 if (f) {
2372 /* /etc/nologin exists. Print its contents and exit. */
2373 while (fgets(buf, sizeof(buf), f))
2374 fputs(buf, stderr);
2375 fclose(f);
2376 if (pw->pw_uid != 0)
2377 exit(254);
2378 }
Damien Miller776af5d1999-11-12 08:49:09 +11002379#endif /* HAVE_LIBPAM */
2380
2381#ifdef HAVE_SETLOGIN
Damien Miller95def091999-11-25 00:26:21 +11002382 /* Set login name in the kernel. */
2383 if (setlogin(pw->pw_name) < 0)
2384 error("setlogin failed: %s", strerror(errno));
Damien Miller776af5d1999-11-12 08:49:09 +11002385#endif /* HAVE_SETLOGIN */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002386
Damien Miller95def091999-11-25 00:26:21 +11002387 /* Set uid, gid, and groups. */
2388 /* Login(1) does this as well, and it needs uid 0 for the "-h"
2389 switch, so we let login(1) to this for us. */
2390 if (!options.use_login) {
2391 if (getuid() == 0 || geteuid() == 0) {
2392 if (setgid(pw->pw_gid) < 0) {
2393 perror("setgid");
2394 exit(1);
2395 }
2396 /* Initialize the group list. */
2397 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
2398 perror("initgroups");
2399 exit(1);
2400 }
2401 endgrent();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002402
Damien Miller95def091999-11-25 00:26:21 +11002403 /* Permanently switch to the desired uid. */
2404 permanently_set_uid(pw->pw_uid);
2405 }
2406 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
2407 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
2408 }
Damien Miller5428f641999-11-25 11:54:57 +11002409 /*
2410 * Get the shell from the password data. An empty shell field is
2411 * legal, and means /bin/sh.
2412 */
Damien Miller95def091999-11-25 00:26:21 +11002413 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002414
2415#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11002416 /* Try to get AFS tokens for the local cell. */
2417 if (k_hasafs()) {
2418 char cell[64];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002419
Damien Miller95def091999-11-25 00:26:21 +11002420 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
2421 krb_afslog(cell, 0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002422
Damien Miller95def091999-11-25 00:26:21 +11002423 krb_afslog(0, 0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002424 }
Damien Miller95def091999-11-25 00:26:21 +11002425#endif /* AFS */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002426
Damien Miller5428f641999-11-25 11:54:57 +11002427 /* Initialize the environment. */
Damien Miller95def091999-11-25 00:26:21 +11002428 envsize = 100;
2429 env = xmalloc(envsize * sizeof(char *));
2430 env[0] = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002431
Damien Miller95def091999-11-25 00:26:21 +11002432 if (!options.use_login) {
2433 /* Set basic environment. */
2434 child_set_env(&env, &envsize, "USER", pw->pw_name);
2435 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
2436 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2437 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002438
Damien Miller95def091999-11-25 00:26:21 +11002439 snprintf(buf, sizeof buf, "%.200s/%.50s",
2440 _PATH_MAILDIR, pw->pw_name);
2441 child_set_env(&env, &envsize, "MAIL", buf);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002442
Damien Miller95def091999-11-25 00:26:21 +11002443 /* Normal systems set SHELL by default. */
2444 child_set_env(&env, &envsize, "SHELL", shell);
2445 }
Damien Miller95def091999-11-25 00:26:21 +11002446 if (getenv("TZ"))
2447 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
2448
2449 /* Set custom environment options from RSA authentication. */
2450 while (custom_environment) {
2451 struct envstring *ce = custom_environment;
2452 char *s = ce->s;
2453 int i;
2454 for (i = 0; s[i] != '=' && s[i]; i++);
2455 if (s[i] == '=') {
2456 s[i] = 0;
2457 child_set_env(&env, &envsize, s, s + i + 1);
2458 }
2459 custom_environment = ce->next;
2460 xfree(ce->s);
2461 xfree(ce);
2462 }
2463
Damien Miller95def091999-11-25 00:26:21 +11002464 snprintf(buf, sizeof buf, "%.50s %d %d",
2465 get_remote_ipaddr(), get_remote_port(), options.port);
2466 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2467
Damien Miller95def091999-11-25 00:26:21 +11002468 if (ttyname)
2469 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
Damien Miller95def091999-11-25 00:26:21 +11002470 if (term)
2471 child_set_env(&env, &envsize, "TERM", term);
Damien Miller95def091999-11-25 00:26:21 +11002472 if (display)
2473 child_set_env(&env, &envsize, "DISPLAY", display);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002474
2475#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11002476 {
2477 extern char *ticket;
2478
2479 if (ticket)
2480 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2481 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002482#endif /* KRB4 */
2483
Damien Miller94388161999-10-29 09:57:31 +10002484#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11002485 /* Pull in any environment variables that may have been set by PAM. */
2486 {
2487 char *equals, var_name[512], var_val[512];
2488 char **pam_env = pam_getenvlist((pam_handle_t *)pamh);
2489 int i;
2490 for(i = 0; pam_env && pam_env[i]; i++) {
2491 equals = strstr(pam_env[i], "=");
2492 if ((strlen(pam_env[i]) < (sizeof(var_name) - 1)) && (equals != NULL))
2493 {
Damien Millerdc33fc31999-12-04 20:24:48 +11002494 debug("PAM environment: %s=%s", var_name, var_val);
Damien Miller95def091999-11-25 00:26:21 +11002495 memset(var_name, '\0', sizeof(var_name));
2496 memset(var_val, '\0', sizeof(var_val));
2497 strncpy(var_name, pam_env[i], equals - pam_env[i]);
2498 strcpy(var_val, equals + 1);
2499 child_set_env(&env, &envsize, var_name, var_val);
2500 }
2501 }
2502 }
Damien Miller94388161999-10-29 09:57:31 +10002503#endif /* HAVE_LIBPAM */
2504
Damien Miller95def091999-11-25 00:26:21 +11002505 if (xauthfile)
2506 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002507
Damien Miller95def091999-11-25 00:26:21 +11002508 if (auth_get_socket_name() != NULL)
2509 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
2510 auth_get_socket_name());
Damien Miller776af5d1999-11-12 08:49:09 +11002511
Damien Miller5428f641999-11-25 11:54:57 +11002512 /* read $HOME/.ssh/environment. */
Damien Miller95def091999-11-25 00:26:21 +11002513 if (!options.use_login) {
2514 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
2515 read_environment_file(&env, &envsize, buf);
2516 }
Damien Miller95def091999-11-25 00:26:21 +11002517 if (debug_flag) {
Damien Miller5428f641999-11-25 11:54:57 +11002518 /* dump the environment */
Damien Miller95def091999-11-25 00:26:21 +11002519 fprintf(stderr, "Environment:\n");
2520 for (i = 0; env[i]; i++)
2521 fprintf(stderr, " %.200s\n", env[i]);
2522 }
Damien Miller5428f641999-11-25 11:54:57 +11002523 /*
2524 * Close the connection descriptors; note that this is the child, and
2525 * the server will still have the socket open, and it is important
2526 * that we do not shutdown it. Note that the descriptors cannot be
2527 * closed before building the environment, as we call
2528 * get_remote_ipaddr there.
2529 */
Damien Miller95def091999-11-25 00:26:21 +11002530 if (packet_get_connection_in() == packet_get_connection_out())
2531 close(packet_get_connection_in());
2532 else {
2533 close(packet_get_connection_in());
2534 close(packet_get_connection_out());
2535 }
Damien Miller5428f641999-11-25 11:54:57 +11002536 /*
2537 * Close all descriptors related to channels. They will still remain
2538 * open in the parent.
2539 */
2540 /* XXX better use close-on-exec? -markus */
Damien Miller95def091999-11-25 00:26:21 +11002541 channel_close_all();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002542
Damien Miller5428f641999-11-25 11:54:57 +11002543 /*
2544 * Close any extra file descriptors. Note that there may still be
2545 * descriptors left by system functions. They will be closed later.
2546 */
Damien Miller95def091999-11-25 00:26:21 +11002547 endpwent();
2548 endhostent();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002549
Damien Miller5428f641999-11-25 11:54:57 +11002550 /*
2551 * Close any extra open file descriptors so that we don\'t have them
2552 * hanging around in clients. Note that we want to do this after
2553 * initgroups, because at least on Solaris 2.3 it leaves file
2554 * descriptors open.
2555 */
Damien Miller95def091999-11-25 00:26:21 +11002556 for (i = 3; i < 64; i++)
2557 close(i);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002558
Damien Miller95def091999-11-25 00:26:21 +11002559 /* Change current directory to the user\'s home directory. */
2560 if (chdir(pw->pw_dir) < 0)
2561 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2562 pw->pw_dir, strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002563
Damien Miller5428f641999-11-25 11:54:57 +11002564 /*
2565 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
2566 * xauth are run in the proper environment.
2567 */
Damien Miller95def091999-11-25 00:26:21 +11002568 environ = env;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002569
Damien Miller5428f641999-11-25 11:54:57 +11002570 /*
2571 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
2572 * in this order).
2573 */
Damien Miller95def091999-11-25 00:26:21 +11002574 if (!options.use_login) {
2575 if (stat(SSH_USER_RC, &st) >= 0) {
2576 if (debug_flag)
2577 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002578
Damien Miller95def091999-11-25 00:26:21 +11002579 f = popen("/bin/sh " SSH_USER_RC, "w");
2580 if (f) {
2581 if (auth_proto != NULL && auth_data != NULL)
2582 fprintf(f, "%s %s\n", auth_proto, auth_data);
2583 pclose(f);
2584 } else
2585 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2586 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
2587 if (debug_flag)
2588 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002589
Damien Miller95def091999-11-25 00:26:21 +11002590 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2591 if (f) {
2592 if (auth_proto != NULL && auth_data != NULL)
2593 fprintf(f, "%s %s\n", auth_proto, auth_data);
2594 pclose(f);
2595 } else
2596 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2597 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002598#ifdef XAUTH_PATH
Damien Miller95def091999-11-25 00:26:21 +11002599 else {
Damien Miller5428f641999-11-25 11:54:57 +11002600 /* Add authority data to .Xauthority if appropriate. */
Damien Miller95def091999-11-25 00:26:21 +11002601 if (auth_proto != NULL && auth_data != NULL) {
2602 if (debug_flag)
2603 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2604 XAUTH_PATH, display, auth_proto, auth_data);
2605
2606 f = popen(XAUTH_PATH " -q -", "w");
2607 if (f) {
2608 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
2609 fclose(f);
2610 } else
2611 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2612 }
2613 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002614#endif /* XAUTH_PATH */
2615
Damien Miller95def091999-11-25 00:26:21 +11002616 /* Get the last component of the shell name. */
2617 cp = strrchr(shell, '/');
2618 if (cp)
2619 cp++;
2620 else
2621 cp = shell;
2622 }
Damien Miller5428f641999-11-25 11:54:57 +11002623 /*
2624 * If we have no command, execute the shell. In this case, the shell
2625 * name to be passed in argv[0] is preceded by '-' to indicate that
2626 * this is a login shell.
2627 */
Damien Miller95def091999-11-25 00:26:21 +11002628 if (!command) {
2629 if (!options.use_login) {
2630 char buf[256];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002631
Damien Miller5428f641999-11-25 11:54:57 +11002632 /*
2633 * Check for mail if we have a tty and it was enabled
2634 * in server options.
2635 */
Damien Miller95def091999-11-25 00:26:21 +11002636 if (ttyname && options.check_mail) {
2637 char *mailbox;
2638 struct stat mailstat;
2639 mailbox = getenv("MAIL");
2640 if (mailbox != NULL) {
2641 if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
2642 printf("No mail.\n");
2643 else if (mailstat.st_mtime < mailstat.st_atime)
2644 printf("You have mail.\n");
2645 else
2646 printf("You have new mail.\n");
2647 }
2648 }
2649 /* Start the shell. Set initial character to '-'. */
2650 buf[0] = '-';
2651 strncpy(buf + 1, cp, sizeof(buf) - 1);
2652 buf[sizeof(buf) - 1] = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002653
Damien Miller95def091999-11-25 00:26:21 +11002654 /* Execute the shell. */
2655 argv[0] = buf;
2656 argv[1] = NULL;
2657 execve(shell, argv, env);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002658
Damien Miller95def091999-11-25 00:26:21 +11002659 /* Executing the shell failed. */
2660 perror(shell);
2661 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002662
Damien Miller95def091999-11-25 00:26:21 +11002663 } else {
2664 /* Launch login(1). */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002665
Damien Miller95def091999-11-25 00:26:21 +11002666 execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(),
2667 "-p", "-f", "--", pw->pw_name, NULL);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002668
Damien Miller95def091999-11-25 00:26:21 +11002669 /* Login couldn't be executed, die. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002670
Damien Miller95def091999-11-25 00:26:21 +11002671 perror("login");
2672 exit(1);
2673 }
2674 }
Damien Miller5428f641999-11-25 11:54:57 +11002675 /*
2676 * Execute the command using the user's shell. This uses the -c
2677 * option to execute the command.
2678 */
Damien Miller95def091999-11-25 00:26:21 +11002679 argv[0] = (char *) cp;
2680 argv[1] = "-c";
2681 argv[2] = (char *) command;
2682 argv[3] = NULL;
2683 execve(shell, argv, env);
2684 perror(shell);
2685 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002686}