blob: 9c570ab8ab747ff7819aa54c749cae861d9403cd [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 Miller2e1b0821999-12-25 10:11:29 +110014RCSID("$Id: sshd.c,v 1.40 1999/12/24 23:11:29 damien Exp $");
Damien Miller50945fa1999-12-09 10:31:37 +110015
Damien Miller6ae00d61999-12-14 15:43:03 +110016#ifdef HAVE_POLL_H
17# include <poll.h>
18#else /* HAVE_POLL_H */
19# ifdef HAVE_SYS_POLL_H
20# include <sys/poll.h>
21# endif /* HAVE_SYS_POLL_H */
22#endif /* HAVE_POLL_H */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100023
24#include "xmalloc.h"
25#include "rsa.h"
26#include "ssh.h"
27#include "pty.h"
28#include "packet.h"
29#include "buffer.h"
30#include "cipher.h"
31#include "mpaux.h"
32#include "servconf.h"
33#include "uidswap.h"
34#include "compat.h"
35
36#ifdef LIBWRAP
37#include <tcpd.h>
38#include <syslog.h>
39int allow_severity = LOG_INFO;
40int deny_severity = LOG_WARNING;
41#endif /* LIBWRAP */
42
43#ifndef O_NOCTTY
44#define O_NOCTTY 0
45#endif
46
Damien Millerd4a8b7e1999-10-27 13:42:43 +100047/* Local Xauthority file. */
Damien Miller5ce662a1999-11-11 17:57:39 +110048static char *xauthfile = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +100049
50/* Server configuration options. */
51ServerOptions options;
52
53/* Name of the server configuration file. */
54char *config_file_name = SERVER_CONFIG_FILE;
55
Damien Miller95def091999-11-25 00:26:21 +110056/*
57 * Debug mode flag. This can be set on the command line. If debug
58 * mode is enabled, extra debugging output will be sent to the system
59 * log, the daemon will not go to background, and will exit after processing
60 * the first connection.
61 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100062int debug_flag = 0;
63
64/* Flag indicating that the daemon is being started from inetd. */
65int inetd_flag = 0;
66
Damien Miller5ce662a1999-11-11 17:57:39 +110067/* debug goes to stderr unless inetd_flag is set */
68int log_stderr = 0;
69
Damien Millerd4a8b7e1999-10-27 13:42:43 +100070/* argv[0] without path. */
71char *av0;
72
73/* Saved arguments to main(). */
74char **saved_argv;
75
Damien Miller5428f641999-11-25 11:54:57 +110076/*
77 * This is set to the socket that the server is listening; this is used in
78 * the SIGHUP signal handler.
79 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100080int listen_sock;
81
Damien Miller5428f641999-11-25 11:54:57 +110082/*
83 * the client's version string, passed by sshd2 in compat mode. if != NULL,
84 * sshd will skip the version-number exchange
85 */
Damien Miller95def091999-11-25 00:26:21 +110086char *client_version_string = NULL;
87
88/* Flags set in auth-rsa from authorized_keys flags. These are set in auth-rsa.c. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +100089int no_port_forwarding_flag = 0;
90int no_agent_forwarding_flag = 0;
91int no_x11_forwarding_flag = 0;
92int no_pty_flag = 0;
Damien Miller95def091999-11-25 00:26:21 +110093
94/* RSA authentication "command=" option. */
95char *forced_command = NULL;
96
97/* RSA authentication "environment=" options. */
98struct envstring *custom_environment = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +100099
100/* Session id for the current session. */
101unsigned char session_id[16];
102
Damien Miller5428f641999-11-25 11:54:57 +1100103/*
104 * Any really sensitive data in the application is contained in this
105 * structure. The idea is that this structure could be locked into memory so
106 * that the pages do not get written into swap. However, there are some
107 * problems. The private key contains BIGNUMs, and we do not (in principle)
108 * have access to the internals of them, and locking just the structure is
109 * not very useful. Currently, memory locking is not implemented.
110 */
Damien Miller95def091999-11-25 00:26:21 +1100111struct {
112 RSA *private_key; /* Private part of server key. */
113 RSA *host_key; /* Private part of host key. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000114} sensitive_data;
115
Damien Miller5428f641999-11-25 11:54:57 +1100116/*
117 * Flag indicating whether the current session key has been used. This flag
118 * is set whenever the key is used, and cleared when the key is regenerated.
119 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000120int key_used = 0;
121
122/* This is set to true when SIGHUP is received. */
123int received_sighup = 0;
124
125/* Public side of the server key. This value is regenerated regularly with
126 the private key. */
127RSA *public_key;
128
129/* Prototypes for various functions defined later in this file. */
Damien Miller2ccf6611999-11-15 15:25:10 +1100130void do_connection();
131void do_authentication(char *user);
Damien Miller95def091999-11-25 00:26:21 +1100132void do_authloop(struct passwd * pw);
Damien Miller2ccf6611999-11-15 15:25:10 +1100133void do_fake_authloop(char *user);
Damien Miller95def091999-11-25 00:26:21 +1100134void do_authenticated(struct passwd * pw);
135void do_exec_pty(const char *command, int ptyfd, int ttyfd,
136 const char *ttyname, struct passwd * pw, const char *term,
137 const char *display, const char *auth_proto,
138 const char *auth_data);
139void do_exec_no_pty(const char *command, struct passwd * pw,
140 const char *display, const char *auth_proto,
141 const char *auth_data);
142void do_child(const char *command, struct passwd * pw, const char *term,
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000143 const char *display, const char *auth_proto,
144 const char *auth_data, const char *ttyname);
Damien Miller2ccf6611999-11-15 15:25:10 +1100145
Damien Miller06230761999-10-28 14:03:14 +1000146#ifdef HAVE_LIBPAM
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000147static int pamconv(int num_msg, const struct pam_message **msg,
Damien Miller95def091999-11-25 00:26:21 +1100148 struct pam_response **resp, void *appdata_ptr);
Damien Miller2e1b0821999-12-25 10:11:29 +1100149int do_pam_auth(const char *user, const char *password);
Damien Millerbf1c9b21999-12-09 10:16:54 +1100150void do_pam_account(char *username, char *remote_user);
151void do_pam_session(char *username, char *ttyname);
Damien Miller332e67f1999-10-27 23:42:05 +1000152void pam_cleanup_proc(void *context);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000153
154static struct pam_conv conv = {
Damien Miller95def091999-11-25 00:26:21 +1100155 pamconv,
156 NULL
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000157};
Damien Miller332e67f1999-10-27 23:42:05 +1000158struct pam_handle_t *pamh = NULL;
159const char *pampasswd = NULL;
Damien Miller356a0b01999-11-08 15:30:59 +1100160char *pamconv_msg = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000161
162static int pamconv(int num_msg, const struct pam_message **msg,
Damien Miller9072e181999-11-25 10:42:08 +1100163 struct pam_response **resp, void *appdata_ptr)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000164{
Damien Miller95def091999-11-25 00:26:21 +1100165 struct pam_response *reply;
166 int count;
167 size_t msg_len;
168 char *p;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000169
Damien Miller95def091999-11-25 00:26:21 +1100170 /* PAM will free this later */
171 reply = malloc(num_msg * sizeof(*reply));
172 if (reply == NULL)
173 return PAM_CONV_ERR;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000174
Damien Miller95def091999-11-25 00:26:21 +1100175 for(count = 0; count < num_msg; count++) {
176 switch (msg[count]->msg_style) {
177 case PAM_PROMPT_ECHO_OFF:
178 if (pampasswd == NULL) {
179 free(reply);
180 return PAM_CONV_ERR;
181 }
182 reply[count].resp_retcode = PAM_SUCCESS;
183 reply[count].resp = xstrdup(pampasswd);
184 break;
Damien Miller5bbbd361999-11-19 07:56:21 +1100185
Damien Miller95def091999-11-25 00:26:21 +1100186 case PAM_TEXT_INFO:
187 reply[count].resp_retcode = PAM_SUCCESS;
188 reply[count].resp = xstrdup("");
189
190 if (msg[count]->msg == NULL)
191 break;
192
193 debug("Adding PAM message: %s", msg[count]->msg);
194
195 msg_len = strlen(msg[count]->msg);
196 if (pamconv_msg) {
197 size_t n = strlen(pamconv_msg);
198 pamconv_msg = xrealloc(pamconv_msg, n + msg_len + 2);
199 p = pamconv_msg + n;
200 } else {
201 pamconv_msg = p = xmalloc(msg_len + 2);
202 }
203 memcpy(p, msg[count]->msg, msg_len);
204 p[msg_len] = '\n';
205 p[msg_len + 1] = '\0';
206 break;
207
208 case PAM_PROMPT_ECHO_ON:
209 case PAM_ERROR_MSG:
210 default:
211 free(reply);
212 return PAM_CONV_ERR;
213 }
Damien Miller356a0b01999-11-08 15:30:59 +1100214 }
Damien Miller332e67f1999-10-27 23:42:05 +1000215
Damien Miller95def091999-11-25 00:26:21 +1100216 *resp = reply;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000217
Damien Miller95def091999-11-25 00:26:21 +1100218 return PAM_SUCCESS;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000219}
220
221void pam_cleanup_proc(void *context)
222{
Damien Miller95def091999-11-25 00:26:21 +1100223 int pam_retval;
224
225 if (pamh != NULL)
226 {
227 pam_retval = pam_close_session((pam_handle_t *)pamh, 0);
228 if (pam_retval != PAM_SUCCESS) {
229 log("Cannot close PAM session: %.200s",
230 PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
231 }
232
233 pam_retval = pam_end((pam_handle_t *)pamh, pam_retval);
234 if (pam_retval != PAM_SUCCESS) {
235 log("Cannot release PAM authentication: %.200s",
236 PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
237 }
238 }
Damien Miller332e67f1999-10-27 23:42:05 +1000239}
240
Damien Miller2e1b0821999-12-25 10:11:29 +1100241int do_pam_auth(const char *user, const char *password)
242{
243 int pam_retval;
244
245 pampasswd = password;
246
247 pam_retval = pam_authenticate((pam_handle_t *)pamh, 0);
248 if (pam_retval == PAM_SUCCESS) {
249 log("PAM Password authentication accepted for user \"%.100s\"", user);
250 return 1;
251 } else {
252 log("PAM Password authentication for \"%.100s\" failed: %s",
253 user, PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
254 return 0;
255 }
256}
257
Damien Millerbf1c9b21999-12-09 10:16:54 +1100258void do_pam_account(char *username, char *remote_user)
Damien Miller332e67f1999-10-27 23:42:05 +1000259{
Damien Miller95def091999-11-25 00:26:21 +1100260 int pam_retval;
Damien Miller332e67f1999-10-27 23:42:05 +1000261
Damien Millerdc33fc31999-12-04 20:24:48 +1100262 debug("PAM setting rhost to \"%.200s\"", get_canonical_hostname());
263 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RHOST,
264 get_canonical_hostname());
265 if (pam_retval != PAM_SUCCESS) {
266 log("PAM set rhost failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
267 do_fake_authloop(username);
Damien Miller95def091999-11-25 00:26:21 +1100268 }
269
270 if (remote_user != NULL) {
271 debug("PAM setting ruser to \"%.200s\"", remote_user);
272 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RUSER, remote_user);
273 if (pam_retval != PAM_SUCCESS) {
274 log("PAM set ruser failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
275 do_fake_authloop(username);
276 }
277 }
278
279 pam_retval = pam_acct_mgmt((pam_handle_t *)pamh, 0);
280 if (pam_retval != PAM_SUCCESS) {
281 log("PAM rejected by account configuration: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
282 do_fake_authloop(username);
283 }
Damien Millerbf1c9b21999-12-09 10:16:54 +1100284}
285
286void do_pam_session(char *username, char *ttyname)
287{
288 int pam_retval;
289
290 if (ttyname != NULL) {
291 debug("PAM setting tty to \"%.200s\"", ttyname);
292 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_TTY, ttyname);
293 if (pam_retval != PAM_SUCCESS)
294 fatal("PAM set tty failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
295 }
Damien Miller95def091999-11-25 00:26:21 +1100296
297 pam_retval = pam_open_session((pam_handle_t *)pamh, 0);
Damien Millerbf1c9b21999-12-09 10:16:54 +1100298 if (pam_retval != PAM_SUCCESS)
299 fatal("PAM session setup failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000300}
Damien Miller06230761999-10-28 14:03:14 +1000301#endif /* HAVE_LIBPAM */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000302
Damien Miller95def091999-11-25 00:26:21 +1100303/*
304 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
305 * the effect is to reread the configuration file (and to regenerate
306 * the server key).
307 */
308void
309sighup_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000310{
Damien Miller95def091999-11-25 00:26:21 +1100311 received_sighup = 1;
312 signal(SIGHUP, sighup_handler);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000313}
314
Damien Miller95def091999-11-25 00:26:21 +1100315/*
316 * Called from the main program after receiving SIGHUP.
317 * Restarts the server.
318 */
319void
320sighup_restart()
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000321{
Damien Miller95def091999-11-25 00:26:21 +1100322 log("Received SIGHUP; restarting.");
323 close(listen_sock);
324 execv(saved_argv[0], saved_argv);
325 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
326 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000327}
328
Damien Miller95def091999-11-25 00:26:21 +1100329/*
330 * Generic signal handler for terminating signals in the master daemon.
331 * These close the listen socket; not closing it seems to cause "Address
332 * already in use" problems on some machines, which is inconvenient.
333 */
334void
335sigterm_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000336{
Damien Miller95def091999-11-25 00:26:21 +1100337 log("Received signal %d; terminating.", sig);
338 close(listen_sock);
339 exit(255);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000340}
341
Damien Miller95def091999-11-25 00:26:21 +1100342/*
343 * SIGCHLD handler. This is called whenever a child dies. This will then
344 * reap any zombies left by exited c.
345 */
346void
347main_sigchld_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000348{
Damien Miller95def091999-11-25 00:26:21 +1100349 int save_errno = errno;
350 int status;
Damien Miller431f66b1999-11-21 18:31:57 +1100351
Damien Miller95def091999-11-25 00:26:21 +1100352 while (waitpid(-1, &status, WNOHANG) > 0)
353 ;
Damien Miller431f66b1999-11-21 18:31:57 +1100354
Damien Miller95def091999-11-25 00:26:21 +1100355 signal(SIGCHLD, main_sigchld_handler);
356 errno = save_errno;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000357}
358
Damien Miller95def091999-11-25 00:26:21 +1100359/*
360 * Signal handler for the alarm after the login grace period has expired.
361 */
362void
363grace_alarm_handler(int sig)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000364{
Damien Miller95def091999-11-25 00:26:21 +1100365 /* Close the connection. */
366 packet_close();
367
368 /* Log error and exit. */
369 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000370}
371
Damien Miller95def091999-11-25 00:26:21 +1100372/*
373 * convert ssh auth msg type into description
374 */
375char *
376get_authname(int type)
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000377{
Damien Miller95def091999-11-25 00:26:21 +1100378 switch (type) {
379 case SSH_CMSG_AUTH_PASSWORD:
380 return "password";
381 case SSH_CMSG_AUTH_RSA:
382 return "rsa";
383 case SSH_CMSG_AUTH_RHOSTS_RSA:
384 return "rhosts-rsa";
385 case SSH_CMSG_AUTH_RHOSTS:
386 return "rhosts";
387#ifdef KRB4
388 case SSH_CMSG_AUTH_KERBEROS:
389 return "kerberos";
390#endif
391#ifdef SKEY
392 case SSH_CMSG_AUTH_TIS_RESPONSE:
393 return "s/key";
394#endif
395 }
396 fatal("get_authname: unknown auth %d: internal error", type);
397 return NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000398}
399
Damien Miller95def091999-11-25 00:26:21 +1100400/*
401 * Signal handler for the key regeneration alarm. Note that this
402 * alarm only occurs in the daemon waiting for connections, and it does not
403 * do anything with the private key or random state before forking.
404 * Thus there should be no concurrency control/asynchronous execution
405 * problems.
406 */
407void
408key_regeneration_alarm(int sig)
409{
410 int save_errno = errno;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000411
Damien Miller95def091999-11-25 00:26:21 +1100412 /* Check if we should generate a new key. */
413 if (key_used) {
414 /* This should really be done in the background. */
415 log("Generating new %d bit RSA key.", options.server_key_bits);
416
417 if (sensitive_data.private_key != NULL)
418 RSA_free(sensitive_data.private_key);
419 sensitive_data.private_key = RSA_new();
420
421 if (public_key != NULL)
422 RSA_free(public_key);
423 public_key = RSA_new();
424
425 rsa_generate_key(sensitive_data.private_key, public_key,
426 options.server_key_bits);
427 arc4random_stir();
428 key_used = 0;
429 log("RSA key generation complete.");
430 }
431 /* Reschedule the alarm. */
432 signal(SIGALRM, key_regeneration_alarm);
433 alarm(options.key_regeneration_time);
434 errno = save_errno;
435}
436
437/*
438 * Main program for the daemon.
439 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000440int
441main(int ac, char **av)
442{
Damien Miller95def091999-11-25 00:26:21 +1100443 extern char *optarg;
444 extern int optind;
445 int opt, aux, sock_in, sock_out, newsock, i, pid, on = 1;
446 int remote_major, remote_minor;
447 int silentrsa = 0;
Damien Miller50945fa1999-12-09 10:31:37 +1100448 struct pollfd fds;
Damien Miller95def091999-11-25 00:26:21 +1100449 struct sockaddr_in sin;
450 char buf[100]; /* Must not be larger than remote_version. */
451 char remote_version[100]; /* Must be at least as big as buf. */
452 const char *remote_ip;
453 int remote_port;
454 char *comment;
455 FILE *f;
456 struct linger linger;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000457
Damien Miller95def091999-11-25 00:26:21 +1100458 /* Save argv[0]. */
459 saved_argv = av;
460 if (strchr(av[0], '/'))
461 av0 = strrchr(av[0], '/') + 1;
462 else
463 av0 = av[0];
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000464
Damien Miller95def091999-11-25 00:26:21 +1100465 /* Initialize configuration options to their default values. */
466 initialize_server_options(&options);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000467
Damien Miller95def091999-11-25 00:26:21 +1100468 /* Parse command-line arguments. */
469 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ")) != EOF) {
470 switch (opt) {
471 case 'f':
472 config_file_name = optarg;
473 break;
474 case 'd':
475 debug_flag = 1;
476 options.log_level = SYSLOG_LEVEL_DEBUG;
477 break;
478 case 'i':
479 inetd_flag = 1;
480 break;
481 case 'Q':
482 silentrsa = 1;
483 break;
484 case 'q':
485 options.log_level = SYSLOG_LEVEL_QUIET;
486 break;
487 case 'b':
488 options.server_key_bits = atoi(optarg);
489 break;
490 case 'p':
491 options.port = atoi(optarg);
492 break;
493 case 'g':
494 options.login_grace_time = atoi(optarg);
495 break;
496 case 'k':
497 options.key_regeneration_time = atoi(optarg);
498 break;
499 case 'h':
500 options.host_key_file = optarg;
501 break;
502 case 'V':
503 client_version_string = optarg;
504 /* only makes sense with inetd_flag, i.e. no listen() */
505 inetd_flag = 1;
506 break;
507 case '?':
508 default:
509 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
510 fprintf(stderr, "Usage: %s [options]\n", av0);
511 fprintf(stderr, "Options:\n");
Damien Miller5428f641999-11-25 11:54:57 +1100512 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE);
Damien Miller95def091999-11-25 00:26:21 +1100513 fprintf(stderr, " -d Debugging mode\n");
514 fprintf(stderr, " -i Started from inetd\n");
515 fprintf(stderr, " -q Quiet (no logging)\n");
516 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
517 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
518 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
519 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
520 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
521 HOST_KEY_FILE);
522 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000523 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000524 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000525
Damien Miller95def091999-11-25 00:26:21 +1100526 /* check if RSA support exists */
527 if (rsa_alive() == 0) {
528 if (silentrsa == 0)
529 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
530 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
531 exit(1);
532 }
533 /* Read server configuration options from the configuration file. */
534 read_server_config(&options, config_file_name);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000535
Damien Miller95def091999-11-25 00:26:21 +1100536 /* Fill in default values for those options not explicitly set. */
537 fill_default_server_options(&options);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000538
Damien Miller95def091999-11-25 00:26:21 +1100539 /* Check certain values for sanity. */
540 if (options.server_key_bits < 512 ||
541 options.server_key_bits > 32768) {
542 fprintf(stderr, "Bad server key size.\n");
543 exit(1);
544 }
545 if (options.port < 1 || options.port > 65535) {
546 fprintf(stderr, "Bad port number.\n");
547 exit(1);
548 }
549 /* Check that there are no remaining arguments. */
550 if (optind < ac) {
551 fprintf(stderr, "Extra argument %s.\n", av[optind]);
552 exit(1);
553 }
554 /* Force logging to stderr while loading the private host key
555 unless started from inetd */
556 log_init(av0, options.log_level, options.log_facility, !inetd_flag);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000557
Damien Miller95def091999-11-25 00:26:21 +1100558 debug("sshd version %.100s", SSH_VERSION);
Damien Miller2ccf6611999-11-15 15:25:10 +1100559
Damien Miller95def091999-11-25 00:26:21 +1100560 sensitive_data.host_key = RSA_new();
561 errno = 0;
562 /* Load the host key. It must have empty passphrase. */
563 if (!load_private_key(options.host_key_file, "",
564 sensitive_data.host_key, &comment)) {
565 error("Could not load host key: %.200s: %.100s",
566 options.host_key_file, strerror(errno));
567 exit(1);
568 }
569 xfree(comment);
570
571 /* Initialize the log (it is reinitialized below in case we
572 forked). */
573 if (debug_flag && !inetd_flag)
574 log_stderr = 1;
575 log_init(av0, options.log_level, options.log_facility, log_stderr);
576
577 /* If not in debugging mode, and not started from inetd,
578 disconnect from the controlling terminal, and fork. The
579 original process exits. */
580 if (!debug_flag && !inetd_flag) {
581#ifdef TIOCNOTTY
582 int fd;
583#endif /* TIOCNOTTY */
584 if (daemon(0, 0) < 0)
585 fatal("daemon() failed: %.200s", strerror(errno));
586
587 /* Disconnect from the controlling tty. */
588#ifdef TIOCNOTTY
589 fd = open("/dev/tty", O_RDWR | O_NOCTTY);
590 if (fd >= 0) {
591 (void) ioctl(fd, TIOCNOTTY, NULL);
592 close(fd);
593 }
594#endif /* TIOCNOTTY */
595 }
596 /* Reinitialize the log (because of the fork above). */
597 log_init(av0, options.log_level, options.log_facility, log_stderr);
598
599 /* Check that server and host key lengths differ sufficiently.
600 This is necessary to make double encryption work with rsaref.
601 Oh, I hate software patents. I dont know if this can go? Niels */
602 if (options.server_key_bits >
603 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
604 options.server_key_bits <
605 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
606 options.server_key_bits =
607 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
608 debug("Forcing server key to %d bits to make it differ from host key.",
609 options.server_key_bits);
610 }
611 /* Do not display messages to stdout in RSA code. */
612 rsa_set_verbose(0);
613
614 /* Initialize the random number generator. */
615 arc4random_stir();
616
617 /* Chdir to the root directory so that the current disk can be
618 unmounted if desired. */
619 chdir("/");
620
621 /* Close connection cleanly after attack. */
622 cipher_attack_detected = packet_disconnect;
623
624 /* Start listening for a socket, unless started from inetd. */
625 if (inetd_flag) {
626 int s1, s2;
627 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
628 s2 = dup(s1);
629 sock_in = dup(0);
630 sock_out = dup(1);
631 /* We intentionally do not close the descriptors 0, 1, and 2
632 as our code for setting the descriptors won\'t work
633 if ttyfd happens to be one of those. */
634 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
635
636 public_key = RSA_new();
637 sensitive_data.private_key = RSA_new();
638
639 log("Generating %d bit RSA key.", options.server_key_bits);
640 rsa_generate_key(sensitive_data.private_key, public_key,
641 options.server_key_bits);
642 arc4random_stir();
643 log("RSA key generation complete.");
644 } else {
645 /* Create socket for listening. */
646 listen_sock = socket(AF_INET, SOCK_STREAM, 0);
647 if (listen_sock < 0)
648 fatal("socket: %.100s", strerror(errno));
649
650 /* Set socket options. We try to make the port reusable
651 and have it close as fast as possible without waiting
652 in unnecessary wait states on close. */
653 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on,
654 sizeof(on));
655 linger.l_onoff = 1;
656 linger.l_linger = 5;
657 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, (void *) &linger,
658 sizeof(linger));
659
Damien Miller95def091999-11-25 00:26:21 +1100660 memset(&sin, 0, sizeof(sin));
661 sin.sin_family = AF_INET;
662 sin.sin_addr = options.listen_addr;
663 sin.sin_port = htons(options.port);
664
Damien Miller95def091999-11-25 00:26:21 +1100665 if (bind(listen_sock, (struct sockaddr *) & sin, sizeof(sin)) < 0) {
666 error("bind: %.100s", strerror(errno));
667 shutdown(listen_sock, SHUT_RDWR);
668 close(listen_sock);
669 fatal("Bind to port %d failed.", options.port);
670 }
671 if (!debug_flag) {
Damien Miller5428f641999-11-25 11:54:57 +1100672 /*
673 * Record our pid in /etc/sshd_pid to make it easier
674 * to kill the correct sshd. We don\'t want to do
675 * this before the bind above because the bind will
676 * fail if there already is a daemon, and this will
677 * overwrite any old pid in the file.
678 */
Damien Miller95def091999-11-25 00:26:21 +1100679 f = fopen(SSH_DAEMON_PID_FILE, "w");
680 if (f) {
681 fprintf(f, "%u\n", (unsigned int) getpid());
682 fclose(f);
683 }
684 }
685
686 log("Server listening on port %d.", options.port);
687 if (listen(listen_sock, 5) < 0)
688 fatal("listen: %.100s", strerror(errno));
689
690 public_key = RSA_new();
691 sensitive_data.private_key = RSA_new();
692
693 log("Generating %d bit RSA key.", options.server_key_bits);
694 rsa_generate_key(sensitive_data.private_key, public_key,
695 options.server_key_bits);
696 arc4random_stir();
697 log("RSA key generation complete.");
698
699 /* Schedule server key regeneration alarm. */
700 signal(SIGALRM, key_regeneration_alarm);
701 alarm(options.key_regeneration_time);
702
703 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
704 signal(SIGHUP, sighup_handler);
705 signal(SIGTERM, sigterm_handler);
706 signal(SIGQUIT, sigterm_handler);
707
708 /* Arrange SIGCHLD to be caught. */
709 signal(SIGCHLD, main_sigchld_handler);
710
Damien Miller5428f641999-11-25 11:54:57 +1100711 /*
712 * Stay listening for connections until the system crashes or
713 * the daemon is killed with a signal.
714 */
Damien Miller95def091999-11-25 00:26:21 +1100715 for (;;) {
716 if (received_sighup)
717 sighup_restart();
Damien Miller50945fa1999-12-09 10:31:37 +1100718 /* Wait in poll until there is a connection. */
719 memset(&fds, 0, sizeof(fds));
720 fds.fd = listen_sock;
721 fds.events = POLLIN;
722 if (poll(&fds, 1, -1) == -1) {
723 if (errno == EINTR)
724 continue;
725 fatal("poll: %.100s", strerror(errno));
726 /*NOTREACHED*/
727 }
728 if (fds.revents == 0)
729 continue;
Damien Miller95def091999-11-25 00:26:21 +1100730 aux = sizeof(sin);
731 newsock = accept(listen_sock, (struct sockaddr *) & sin, &aux);
732 if (received_sighup)
733 sighup_restart();
734 if (newsock < 0) {
735 if (errno == EINTR)
736 continue;
737 error("accept: %.100s", strerror(errno));
738 continue;
739 }
Damien Miller5428f641999-11-25 11:54:57 +1100740 /*
741 * Got connection. Fork a child to handle it, unless
742 * we are in debugging mode.
743 */
Damien Miller95def091999-11-25 00:26:21 +1100744 if (debug_flag) {
Damien Miller5428f641999-11-25 11:54:57 +1100745 /*
746 * In debugging mode. Close the listening
747 * socket, and start processing the
748 * connection without forking.
749 */
Damien Miller95def091999-11-25 00:26:21 +1100750 debug("Server will not fork when running in debugging mode.");
751 close(listen_sock);
752 sock_in = newsock;
753 sock_out = newsock;
754 pid = getpid();
755 break;
756 } else {
Damien Miller5428f641999-11-25 11:54:57 +1100757 /*
758 * Normal production daemon. Fork, and have
759 * the child process the connection. The
760 * parent continues listening.
761 */
Damien Miller95def091999-11-25 00:26:21 +1100762 if ((pid = fork()) == 0) {
Damien Miller5428f641999-11-25 11:54:57 +1100763 /*
764 * Child. Close the listening socket, and start using the
765 * accepted socket. Reinitialize logging (since our pid has
766 * changed). We break out of the loop to handle the connection.
767 */
Damien Miller95def091999-11-25 00:26:21 +1100768 close(listen_sock);
769 sock_in = newsock;
770 sock_out = newsock;
771 log_init(av0, options.log_level, options.log_facility, log_stderr);
772 break;
773 }
774 }
775
776 /* Parent. Stay in the loop. */
777 if (pid < 0)
778 error("fork: %.100s", strerror(errno));
779 else
780 debug("Forked child %d.", pid);
781
782 /* Mark that the key has been used (it was "given" to the child). */
783 key_used = 1;
784
785 arc4random_stir();
786
787 /* Close the new socket (the child is now taking care of it). */
788 close(newsock);
789 }
790 }
791
792 /* This is the child processing a new connection. */
793
Damien Miller5428f641999-11-25 11:54:57 +1100794 /*
795 * Disable the key regeneration alarm. We will not regenerate the
796 * key since we are no longer in a position to give it to anyone. We
797 * will not restart on SIGHUP since it no longer makes sense.
798 */
Damien Miller95def091999-11-25 00:26:21 +1100799 alarm(0);
800 signal(SIGALRM, SIG_DFL);
801 signal(SIGHUP, SIG_DFL);
802 signal(SIGTERM, SIG_DFL);
803 signal(SIGQUIT, SIG_DFL);
804 signal(SIGCHLD, SIG_DFL);
805
Damien Miller5428f641999-11-25 11:54:57 +1100806 /*
807 * Set socket options for the connection. We want the socket to
808 * close as fast as possible without waiting for anything. If the
809 * connection is not a socket, these will do nothing.
810 */
811 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
Damien Miller95def091999-11-25 00:26:21 +1100812 linger.l_onoff = 1;
813 linger.l_linger = 5;
814 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
815
Damien Miller5428f641999-11-25 11:54:57 +1100816 /*
817 * Register our connection. This turns encryption off because we do
818 * not have a key.
819 */
Damien Miller95def091999-11-25 00:26:21 +1100820 packet_set_connection(sock_in, sock_out);
821
822 remote_port = get_remote_port();
823 remote_ip = get_remote_ipaddr();
824
825 /* Check whether logins are denied from this host. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000826#ifdef LIBWRAP
Damien Miller95def091999-11-25 00:26:21 +1100827 {
828 struct request_info req;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000829
Damien Miller95def091999-11-25 00:26:21 +1100830 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
831 fromhost(&req);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000832
Damien Miller95def091999-11-25 00:26:21 +1100833 if (!hosts_access(&req)) {
834 close(sock_in);
835 close(sock_out);
836 refuse(&req);
837 }
838 verbose("Connection from %.500s port %d", eval_client(&req), remote_port);
839 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000840#else
Damien Miller95def091999-11-25 00:26:21 +1100841 /* Log the connection. */
842 verbose("Connection from %.500s port %d", remote_ip, remote_port);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000843#endif /* LIBWRAP */
844
Damien Miller5428f641999-11-25 11:54:57 +1100845 /*
846 * We don\'t want to listen forever unless the other side
847 * successfully authenticates itself. So we set up an alarm which is
848 * cleared after successful authentication. A limit of zero
849 * indicates no limit. Note that we don\'t set the alarm in debugging
850 * mode; it is just annoying to have the server exit just when you
851 * are about to discover the bug.
852 */
Damien Miller95def091999-11-25 00:26:21 +1100853 signal(SIGALRM, grace_alarm_handler);
854 if (!debug_flag)
855 alarm(options.login_grace_time);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000856
Damien Miller95def091999-11-25 00:26:21 +1100857 if (client_version_string != NULL) {
858 /* we are exec'ed by sshd2, so skip exchange of protocol version */
859 strlcpy(buf, client_version_string, sizeof(buf));
860 } else {
861 /* Send our protocol version identification. */
862 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
863 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
Damien Miller037a0dc1999-12-07 15:38:31 +1100864 if (atomicio(write, sock_out, buf, strlen(buf)) != strlen(buf))
Damien Miller95def091999-11-25 00:26:21 +1100865 fatal("Could not write ident string to %s.", get_remote_ipaddr());
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000866
Damien Miller95def091999-11-25 00:26:21 +1100867 /* Read other side\'s version identification. */
868 for (i = 0; i < sizeof(buf) - 1; i++) {
869 if (read(sock_in, &buf[i], 1) != 1)
870 fatal("Did not receive ident string from %s.", get_remote_ipaddr());
871 if (buf[i] == '\r') {
872 buf[i] = '\n';
873 buf[i + 1] = 0;
874 break;
875 }
876 if (buf[i] == '\n') {
877 /* buf[i] == '\n' */
878 buf[i + 1] = 0;
879 break;
880 }
881 }
882 buf[sizeof(buf) - 1] = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000883 }
Damien Miller95def091999-11-25 00:26:21 +1100884
Damien Miller5428f641999-11-25 11:54:57 +1100885 /*
886 * Check that the versions match. In future this might accept
887 * several versions and set appropriate flags to handle them.
888 */
Damien Miller95def091999-11-25 00:26:21 +1100889 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
Damien Miller037a0dc1999-12-07 15:38:31 +1100890 remote_version) != 3) {
891 char *s = "Protocol mismatch.\n";
892
893 (void) atomicio(write, sock_out, s, strlen(s));
Damien Miller95def091999-11-25 00:26:21 +1100894 close(sock_in);
895 close(sock_out);
896 fatal("Bad protocol version identification '%.100s' from %s",
897 buf, get_remote_ipaddr());
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000898 }
Damien Miller95def091999-11-25 00:26:21 +1100899 debug("Client protocol version %d.%d; client software version %.100s",
900 remote_major, remote_minor, remote_version);
901 if (remote_major != PROTOCOL_MAJOR) {
Damien Miller037a0dc1999-12-07 15:38:31 +1100902 char *s = "Protocol major versions differ.\n";
903
904 (void) atomicio(write, sock_out, s, strlen(s));
Damien Miller95def091999-11-25 00:26:21 +1100905 close(sock_in);
906 close(sock_out);
907 fatal("Protocol major versions differ for %s: %d vs. %d",
908 get_remote_ipaddr(),
909 PROTOCOL_MAJOR, remote_major);
910 }
911 /* Check that the client has sufficiently high software version. */
912 if (remote_major == 1 && remote_minor < 3)
913 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 +1000914
Damien Miller95def091999-11-25 00:26:21 +1100915 if (remote_major == 1 && remote_minor == 3) {
916 enable_compat13();
917 if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
918 debug("Agent forwarding disabled, remote version is not compatible.");
919 no_agent_forwarding_flag = 1;
920 }
921 }
Damien Miller5428f641999-11-25 11:54:57 +1100922 /*
923 * Check that the connection comes from a privileged port. Rhosts-
924 * and Rhosts-RSA-Authentication only make sense from priviledged
925 * programs. Of course, if the intruder has root access on his local
926 * machine, he can connect from any port. So do not use these
927 * authentication methods from machines that you do not trust.
928 */
Damien Miller95def091999-11-25 00:26:21 +1100929 if (remote_port >= IPPORT_RESERVED ||
930 remote_port < IPPORT_RESERVED / 2) {
931 options.rhosts_authentication = 0;
932 options.rhosts_rsa_authentication = 0;
933 }
934 packet_set_nonblocking();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000935
Damien Miller95def091999-11-25 00:26:21 +1100936 /* Handle the connection. */
937 do_connection();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000938
939#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +1100940 /* Cleanup user's ticket cache file. */
941 if (options.kerberos_ticket_cleanup)
942 (void) dest_tkt();
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000943#endif /* KRB4 */
944
Damien Miller95def091999-11-25 00:26:21 +1100945 /* Cleanup user's local Xauthority file. */
946 if (xauthfile)
947 unlink(xauthfile);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000948
Damien Miller95def091999-11-25 00:26:21 +1100949 /* The connection has been terminated. */
950 verbose("Closing connection to %.100s", remote_ip);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000951
Damien Miller06230761999-10-28 14:03:14 +1000952#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +1100953 {
954 int retval;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000955
Damien Miller95def091999-11-25 00:26:21 +1100956 if (pamh != NULL) {
957 debug("Closing PAM session.");
958 retval = pam_close_session((pam_handle_t *)pamh, 0);
959
960 debug("Terminating PAM library.");
961 if (pam_end((pam_handle_t *)pamh, retval) != PAM_SUCCESS)
962 log("Cannot release PAM authentication.");
963
964 fatal_remove_cleanup(&pam_cleanup_proc, NULL);
965 }
966 }
Damien Miller06230761999-10-28 14:03:14 +1000967#endif /* HAVE_LIBPAM */
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000968
Damien Miller95def091999-11-25 00:26:21 +1100969 packet_close();
970 exit(0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000971}
972
Damien Miller95def091999-11-25 00:26:21 +1100973/*
974 * Process an incoming connection. Protocol version identifiers have already
975 * been exchanged. This sends server key and performs the key exchange.
976 * Server and host keys will no longer be needed after this functions.
977 */
Damien Miller2ccf6611999-11-15 15:25:10 +1100978void
979do_connection()
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000980{
Damien Miller95def091999-11-25 00:26:21 +1100981 int i, len;
982 BIGNUM *session_key_int;
983 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
984 unsigned char check_bytes[8];
985 char *user;
986 unsigned int cipher_type, auth_mask, protocol_flags;
Damien Millera34a28b1999-12-14 10:47:15 +1100987 int plen, slen, ulen;
Damien Miller95def091999-11-25 00:26:21 +1100988 u_int32_t rand = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +1000989
Damien Miller5428f641999-11-25 11:54:57 +1100990 /*
991 * Generate check bytes that the client must send back in the user
992 * packet in order for it to be accepted; this is used to defy ip
993 * spoofing attacks. Note that this only works against somebody
994 * doing IP spoofing from a remote machine; any machine on the local
995 * network can still see outgoing packets and catch the random
996 * cookie. This only affects rhosts authentication, and this is one
997 * of the reasons why it is inherently insecure.
998 */
Damien Miller95def091999-11-25 00:26:21 +1100999 for (i = 0; i < 8; i++) {
1000 if (i % 4 == 0)
1001 rand = arc4random();
1002 check_bytes[i] = rand & 0xff;
1003 rand >>= 8;
1004 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001005
Damien Miller5428f641999-11-25 11:54:57 +11001006 /*
1007 * Send our public key. We include in the packet 64 bits of random
1008 * data that must be matched in the reply in order to prevent IP
1009 * spoofing.
1010 */
Damien Miller95def091999-11-25 00:26:21 +11001011 packet_start(SSH_SMSG_PUBLIC_KEY);
1012 for (i = 0; i < 8; i++)
1013 packet_put_char(check_bytes[i]);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001014
Damien Miller95def091999-11-25 00:26:21 +11001015 /* Store our public server RSA key. */
1016 packet_put_int(BN_num_bits(public_key->n));
1017 packet_put_bignum(public_key->e);
1018 packet_put_bignum(public_key->n);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001019
Damien Miller95def091999-11-25 00:26:21 +11001020 /* Store our public host RSA key. */
1021 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
1022 packet_put_bignum(sensitive_data.host_key->e);
1023 packet_put_bignum(sensitive_data.host_key->n);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001024
Damien Miller95def091999-11-25 00:26:21 +11001025 /* Put protocol flags. */
1026 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001027
Damien Miller95def091999-11-25 00:26:21 +11001028 /* Declare which ciphers we support. */
1029 packet_put_int(cipher_mask());
1030
1031 /* Declare supported authentication types. */
1032 auth_mask = 0;
1033 if (options.rhosts_authentication)
1034 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1035 if (options.rhosts_rsa_authentication)
1036 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1037 if (options.rsa_authentication)
1038 auth_mask |= 1 << SSH_AUTH_RSA;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001039#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11001040 if (options.kerberos_authentication)
1041 auth_mask |= 1 << SSH_AUTH_KERBEROS;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001042#endif
1043#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11001044 if (options.kerberos_tgt_passing)
1045 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1046 if (options.afs_token_passing)
1047 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001048#endif
Damien Miller95def091999-11-25 00:26:21 +11001049#ifdef SKEY
1050 if (options.skey_authentication == 1)
1051 auth_mask |= 1 << SSH_AUTH_TIS;
1052#endif
1053 if (options.password_authentication)
1054 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1055 packet_put_int(auth_mask);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001056
Damien Miller95def091999-11-25 00:26:21 +11001057 /* Send the packet and wait for it to be sent. */
1058 packet_send();
1059 packet_write_wait();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001060
Damien Miller95def091999-11-25 00:26:21 +11001061 debug("Sent %d bit public key and %d bit host key.",
1062 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001063
Damien Miller95def091999-11-25 00:26:21 +11001064 /* Read clients reply (cipher type and session key). */
1065 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001066
Damien Miller50945fa1999-12-09 10:31:37 +11001067 /* Get cipher type and check whether we accept this. */
Damien Miller95def091999-11-25 00:26:21 +11001068 cipher_type = packet_get_char();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001069
Damien Miller50945fa1999-12-09 10:31:37 +11001070 if (!(cipher_mask() & (1 << cipher_type)))
1071 packet_disconnect("Warning: client selects unsupported cipher.");
1072
Damien Miller95def091999-11-25 00:26:21 +11001073 /* Get check bytes from the packet. These must match those we
1074 sent earlier with the public key packet. */
1075 for (i = 0; i < 8; i++)
1076 if (check_bytes[i] != packet_get_char())
1077 packet_disconnect("IP Spoofing check bytes do not match.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001078
Damien Miller95def091999-11-25 00:26:21 +11001079 debug("Encryption type: %.200s", cipher_name(cipher_type));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001080
Damien Miller95def091999-11-25 00:26:21 +11001081 /* Get the encrypted integer. */
1082 session_key_int = BN_new();
1083 packet_get_bignum(session_key_int, &slen);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001084
Damien Miller95def091999-11-25 00:26:21 +11001085 protocol_flags = packet_get_int();
1086 packet_set_protocol_flags(protocol_flags);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001087
Damien Miller95def091999-11-25 00:26:21 +11001088 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001089
Damien Miller5428f641999-11-25 11:54:57 +11001090 /*
1091 * Decrypt it using our private server key and private host key (key
1092 * with larger modulus first).
1093 */
Damien Miller95def091999-11-25 00:26:21 +11001094 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1095 /* Private key has bigger modulus. */
1096 if (BN_num_bits(sensitive_data.private_key->n) <
1097 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1098 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1099 get_remote_ipaddr(),
1100 BN_num_bits(sensitive_data.private_key->n),
1101 BN_num_bits(sensitive_data.host_key->n),
1102 SSH_KEY_BITS_RESERVED);
1103 }
1104 rsa_private_decrypt(session_key_int, session_key_int,
1105 sensitive_data.private_key);
1106 rsa_private_decrypt(session_key_int, session_key_int,
1107 sensitive_data.host_key);
1108 } else {
1109 /* Host key has bigger modulus (or they are equal). */
1110 if (BN_num_bits(sensitive_data.host_key->n) <
1111 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1112 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1113 get_remote_ipaddr(),
1114 BN_num_bits(sensitive_data.host_key->n),
1115 BN_num_bits(sensitive_data.private_key->n),
1116 SSH_KEY_BITS_RESERVED);
1117 }
1118 rsa_private_decrypt(session_key_int, session_key_int,
1119 sensitive_data.host_key);
1120 rsa_private_decrypt(session_key_int, session_key_int,
1121 sensitive_data.private_key);
1122 }
Damien Miller356a0b01999-11-08 15:30:59 +11001123
Damien Miller95def091999-11-25 00:26:21 +11001124 compute_session_id(session_id, check_bytes,
1125 sensitive_data.host_key->n,
1126 sensitive_data.private_key->n);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001127
Damien Miller5428f641999-11-25 11:54:57 +11001128 /*
1129 * Extract session key from the decrypted integer. The key is in the
1130 * least significant 256 bits of the integer; the first byte of the
1131 * key is in the highest bits.
1132 */
Damien Miller95def091999-11-25 00:26:21 +11001133 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1134 len = BN_num_bytes(session_key_int);
1135 if (len < 0 || len > sizeof(session_key))
1136 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1137 get_remote_ipaddr(),
1138 len, sizeof(session_key));
1139 memset(session_key, 0, sizeof(session_key));
1140 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001141
Damien Miller95def091999-11-25 00:26:21 +11001142 /* Xor the first 16 bytes of the session key with the session id. */
1143 for (i = 0; i < 16; i++)
1144 session_key[i] ^= session_id[i];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001145
Damien Miller95def091999-11-25 00:26:21 +11001146 /* Destroy the decrypted integer. It is no longer needed. */
1147 BN_clear_free(session_key_int);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001148
Damien Miller95def091999-11-25 00:26:21 +11001149 /* Set the session key. From this on all communications will be encrypted. */
1150 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001151
Damien Miller95def091999-11-25 00:26:21 +11001152 /* Destroy our copy of the session key. It is no longer needed. */
1153 memset(session_key, 0, sizeof(session_key));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001154
Damien Miller95def091999-11-25 00:26:21 +11001155 debug("Received session key; encryption turned on.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001156
Damien Miller95def091999-11-25 00:26:21 +11001157 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1158 packet_start(SSH_SMSG_SUCCESS);
1159 packet_send();
1160 packet_write_wait();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001161
Damien Miller95def091999-11-25 00:26:21 +11001162 /* Get the name of the user that we wish to log in as. */
1163 packet_read_expect(&plen, SSH_CMSG_USER);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001164
Damien Miller95def091999-11-25 00:26:21 +11001165 /* Get the user name. */
Damien Millera34a28b1999-12-14 10:47:15 +11001166 user = packet_get_string(&ulen);
1167 packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
Damien Miller95def091999-11-25 00:26:21 +11001168
1169 /* Destroy the private and public keys. They will no longer be needed. */
1170 RSA_free(public_key);
1171 RSA_free(sensitive_data.private_key);
1172 RSA_free(sensitive_data.host_key);
1173
1174 setproctitle("%s", user);
1175 /* Do the authentication. */
1176 do_authentication(user);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001177}
1178
Damien Miller95def091999-11-25 00:26:21 +11001179/*
1180 * Check if the user is allowed to log in via ssh. If user is listed in
1181 * DenyUsers or user's primary group is listed in DenyGroups, false will
1182 * be returned. If AllowUsers isn't empty and user isn't listed there, or
1183 * if AllowGroups isn't empty and user isn't listed there, false will be
1184 * returned. Otherwise true is returned.
1185 * XXX This function should also check if user has a valid shell
1186 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001187static int
Damien Miller95def091999-11-25 00:26:21 +11001188allowed_user(struct passwd * pw)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001189{
Damien Miller95def091999-11-25 00:26:21 +11001190 struct group *grp;
1191 int i;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001192
Damien Miller95def091999-11-25 00:26:21 +11001193 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1194 if (!pw)
1195 return 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001196
Damien Miller95def091999-11-25 00:26:21 +11001197 /* XXX Should check for valid login shell */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001198
Damien Miller95def091999-11-25 00:26:21 +11001199 /* Return false if user is listed in DenyUsers */
1200 if (options.num_deny_users > 0) {
1201 if (!pw->pw_name)
1202 return 0;
1203 for (i = 0; i < options.num_deny_users; i++)
1204 if (match_pattern(pw->pw_name, options.deny_users[i]))
1205 return 0;
1206 }
Damien Miller5428f641999-11-25 11:54:57 +11001207 /* Return false if AllowUsers isn't empty and user isn't listed there */
Damien Miller95def091999-11-25 00:26:21 +11001208 if (options.num_allow_users > 0) {
1209 if (!pw->pw_name)
1210 return 0;
1211 for (i = 0; i < options.num_allow_users; i++)
1212 if (match_pattern(pw->pw_name, options.allow_users[i]))
1213 break;
1214 /* i < options.num_allow_users iff we break for loop */
1215 if (i >= options.num_allow_users)
1216 return 0;
1217 }
1218 /* Get the primary group name if we need it. Return false if it fails */
1219 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
1220 grp = getgrgid(pw->pw_gid);
1221 if (!grp)
1222 return 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001223
Damien Miller95def091999-11-25 00:26:21 +11001224 /* Return false if user's group is listed in DenyGroups */
1225 if (options.num_deny_groups > 0) {
1226 if (!grp->gr_name)
1227 return 0;
1228 for (i = 0; i < options.num_deny_groups; i++)
1229 if (match_pattern(grp->gr_name, options.deny_groups[i]))
1230 return 0;
1231 }
Damien Miller5428f641999-11-25 11:54:57 +11001232 /*
1233 * Return false if AllowGroups isn't empty and user's group
1234 * isn't listed there
1235 */
Damien Miller95def091999-11-25 00:26:21 +11001236 if (options.num_allow_groups > 0) {
1237 if (!grp->gr_name)
1238 return 0;
1239 for (i = 0; i < options.num_allow_groups; i++)
1240 if (match_pattern(grp->gr_name, options.allow_groups[i]))
1241 break;
1242 /* i < options.num_allow_groups iff we break for
1243 loop */
1244 if (i >= options.num_allow_groups)
1245 return 0;
1246 }
1247 }
1248 /* We found no reason not to let this user try to log on... */
1249 return 1;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001250}
1251
Damien Miller95def091999-11-25 00:26:21 +11001252/*
1253 * Performs authentication of an incoming connection. Session key has already
1254 * been exchanged and encryption is enabled. User is the user name to log
1255 * in as (received from the client).
1256 */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001257void
Damien Miller2ccf6611999-11-15 15:25:10 +11001258do_authentication(char *user)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001259{
Damien Miller95def091999-11-25 00:26:21 +11001260 struct passwd *pw, pwcopy;
Damien Miller2ccf6611999-11-15 15:25:10 +11001261
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001262#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11001263 /* If machine has AFS, set process authentication group. */
1264 if (k_hasafs()) {
1265 k_setpag();
1266 k_unlog();
1267 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001268#endif /* AFS */
Damien Miller95def091999-11-25 00:26:21 +11001269
1270 /* Verify that the user is a valid user. */
1271 pw = getpwnam(user);
1272 if (!pw || !allowed_user(pw))
1273 do_fake_authloop(user);
1274
1275 /* Take a copy of the returned structure. */
1276 memset(&pwcopy, 0, sizeof(pwcopy));
1277 pwcopy.pw_name = xstrdup(pw->pw_name);
1278 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1279 pwcopy.pw_uid = pw->pw_uid;
1280 pwcopy.pw_gid = pw->pw_gid;
1281 pwcopy.pw_dir = xstrdup(pw->pw_dir);
1282 pwcopy.pw_shell = xstrdup(pw->pw_shell);
1283 pw = &pwcopy;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001284
Damien Miller06230761999-10-28 14:03:14 +10001285#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001286 {
1287 int pam_retval;
Damien Miller2ccf6611999-11-15 15:25:10 +11001288
Damien Miller95def091999-11-25 00:26:21 +11001289 debug("Starting up PAM with username \"%.200s\"", pw->pw_name);
Damien Miller2ccf6611999-11-15 15:25:10 +11001290
Damien Miller95def091999-11-25 00:26:21 +11001291 pam_retval = pam_start("sshd", pw->pw_name, &conv, (pam_handle_t**)&pamh);
1292 if (pam_retval != PAM_SUCCESS)
1293 fatal("PAM initialisation failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
1294
1295 fatal_add_cleanup(&pam_cleanup_proc, NULL);
1296 }
Damien Miller06230761999-10-28 14:03:14 +10001297#endif
Damien Miller3d112ef1999-10-28 13:20:30 +10001298
Damien Miller5428f641999-11-25 11:54:57 +11001299 /*
1300 * If we are not running as root, the user must have the same uid as
1301 * the server.
1302 */
Damien Miller95def091999-11-25 00:26:21 +11001303 if (getuid() != 0 && pw->pw_uid != getuid())
1304 packet_disconnect("Cannot change user when server not running as root.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001305
Damien Miller95def091999-11-25 00:26:21 +11001306 debug("Attempting authentication for %.100s.", user);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001307
Damien Miller95def091999-11-25 00:26:21 +11001308 /* If the user has no password, accept authentication immediately. */
1309 if (options.password_authentication &&
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001310#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11001311 (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001312#endif /* KRB4 */
Damien Miller2e1b0821999-12-25 10:11:29 +11001313#ifdef HAVE_LIBPAM
1314 do_pam_auth(pw->pw_name, "")) {
1315#else /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001316 auth_password(pw, "")) {
Damien Miller2e1b0821999-12-25 10:11:29 +11001317#endif /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001318 /* Authentication with empty password succeeded. */
1319 log("Login for user %s from %.100s, accepted without authentication.",
1320 pw->pw_name, get_remote_ipaddr());
1321 } else {
1322 /* Loop until the user has been authenticated or the
1323 connection is closed, do_authloop() returns only if
1324 authentication is successfull */
1325 do_authloop(pw);
1326 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001327
Damien Miller95def091999-11-25 00:26:21 +11001328 /* Check if the user is logging in as root and root logins are disallowed. */
1329 if (pw->pw_uid == 0 && !options.permit_root_login) {
1330 if (forced_command)
1331 log("Root login accepted for forced command.");
1332 else
1333 packet_disconnect("ROOT LOGIN REFUSED FROM %.200s",
1334 get_canonical_hostname());
1335 }
1336 /* The user has been authenticated and accepted. */
1337 packet_start(SSH_SMSG_SUCCESS);
1338 packet_send();
1339 packet_write_wait();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001340
Damien Miller95def091999-11-25 00:26:21 +11001341 /* Perform session preparation. */
1342 do_authenticated(pw);
Damien Miller2ccf6611999-11-15 15:25:10 +11001343}
1344
Damien Miller95def091999-11-25 00:26:21 +11001345#define AUTH_FAIL_MAX 6
1346#define AUTH_FAIL_LOG (AUTH_FAIL_MAX/2)
1347#define AUTH_FAIL_MSG "Too many authentication failures for %.100s"
Damien Miller2ccf6611999-11-15 15:25:10 +11001348
Damien Miller95def091999-11-25 00:26:21 +11001349/*
1350 * read packets and try to authenticate local user *pw.
1351 * return if authentication is successfull
1352 */
Damien Miller2ccf6611999-11-15 15:25:10 +11001353void
Damien Miller95def091999-11-25 00:26:21 +11001354do_authloop(struct passwd * pw)
Damien Miller2ccf6611999-11-15 15:25:10 +11001355{
Damien Miller95def091999-11-25 00:26:21 +11001356 int attempt = 0;
1357 unsigned int bits;
1358 BIGNUM *client_host_key_e, *client_host_key_n;
1359 BIGNUM *n;
1360 char *client_user = NULL, *password = NULL;
1361 char user[1024];
1362 int plen, dlen, nlen, ulen, elen;
1363 int type = 0;
1364 void (*authlog) (const char *fmt,...) = verbose;
Damien Miller3bd49ec1999-11-15 15:40:55 +11001365#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001366 int pam_retval;
Damien Miller3bd49ec1999-11-15 15:40:55 +11001367#endif /* HAVE_LIBPAM */
Damien Miller2ccf6611999-11-15 15:25:10 +11001368
Damien Miller95def091999-11-25 00:26:21 +11001369 /* Indicate that authentication is needed. */
1370 packet_start(SSH_SMSG_FAILURE);
1371 packet_send();
1372 packet_write_wait();
Damien Miller2ccf6611999-11-15 15:25:10 +11001373
Damien Miller95def091999-11-25 00:26:21 +11001374 for (attempt = 1;; attempt++) {
1375 int authenticated = 0;
1376 strlcpy(user, "", sizeof user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001377
Damien Miller95def091999-11-25 00:26:21 +11001378 /* Get a packet from the client. */
1379 type = packet_read(&plen);
1380
1381 /* Process the packet. */
1382 switch (type) {
Damien Miller2ccf6611999-11-15 15:25:10 +11001383#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11001384 case SSH_CMSG_HAVE_KERBEROS_TGT:
1385 if (!options.kerberos_tgt_passing) {
1386 /* packet_get_all(); */
1387 verbose("Kerberos tgt passing disabled.");
1388 break;
1389 } else {
1390 /* Accept Kerberos tgt. */
1391 char *tgt = packet_get_string(&dlen);
1392 packet_integrity_check(plen, 4 + dlen, type);
1393 if (!auth_kerberos_tgt(pw, tgt))
1394 verbose("Kerberos tgt REFUSED for %s", pw->pw_name);
1395 xfree(tgt);
1396 }
1397 continue;
1398
1399 case SSH_CMSG_HAVE_AFS_TOKEN:
1400 if (!options.afs_token_passing || !k_hasafs()) {
1401 /* packet_get_all(); */
1402 verbose("AFS token passing disabled.");
1403 break;
1404 } else {
1405 /* Accept AFS token. */
1406 char *token_string = packet_get_string(&dlen);
1407 packet_integrity_check(plen, 4 + dlen, type);
1408 if (!auth_afs_token(pw, token_string))
1409 verbose("AFS token REFUSED for %s", pw->pw_name);
1410 xfree(token_string);
1411 }
1412 continue;
Damien Miller2ccf6611999-11-15 15:25:10 +11001413#endif /* AFS */
Damien Miller2ccf6611999-11-15 15:25:10 +11001414#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11001415 case SSH_CMSG_AUTH_KERBEROS:
1416 if (!options.kerberos_authentication) {
1417 /* packet_get_all(); */
1418 verbose("Kerberos authentication disabled.");
1419 break;
1420 } else {
1421 /* Try Kerberos v4 authentication. */
1422 KTEXT_ST auth;
1423 char *tkt_user = NULL;
1424 char *kdata = packet_get_string((unsigned int *) &auth.length);
1425 packet_integrity_check(plen, 4 + auth.length, type);
Damien Miller2ccf6611999-11-15 15:25:10 +11001426
Damien Miller95def091999-11-25 00:26:21 +11001427 if (auth.length < MAX_KTXT_LEN)
1428 memcpy(auth.dat, kdata, auth.length);
1429 xfree(kdata);
1430
1431 authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
1432
1433 if (authenticated) {
1434 snprintf(user, sizeof user, " tktuser %s", tkt_user);
1435 xfree(tkt_user);
1436 }
1437 }
1438 break;
Damien Miller2ccf6611999-11-15 15:25:10 +11001439#endif /* KRB4 */
Damien Miller2ccf6611999-11-15 15:25:10 +11001440
Damien Miller95def091999-11-25 00:26:21 +11001441 case SSH_CMSG_AUTH_RHOSTS:
1442 if (!options.rhosts_authentication) {
1443 verbose("Rhosts authentication disabled.");
1444 break;
1445 }
Damien Miller5428f641999-11-25 11:54:57 +11001446 /*
1447 * Get client user name. Note that we just have to
1448 * trust the client; this is one reason why rhosts
1449 * authentication is insecure. (Another is
1450 * IP-spoofing on a local network.)
1451 */
Damien Miller95def091999-11-25 00:26:21 +11001452 client_user = packet_get_string(&ulen);
1453 packet_integrity_check(plen, 4 + ulen, type);
1454
1455 /* Try to authenticate using /etc/hosts.equiv and
1456 .rhosts. */
1457 authenticated = auth_rhosts(pw, client_user);
1458
1459 snprintf(user, sizeof user, " ruser %s", client_user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001460#ifndef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001461 xfree(client_user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001462#endif /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001463 break;
Damien Miller7e8e8201999-11-16 13:37:16 +11001464
Damien Miller95def091999-11-25 00:26:21 +11001465 case SSH_CMSG_AUTH_RHOSTS_RSA:
1466 if (!options.rhosts_rsa_authentication) {
1467 verbose("Rhosts with RSA authentication disabled.");
1468 break;
1469 }
Damien Miller5428f641999-11-25 11:54:57 +11001470 /*
1471 * Get client user name. Note that we just have to
1472 * trust the client; root on the client machine can
1473 * claim to be any user.
1474 */
Damien Miller95def091999-11-25 00:26:21 +11001475 client_user = packet_get_string(&ulen);
1476
1477 /* Get the client host key. */
1478 client_host_key_e = BN_new();
1479 client_host_key_n = BN_new();
1480 bits = packet_get_int();
1481 packet_get_bignum(client_host_key_e, &elen);
1482 packet_get_bignum(client_host_key_n, &nlen);
1483
1484 if (bits != BN_num_bits(client_host_key_n))
1485 error("Warning: keysize mismatch for client_host_key: "
1486 "actual %d, announced %d", BN_num_bits(client_host_key_n), bits);
1487 packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1488
1489 authenticated = auth_rhosts_rsa(pw, client_user,
1490 client_host_key_e, client_host_key_n);
1491 BN_clear_free(client_host_key_e);
1492 BN_clear_free(client_host_key_n);
1493
1494 snprintf(user, sizeof user, " ruser %s", client_user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001495#ifndef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001496 xfree(client_user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001497#endif /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001498 break;
Damien Miller81428f91999-11-18 09:28:11 +11001499
Damien Miller95def091999-11-25 00:26:21 +11001500 case SSH_CMSG_AUTH_RSA:
1501 if (!options.rsa_authentication) {
1502 verbose("RSA authentication disabled.");
1503 break;
1504 }
1505 /* RSA authentication requested. */
1506 n = BN_new();
1507 packet_get_bignum(n, &nlen);
1508 packet_integrity_check(plen, nlen, type);
1509 authenticated = auth_rsa(pw, n);
1510 BN_clear_free(n);
1511 break;
1512
1513 case SSH_CMSG_AUTH_PASSWORD:
1514 if (!options.password_authentication) {
1515 verbose("Password authentication disabled.");
1516 break;
1517 }
Damien Miller5428f641999-11-25 11:54:57 +11001518 /*
1519 * Read user password. It is in plain text, but was
1520 * transmitted over the encrypted channel so it is
1521 * not visible to an outside observer.
1522 */
Damien Miller95def091999-11-25 00:26:21 +11001523 password = packet_get_string(&dlen);
1524 packet_integrity_check(plen, 4 + dlen, type);
1525
Damien Miller06230761999-10-28 14:03:14 +10001526#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001527 /* Do PAM auth with password */
Damien Miller2e1b0821999-12-25 10:11:29 +11001528 authenticated = do_pam_auth(pw->pw_name, password);
Damien Miller2ccf6611999-11-15 15:25:10 +11001529#else /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001530 /* Try authentication with the password. */
1531 authenticated = auth_password(pw, password);
Damien Miller2e1b0821999-12-25 10:11:29 +11001532#endif /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001533 memset(password, 0, strlen(password));
1534 xfree(password);
1535 break;
Damien Miller2ccf6611999-11-15 15:25:10 +11001536
Damien Miller95def091999-11-25 00:26:21 +11001537#ifdef SKEY
1538 case SSH_CMSG_AUTH_TIS:
1539 debug("rcvd SSH_CMSG_AUTH_TIS");
1540 if (options.skey_authentication == 1) {
1541 char *skeyinfo = skey_keyinfo(pw->pw_name);
1542 if (skeyinfo == NULL) {
1543 debug("generating fake skeyinfo for %.100s.", pw->pw_name);
1544 skeyinfo = skey_fake_keyinfo(pw->pw_name);
1545 }
1546 if (skeyinfo != NULL) {
Damien Miller5428f641999-11-25 11:54:57 +11001547 /* we send our s/key- in tis-challenge messages */
Damien Miller95def091999-11-25 00:26:21 +11001548 debug("sending challenge '%s'", skeyinfo);
1549 packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1550 packet_put_string(skeyinfo, strlen(skeyinfo));
1551 packet_send();
1552 packet_write_wait();
1553 continue;
1554 }
1555 }
1556 break;
1557 case SSH_CMSG_AUTH_TIS_RESPONSE:
1558 debug("rcvd SSH_CMSG_AUTH_TIS_RESPONSE");
1559 if (options.skey_authentication == 1) {
1560 char *response = packet_get_string(&dlen);
1561 debug("skey response == '%s'", response);
1562 packet_integrity_check(plen, 4 + dlen, type);
1563 authenticated = (skey_haskey(pw->pw_name) == 0 &&
1564 skey_passcheck(pw->pw_name, response) != -1);
1565 xfree(response);
1566 }
1567 break;
1568#else
1569 case SSH_CMSG_AUTH_TIS:
1570 /* TIS Authentication is unsupported */
1571 log("TIS authentication unsupported.");
1572 break;
1573#endif
1574
1575 default:
Damien Miller5428f641999-11-25 11:54:57 +11001576 /*
1577 * Any unknown messages will be ignored (and failure
1578 * returned) during authentication.
1579 */
Damien Miller95def091999-11-25 00:26:21 +11001580 log("Unknown message during authentication: type %d", type);
1581 break;
1582 }
1583
1584 /* Raise logging level */
1585 if (authenticated ||
1586 attempt == AUTH_FAIL_LOG ||
1587 type == SSH_CMSG_AUTH_PASSWORD)
1588 authlog = log;
1589
1590 authlog("%s %s for %.200s from %.200s port %d%s",
1591 authenticated ? "Accepted" : "Failed",
1592 get_authname(type),
1593 pw->pw_uid == 0 ? "ROOT" : pw->pw_name,
1594 get_remote_ipaddr(),
1595 get_remote_port(),
1596 user);
Damien Miller2ccf6611999-11-15 15:25:10 +11001597
Damien Millereabf3411999-12-07 14:56:27 +11001598#ifndef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11001599 if (authenticated)
1600 return;
1601
1602 if (attempt > AUTH_FAIL_MAX)
1603 packet_disconnect(AUTH_FAIL_MSG, pw->pw_name);
Damien Millereabf3411999-12-07 14:56:27 +11001604#else /* HAVE_LIBPAM */
1605 if (authenticated) {
Damien Millerbf1c9b21999-12-09 10:16:54 +11001606 do_pam_account(pw->pw_name, client_user);
Damien Millereabf3411999-12-07 14:56:27 +11001607
Damien Millereabf3411999-12-07 14:56:27 +11001608 if (client_user != NULL)
1609 xfree(client_user);
1610
Damien Millereabf3411999-12-07 14:56:27 +11001611 return;
1612 }
1613
1614 if (attempt > AUTH_FAIL_MAX) {
Damien Millereabf3411999-12-07 14:56:27 +11001615 if (client_user != NULL)
1616 xfree(client_user);
1617
Damien Millereabf3411999-12-07 14:56:27 +11001618 packet_disconnect(AUTH_FAIL_MSG, pw->pw_name);
1619 }
1620#endif /* HAVE_LIBPAM */
Damien Miller95def091999-11-25 00:26:21 +11001621
1622 /* Send a message indicating that the authentication attempt failed. */
1623 packet_start(SSH_SMSG_FAILURE);
1624 packet_send();
1625 packet_write_wait();
1626 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001627}
1628
Damien Miller95def091999-11-25 00:26:21 +11001629/*
1630 * The user does not exist or access is denied,
1631 * but fake indication that authentication is needed.
1632 */
Damien Miller2ccf6611999-11-15 15:25:10 +11001633void
1634do_fake_authloop(char *user)
Damien Miller3d112ef1999-10-28 13:20:30 +10001635{
Damien Miller95def091999-11-25 00:26:21 +11001636 int attempt = 0;
Damien Miller2ccf6611999-11-15 15:25:10 +11001637
Damien Miller95def091999-11-25 00:26:21 +11001638 log("Faking authloop for illegal user %.200s from %.200s port %d",
1639 user,
1640 get_remote_ipaddr(),
1641 get_remote_port());
Damien Miller3d112ef1999-10-28 13:20:30 +10001642
Damien Miller95def091999-11-25 00:26:21 +11001643 /* Indicate that authentication is needed. */
1644 packet_start(SSH_SMSG_FAILURE);
1645 packet_send();
1646 packet_write_wait();
1647
Damien Miller5428f641999-11-25 11:54:57 +11001648 /*
1649 * Keep reading packets, and always respond with a failure. This is
1650 * to avoid disclosing whether such a user really exists.
1651 */
Damien Miller95def091999-11-25 00:26:21 +11001652 for (attempt = 1;; attempt++) {
Damien Miller5428f641999-11-25 11:54:57 +11001653 /* Read a packet. This will not return if the client disconnects. */
Damien Miller95def091999-11-25 00:26:21 +11001654 int plen;
1655 int type = packet_read(&plen);
Damien Miller2ccf6611999-11-15 15:25:10 +11001656#ifdef SKEY
Damien Miller95def091999-11-25 00:26:21 +11001657 int dlen;
1658 char *password, *skeyinfo;
Damien Millera34a28b1999-12-14 10:47:15 +11001659 /* Try to send a fake s/key challenge. */
1660 if (options.skey_authentication == 1 &&
Damien Miller95def091999-11-25 00:26:21 +11001661 (skeyinfo = skey_fake_keyinfo(user)) != NULL) {
Damien Millera34a28b1999-12-14 10:47:15 +11001662 if (type == SSH_CMSG_AUTH_TIS) {
1663 packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1664 packet_put_string(skeyinfo, strlen(skeyinfo));
1665 packet_send();
1666 packet_write_wait();
1667 continue;
1668 } else if (type == SSH_CMSG_AUTH_PASSWORD &&
1669 options.password_authentication &&
1670 (password = packet_get_string(&dlen)) != NULL &&
1671 dlen == 5 &&
1672 strncasecmp(password, "s/key", 5) == 0 ) {
1673 packet_send_debug(skeyinfo);
1674 }
Damien Miller95def091999-11-25 00:26:21 +11001675 }
Damien Miller2ccf6611999-11-15 15:25:10 +11001676#endif
Damien Miller95def091999-11-25 00:26:21 +11001677 if (attempt > AUTH_FAIL_MAX)
1678 packet_disconnect(AUTH_FAIL_MSG, user);
1679
Damien Miller5428f641999-11-25 11:54:57 +11001680 /*
1681 * Send failure. This should be indistinguishable from a
1682 * failed authentication.
1683 */
Damien Miller95def091999-11-25 00:26:21 +11001684 packet_start(SSH_SMSG_FAILURE);
1685 packet_send();
1686 packet_write_wait();
1687 }
1688 /* NOTREACHED */
1689 abort();
Damien Miller3d112ef1999-10-28 13:20:30 +10001690}
1691
Damien Miller2ccf6611999-11-15 15:25:10 +11001692
Damien Miller95def091999-11-25 00:26:21 +11001693/*
1694 * Remove local Xauthority file.
1695 */
Damien Miller5ce662a1999-11-11 17:57:39 +11001696static void
1697xauthfile_cleanup_proc(void *ignore)
1698{
Damien Miller95def091999-11-25 00:26:21 +11001699 debug("xauthfile_cleanup_proc called");
Damien Miller5ce662a1999-11-11 17:57:39 +11001700
Damien Miller95def091999-11-25 00:26:21 +11001701 if (xauthfile != NULL) {
1702 unlink(xauthfile);
1703 xfree(xauthfile);
1704 xauthfile = NULL;
1705 }
Damien Miller5ce662a1999-11-11 17:57:39 +11001706}
1707
Damien Miller95def091999-11-25 00:26:21 +11001708/*
1709 * Prepares for an interactive session. This is called after the user has
1710 * been successfully authenticated. During this message exchange, pseudo
1711 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1712 * are requested, etc.
1713 */
1714void
1715do_authenticated(struct passwd * pw)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001716{
Damien Miller95def091999-11-25 00:26:21 +11001717 int type;
1718 int compression_level = 0, enable_compression_after_reply = 0;
1719 int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1;
1720 int row, col, xpixel, ypixel, screen;
1721 char ttyname[64];
1722 char *command, *term = NULL, *display = NULL, *proto = NULL,
1723 *data = NULL;
1724 struct group *grp;
1725 gid_t tty_gid;
1726 mode_t tty_mode;
1727 int n_bytes;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001728
Damien Miller5428f641999-11-25 11:54:57 +11001729 /*
1730 * Cancel the alarm we set to limit the time taken for
1731 * authentication.
1732 */
Damien Miller95def091999-11-25 00:26:21 +11001733 alarm(0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001734
Damien Miller5428f641999-11-25 11:54:57 +11001735 /*
1736 * Inform the channel mechanism that we are the server side and that
1737 * the client may request to connect to any port at all. (The user
1738 * could do it anyway, and we wouldn\'t know what is permitted except
1739 * by the client telling us, so we can equally well trust the client
1740 * not to request anything bogus.)
1741 */
Damien Miller95def091999-11-25 00:26:21 +11001742 channel_permit_all_opens();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001743
Damien Miller5428f641999-11-25 11:54:57 +11001744 /*
1745 * We stay in this loop until the client requests to execute a shell
1746 * or a command.
1747 */
Damien Miller95def091999-11-25 00:26:21 +11001748 while (1) {
1749 int plen, dlen;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001750
Damien Miller95def091999-11-25 00:26:21 +11001751 /* Get a packet from the client. */
1752 type = packet_read(&plen);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001753
Damien Miller95def091999-11-25 00:26:21 +11001754 /* Process the packet. */
1755 switch (type) {
1756 case SSH_CMSG_REQUEST_COMPRESSION:
1757 packet_integrity_check(plen, 4, type);
1758 compression_level = packet_get_int();
1759 if (compression_level < 1 || compression_level > 9) {
1760 packet_send_debug("Received illegal compression level %d.",
1761 compression_level);
1762 goto fail;
1763 }
1764 /* Enable compression after we have responded with SUCCESS. */
1765 enable_compression_after_reply = 1;
1766 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001767
Damien Miller95def091999-11-25 00:26:21 +11001768 case SSH_CMSG_REQUEST_PTY:
1769 if (no_pty_flag) {
1770 debug("Allocating a pty not permitted for this authentication.");
1771 goto fail;
1772 }
1773 if (have_pty)
1774 packet_disconnect("Protocol error: you already have a pty.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001775
Damien Miller95def091999-11-25 00:26:21 +11001776 debug("Allocating pty.");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001777
Damien Miller95def091999-11-25 00:26:21 +11001778 /* Allocate a pty and open it. */
Damien Miller037a0dc1999-12-07 15:38:31 +11001779 if (!pty_allocate(&ptyfd, &ttyfd, ttyname,
1780 sizeof(ttyname))) {
Damien Miller95def091999-11-25 00:26:21 +11001781 error("Failed to allocate pty.");
1782 goto fail;
1783 }
1784 /* Determine the group to make the owner of the tty. */
1785 grp = getgrnam("tty");
1786 if (grp) {
1787 tty_gid = grp->gr_gid;
1788 tty_mode = S_IRUSR | S_IWUSR | S_IWGRP;
1789 } else {
1790 tty_gid = pw->pw_gid;
1791 tty_mode = S_IRUSR | S_IWUSR | S_IWGRP | S_IWOTH;
1792 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001793
Damien Miller95def091999-11-25 00:26:21 +11001794 /* Change ownership of the tty. */
1795 if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
1796 fatal("chown(%.100s, %d, %d) failed: %.100s",
1797 ttyname, pw->pw_uid, tty_gid, strerror(errno));
1798 if (chmod(ttyname, tty_mode) < 0)
1799 fatal("chmod(%.100s, 0%o) failed: %.100s",
1800 ttyname, tty_mode, strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001801
Damien Miller95def091999-11-25 00:26:21 +11001802 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
1803 term = packet_get_string(&dlen);
1804 packet_integrity_check(dlen, strlen(term), type);
1805 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
1806 /* Remaining bytes */
1807 n_bytes = plen - (4 + dlen + 4 * 4);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001808
Damien Miller95def091999-11-25 00:26:21 +11001809 if (strcmp(term, "") == 0)
1810 term = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001811
Damien Miller95def091999-11-25 00:26:21 +11001812 /* Get window size from the packet. */
1813 row = packet_get_int();
1814 col = packet_get_int();
1815 xpixel = packet_get_int();
1816 ypixel = packet_get_int();
1817 pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001818
Damien Miller95def091999-11-25 00:26:21 +11001819 /* Get tty modes from the packet. */
1820 tty_parse_modes(ttyfd, &n_bytes);
1821 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001822
Damien Miller95def091999-11-25 00:26:21 +11001823 /* Indicate that we now have a pty. */
1824 have_pty = 1;
Damien Millerbf1c9b21999-12-09 10:16:54 +11001825
1826#ifdef HAVE_LIBPAM
1827 /* do the pam_open_session since we have the pty */
1828 do_pam_session(pw->pw_name,ttyname);
1829#endif /* HAVE_LIBPAM */
1830
Damien Miller95def091999-11-25 00:26:21 +11001831 break;
1832
1833 case SSH_CMSG_X11_REQUEST_FORWARDING:
1834 if (!options.x11_forwarding) {
1835 packet_send_debug("X11 forwarding disabled in server configuration file.");
1836 goto fail;
1837 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001838#ifdef XAUTH_PATH
Damien Miller95def091999-11-25 00:26:21 +11001839 if (no_x11_forwarding_flag) {
1840 packet_send_debug("X11 forwarding not permitted for this authentication.");
1841 goto fail;
1842 }
1843 debug("Received request for X11 forwarding with auth spoofing.");
1844 if (display)
1845 packet_disconnect("Protocol error: X11 display already set.");
1846 {
1847 int proto_len, data_len;
1848 proto = packet_get_string(&proto_len);
1849 data = packet_get_string(&data_len);
1850 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
1851 }
1852 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1853 screen = packet_get_int();
1854 else
1855 screen = 0;
Damien Millera34a28b1999-12-14 10:47:15 +11001856 display = x11_create_display_inet(screen, options.x11_display_offset);
Damien Miller95def091999-11-25 00:26:21 +11001857 if (!display)
1858 goto fail;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001859
Damien Miller95def091999-11-25 00:26:21 +11001860 /* Setup to always have a local .Xauthority. */
1861 xauthfile = xmalloc(MAXPATHLEN);
1862 snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX");
1863
1864 if ((xauthfd = mkstemp(xauthfile)) != -1) {
1865 fchown(xauthfd, pw->pw_uid, pw->pw_gid);
1866 close(xauthfd);
1867 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
1868 } else {
1869 xfree(xauthfile);
1870 xauthfile = NULL;
1871 }
1872 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001873#else /* XAUTH_PATH */
Damien Miller95def091999-11-25 00:26:21 +11001874 packet_send_debug("No xauth program; cannot forward with spoofing.");
1875 goto fail;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001876#endif /* XAUTH_PATH */
1877
Damien Miller95def091999-11-25 00:26:21 +11001878 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1879 if (no_agent_forwarding_flag) {
1880 debug("Authentication agent forwarding not permitted for this authentication.");
1881 goto fail;
1882 }
1883 debug("Received authentication agent forwarding request.");
1884 auth_input_request_forwarding(pw);
1885 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001886
Damien Miller95def091999-11-25 00:26:21 +11001887 case SSH_CMSG_PORT_FORWARD_REQUEST:
1888 if (no_port_forwarding_flag) {
1889 debug("Port forwarding not permitted for this authentication.");
1890 goto fail;
1891 }
1892 debug("Received TCP/IP port forwarding request.");
1893 channel_input_port_forward_request(pw->pw_uid == 0);
1894 break;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001895
Damien Miller95def091999-11-25 00:26:21 +11001896 case SSH_CMSG_MAX_PACKET_SIZE:
1897 if (packet_set_maxsize(packet_get_int()) < 0)
1898 goto fail;
1899 break;
Damien Miller6162d121999-11-21 13:23:52 +11001900
Damien Miller95def091999-11-25 00:26:21 +11001901 case SSH_CMSG_EXEC_SHELL:
1902 /* Set interactive/non-interactive mode. */
1903 packet_set_interactive(have_pty || display != NULL,
1904 options.keepalives);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001905
Damien Miller95def091999-11-25 00:26:21 +11001906 if (forced_command != NULL)
1907 goto do_forced_command;
1908 debug("Forking shell.");
1909 packet_integrity_check(plen, 0, type);
1910 if (have_pty)
1911 do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1912 else
1913 do_exec_no_pty(NULL, pw, display, proto, data);
1914 return;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001915
Damien Miller95def091999-11-25 00:26:21 +11001916 case SSH_CMSG_EXEC_CMD:
1917 /* Set interactive/non-interactive mode. */
1918 packet_set_interactive(have_pty || display != NULL,
1919 options.keepalives);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001920
Damien Miller95def091999-11-25 00:26:21 +11001921 if (forced_command != NULL)
1922 goto do_forced_command;
1923 /* Get command from the packet. */
1924 {
1925 int dlen;
1926 command = packet_get_string(&dlen);
1927 debug("Executing command '%.500s'", command);
1928 packet_integrity_check(plen, 4 + dlen, type);
1929 }
1930 if (have_pty)
1931 do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1932 else
1933 do_exec_no_pty(command, pw, display, proto, data);
1934 xfree(command);
1935 return;
1936
1937 default:
Damien Miller5428f641999-11-25 11:54:57 +11001938 /*
1939 * Any unknown messages in this phase are ignored,
1940 * and a failure message is returned.
1941 */
Damien Miller95def091999-11-25 00:26:21 +11001942 log("Unknown packet type received after authentication: %d", type);
1943 goto fail;
1944 }
1945
1946 /* The request was successfully processed. */
1947 packet_start(SSH_SMSG_SUCCESS);
1948 packet_send();
1949 packet_write_wait();
1950
1951 /* Enable compression now that we have replied if appropriate. */
1952 if (enable_compression_after_reply) {
1953 enable_compression_after_reply = 0;
1954 packet_start_compression(compression_level);
1955 }
1956 continue;
1957
1958fail:
1959 /* The request failed. */
1960 packet_start(SSH_SMSG_FAILURE);
1961 packet_send();
1962 packet_write_wait();
1963 continue;
1964
1965do_forced_command:
Damien Miller5428f641999-11-25 11:54:57 +11001966 /*
1967 * There is a forced command specified for this login.
1968 * Execute it.
1969 */
Damien Miller95def091999-11-25 00:26:21 +11001970 debug("Executing forced command: %.900s", forced_command);
1971 if (have_pty)
1972 do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1973 else
1974 do_exec_no_pty(forced_command, pw, display, proto, data);
1975 return;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001976 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001977}
1978
Damien Miller95def091999-11-25 00:26:21 +11001979/*
1980 * This is called to fork and execute a command when we have no tty. This
1981 * will call do_child from the child, and server_loop from the parent after
1982 * setting up file descriptors and such.
1983 */
1984void
1985do_exec_no_pty(const char *command, struct passwd * pw,
1986 const char *display, const char *auth_proto,
1987 const char *auth_data)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10001988{
Damien Miller95def091999-11-25 00:26:21 +11001989 int pid;
1990
1991#ifdef USE_PIPES
1992 int pin[2], pout[2], perr[2];
1993 /* Allocate pipes for communicating with the program. */
1994 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1995 packet_disconnect("Could not create pipes: %.100s",
1996 strerror(errno));
1997#else /* USE_PIPES */
1998 int inout[2], err[2];
1999 /* Uses socket pairs to communicate with the program. */
2000 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
2001 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
2002 packet_disconnect("Could not create socket pairs: %.100s",
2003 strerror(errno));
2004#endif /* USE_PIPES */
2005
2006 setproctitle("%s@notty", pw->pw_name);
2007
2008 /* Fork the child. */
2009 if ((pid = fork()) == 0) {
2010 /* Child. Reinitialize the log since the pid has changed. */
2011 log_init(av0, options.log_level, options.log_facility, log_stderr);
2012
Damien Miller5428f641999-11-25 11:54:57 +11002013 /*
2014 * Create a new session and process group since the 4.4BSD
2015 * setlogin() affects the entire process group.
2016 */
Damien Miller95def091999-11-25 00:26:21 +11002017 if (setsid() < 0)
2018 error("setsid failed: %.100s", strerror(errno));
2019
2020#ifdef USE_PIPES
Damien Miller5428f641999-11-25 11:54:57 +11002021 /*
2022 * Redirect stdin. We close the parent side of the socket
2023 * pair, and make the child side the standard input.
2024 */
Damien Miller95def091999-11-25 00:26:21 +11002025 close(pin[1]);
2026 if (dup2(pin[0], 0) < 0)
2027 perror("dup2 stdin");
2028 close(pin[0]);
2029
2030 /* Redirect stdout. */
2031 close(pout[0]);
2032 if (dup2(pout[1], 1) < 0)
2033 perror("dup2 stdout");
2034 close(pout[1]);
2035
2036 /* Redirect stderr. */
2037 close(perr[0]);
2038 if (dup2(perr[1], 2) < 0)
2039 perror("dup2 stderr");
2040 close(perr[1]);
2041#else /* USE_PIPES */
Damien Miller5428f641999-11-25 11:54:57 +11002042 /*
2043 * Redirect stdin, stdout, and stderr. Stdin and stdout will
2044 * use the same socket, as some programs (particularly rdist)
2045 * seem to depend on it.
2046 */
Damien Miller95def091999-11-25 00:26:21 +11002047 close(inout[1]);
2048 close(err[1]);
2049 if (dup2(inout[0], 0) < 0) /* stdin */
2050 perror("dup2 stdin");
2051 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
2052 perror("dup2 stdout");
2053 if (dup2(err[0], 2) < 0) /* stderr */
2054 perror("dup2 stderr");
2055#endif /* USE_PIPES */
2056
2057 /* Do processing for the child (exec command etc). */
2058 do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
2059 /* NOTREACHED */
2060 }
2061 if (pid < 0)
2062 packet_disconnect("fork failed: %.100s", strerror(errno));
2063#ifdef USE_PIPES
2064 /* We are the parent. Close the child sides of the pipes. */
2065 close(pin[0]);
2066 close(pout[1]);
2067 close(perr[1]);
2068
2069 /* Enter the interactive session. */
2070 server_loop(pid, pin[1], pout[0], perr[0]);
2071 /* server_loop has closed pin[1], pout[1], and perr[1]. */
2072#else /* USE_PIPES */
2073 /* We are the parent. Close the child sides of the socket pairs. */
2074 close(inout[0]);
2075 close(err[0]);
2076
Damien Miller5428f641999-11-25 11:54:57 +11002077 /*
2078 * Enter the interactive session. Note: server_loop must be able to
2079 * handle the case that fdin and fdout are the same.
2080 */
Damien Miller95def091999-11-25 00:26:21 +11002081 server_loop(pid, inout[1], inout[1], err[1]);
2082 /* server_loop has closed inout[1] and err[1]. */
2083#endif /* USE_PIPES */
2084}
2085
2086struct pty_cleanup_context {
2087 const char *ttyname;
2088 int pid;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002089};
2090
Damien Miller95def091999-11-25 00:26:21 +11002091/*
2092 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
2093 * dropped connection).
2094 */
2095void
2096pty_cleanup_proc(void *context)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002097{
Damien Miller95def091999-11-25 00:26:21 +11002098 struct pty_cleanup_context *cu = context;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002099
Damien Miller95def091999-11-25 00:26:21 +11002100 debug("pty_cleanup_proc called");
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002101
Damien Miller95def091999-11-25 00:26:21 +11002102 /* Record that the user has logged out. */
2103 record_logout(cu->pid, cu->ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002104
Damien Miller95def091999-11-25 00:26:21 +11002105 /* Release the pseudo-tty. */
2106 pty_release(cu->ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002107}
2108
Damien Miller95def091999-11-25 00:26:21 +11002109/*
2110 * This is called to fork and execute a command when we have a tty. This
2111 * will call do_child from the child, and server_loop from the parent after
2112 * setting up file descriptors, controlling tty, updating wtmp, utmp,
2113 * lastlog, and other such operations.
2114 */
2115void
2116do_exec_pty(const char *command, int ptyfd, int ttyfd,
2117 const char *ttyname, struct passwd * pw, const char *term,
2118 const char *display, const char *auth_proto,
2119 const char *auth_data)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002120{
Damien Miller95def091999-11-25 00:26:21 +11002121 int pid, fdout;
2122 const char *hostname;
2123 time_t last_login_time;
2124 char buf[100], *time_string;
2125 FILE *f;
2126 char line[256];
2127 struct stat st;
2128 int quiet_login;
2129 struct sockaddr_in from;
2130 int fromlen;
2131 struct pty_cleanup_context cleanup_context;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002132
Damien Miller95def091999-11-25 00:26:21 +11002133 /* Get remote host name. */
2134 hostname = get_canonical_hostname();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002135
Damien Miller5428f641999-11-25 11:54:57 +11002136 /*
2137 * Get the time when the user last logged in. Buf will be set to
2138 * contain the hostname the last login was from.
2139 */
Damien Miller95def091999-11-25 00:26:21 +11002140 if (!options.use_login) {
2141 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
2142 buf, sizeof(buf));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002143 }
Damien Miller95def091999-11-25 00:26:21 +11002144 setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002145
Damien Miller95def091999-11-25 00:26:21 +11002146 /* Fork the child. */
2147 if ((pid = fork()) == 0) {
2148 pid = getpid();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002149
Damien Miller95def091999-11-25 00:26:21 +11002150 /* Child. Reinitialize the log because the pid has
2151 changed. */
2152 log_init(av0, options.log_level, options.log_facility, log_stderr);
2153
2154 /* Close the master side of the pseudo tty. */
2155 close(ptyfd);
2156
2157 /* Make the pseudo tty our controlling tty. */
2158 pty_make_controlling_tty(&ttyfd, ttyname);
2159
2160 /* Redirect stdin from the pseudo tty. */
2161 if (dup2(ttyfd, fileno(stdin)) < 0)
2162 error("dup2 stdin failed: %.100s", strerror(errno));
2163
2164 /* Redirect stdout to the pseudo tty. */
2165 if (dup2(ttyfd, fileno(stdout)) < 0)
2166 error("dup2 stdin failed: %.100s", strerror(errno));
2167
2168 /* Redirect stderr to the pseudo tty. */
2169 if (dup2(ttyfd, fileno(stderr)) < 0)
2170 error("dup2 stdin failed: %.100s", strerror(errno));
2171
2172 /* Close the extra descriptor for the pseudo tty. */
2173 close(ttyfd);
2174
Damien Miller5428f641999-11-25 11:54:57 +11002175 /*
2176 * Get IP address of client. This is needed because we want
2177 * to record where the user logged in from. If the
2178 * connection is not a socket, let the ip address be 0.0.0.0.
2179 */
Damien Miller95def091999-11-25 00:26:21 +11002180 memset(&from, 0, sizeof(from));
2181 if (packet_get_connection_in() == packet_get_connection_out()) {
2182 fromlen = sizeof(from);
2183 if (getpeername(packet_get_connection_in(),
2184 (struct sockaddr *) & from, &fromlen) < 0) {
2185 debug("getpeername: %.100s", strerror(errno));
2186 fatal_cleanup();
2187 }
2188 }
2189 /* Record that there was a login on that terminal. */
2190 record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
2191 &from);
2192
2193 /* Check if .hushlogin exists. */
2194 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2195 quiet_login = stat(line, &st) >= 0;
Damien Miller356a0b01999-11-08 15:30:59 +11002196
2197#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11002198 /* output the results of the pamconv() */
2199 if (!quiet_login && pamconv_msg != NULL)
2200 fprintf(stderr, pamconv_msg);
Damien Miller356a0b01999-11-08 15:30:59 +11002201#endif
Damien Miller95def091999-11-25 00:26:21 +11002202
Damien Miller5428f641999-11-25 11:54:57 +11002203 /*
2204 * If the user has logged in before, display the time of last
2205 * login. However, don't display anything extra if a command
2206 * has been specified (so that ssh can be used to execute
2207 * commands on a remote machine without users knowing they
2208 * are going to another machine). Login(1) will do this for
2209 * us as well, so check if login(1) is used
2210 */
Damien Miller95def091999-11-25 00:26:21 +11002211 if (command == NULL && last_login_time != 0 && !quiet_login &&
2212 !options.use_login) {
2213 /* Convert the date to a string. */
2214 time_string = ctime(&last_login_time);
2215 /* Remove the trailing newline. */
2216 if (strchr(time_string, '\n'))
2217 *strchr(time_string, '\n') = 0;
2218 /* Display the last login time. Host if displayed
2219 if known. */
2220 if (strcmp(buf, "") == 0)
2221 printf("Last login: %s\r\n", time_string);
2222 else
2223 printf("Last login: %s from %s\r\n", time_string, buf);
2224 }
Damien Miller5428f641999-11-25 11:54:57 +11002225 /*
2226 * Print /etc/motd unless a command was specified or printing
2227 * it was disabled in server options or login(1) will be
2228 * used. Note that some machines appear to print it in
2229 * /etc/profile or similar.
2230 */
Damien Miller95def091999-11-25 00:26:21 +11002231 if (command == NULL && options.print_motd && !quiet_login &&
2232 !options.use_login) {
2233 /* Print /etc/motd if it exists. */
2234 f = fopen("/etc/motd", "r");
2235 if (f) {
2236 while (fgets(line, sizeof(line), f))
2237 fputs(line, stdout);
2238 fclose(f);
2239 }
2240 }
2241 /* Do common processing for the child, such as execing the command. */
2242 do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
2243 /* NOTREACHED */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002244 }
Damien Miller95def091999-11-25 00:26:21 +11002245 if (pid < 0)
2246 packet_disconnect("fork failed: %.100s", strerror(errno));
2247 /* Parent. Close the slave side of the pseudo tty. */
2248 close(ttyfd);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002249
Damien Miller5428f641999-11-25 11:54:57 +11002250 /*
2251 * Create another descriptor of the pty master side for use as the
2252 * standard input. We could use the original descriptor, but this
2253 * simplifies code in server_loop. The descriptor is bidirectional.
2254 */
Damien Miller95def091999-11-25 00:26:21 +11002255 fdout = dup(ptyfd);
2256 if (fdout < 0)
2257 packet_disconnect("dup failed: %.100s", strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002258
Damien Miller5428f641999-11-25 11:54:57 +11002259 /*
2260 * Add a cleanup function to clear the utmp entry and record logout
2261 * time in case we call fatal() (e.g., the connection gets closed).
2262 */
Damien Miller95def091999-11-25 00:26:21 +11002263 cleanup_context.pid = pid;
2264 cleanup_context.ttyname = ttyname;
2265 fatal_add_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002266
Damien Miller95def091999-11-25 00:26:21 +11002267 /* Enter interactive session. */
2268 server_loop(pid, ptyfd, fdout, -1);
2269 /* server_loop has not closed ptyfd and fdout. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002270
Damien Miller95def091999-11-25 00:26:21 +11002271 /* Cancel the cleanup function. */
2272 fatal_remove_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002273
Damien Miller95def091999-11-25 00:26:21 +11002274 /* Record that the user has logged out. */
2275 record_logout(pid, ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002276
Damien Miller95def091999-11-25 00:26:21 +11002277 /* Release the pseudo-tty. */
2278 pty_release(ttyname);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002279
Damien Miller5428f641999-11-25 11:54:57 +11002280 /*
2281 * Close the server side of the socket pairs. We must do this after
2282 * the pty cleanup, so that another process doesn't get this pty
2283 * while we're still cleaning up.
2284 */
Damien Miller95def091999-11-25 00:26:21 +11002285 close(ptyfd);
2286 close(fdout);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002287}
2288
Damien Miller95def091999-11-25 00:26:21 +11002289/*
2290 * Sets the value of the given variable in the environment. If the variable
2291 * already exists, its value is overriden.
2292 */
2293void
2294child_set_env(char ***envp, unsigned int *envsizep, const char *name,
2295 const char *value)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002296{
Damien Miller95def091999-11-25 00:26:21 +11002297 unsigned int i, namelen;
2298 char **env;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002299
Damien Miller5428f641999-11-25 11:54:57 +11002300 /*
2301 * Find the slot where the value should be stored. If the variable
2302 * already exists, we reuse the slot; otherwise we append a new slot
2303 * at the end of the array, expanding if necessary.
2304 */
Damien Miller95def091999-11-25 00:26:21 +11002305 env = *envp;
2306 namelen = strlen(name);
2307 for (i = 0; env[i]; i++)
2308 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2309 break;
2310 if (env[i]) {
Damien Miller5428f641999-11-25 11:54:57 +11002311 /* Reuse the slot. */
Damien Miller95def091999-11-25 00:26:21 +11002312 xfree(env[i]);
2313 } else {
Damien Miller5428f641999-11-25 11:54:57 +11002314 /* New variable. Expand if necessary. */
Damien Miller95def091999-11-25 00:26:21 +11002315 if (i >= (*envsizep) - 1) {
2316 (*envsizep) += 50;
2317 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2318 }
2319 /* Need to set the NULL pointer at end of array beyond the new slot. */
2320 env[i + 1] = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002321 }
2322
Damien Miller95def091999-11-25 00:26:21 +11002323 /* Allocate space and format the variable in the appropriate slot. */
2324 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2325 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002326}
2327
Damien Miller95def091999-11-25 00:26:21 +11002328/*
2329 * Reads environment variables from the given file and adds/overrides them
2330 * into the environment. If the file does not exist, this does nothing.
2331 * Otherwise, it must consist of empty lines, comments (line starts with '#')
2332 * and assignments of the form name=value. No other forms are allowed.
2333 */
2334void
2335read_environment_file(char ***env, unsigned int *envsize,
2336 const char *filename)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002337{
Damien Miller95def091999-11-25 00:26:21 +11002338 FILE *f;
2339 char buf[4096];
2340 char *cp, *value;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002341
Damien Miller95def091999-11-25 00:26:21 +11002342 f = fopen(filename, "r");
2343 if (!f)
2344 return;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002345
Damien Miller95def091999-11-25 00:26:21 +11002346 while (fgets(buf, sizeof(buf), f)) {
Damien Miller5428f641999-11-25 11:54:57 +11002347 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++)
2348 ;
Damien Miller95def091999-11-25 00:26:21 +11002349 if (!*cp || *cp == '#' || *cp == '\n')
2350 continue;
Damien Miller95def091999-11-25 00:26:21 +11002351 if (strchr(cp, '\n'))
2352 *strchr(cp, '\n') = '\0';
Damien Miller95def091999-11-25 00:26:21 +11002353 value = strchr(cp, '=');
2354 if (value == NULL) {
2355 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
2356 continue;
2357 }
Damien Miller5428f641999-11-25 11:54:57 +11002358 /* Replace the equals sign by nul, and advance value to the value string. */
Damien Miller95def091999-11-25 00:26:21 +11002359 *value = '\0';
2360 value++;
Damien Miller95def091999-11-25 00:26:21 +11002361 child_set_env(env, envsize, cp, value);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002362 }
Damien Miller95def091999-11-25 00:26:21 +11002363 fclose(f);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002364}
2365
Damien Miller95def091999-11-25 00:26:21 +11002366/*
2367 * Performs common processing for the child, such as setting up the
2368 * environment, closing extra file descriptors, setting the user and group
2369 * ids, and executing the command or shell.
2370 */
2371void
2372do_child(const char *command, struct passwd * pw, const char *term,
2373 const char *display, const char *auth_proto,
2374 const char *auth_data, const char *ttyname)
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002375{
Damien Miller95def091999-11-25 00:26:21 +11002376 const char *shell, *cp = NULL;
2377 char buf[256];
2378 FILE *f;
2379 unsigned int envsize, i;
2380 char **env;
2381 extern char **environ;
2382 struct stat st;
2383 char *argv[10];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002384
Damien Miller356a0b01999-11-08 15:30:59 +11002385#ifndef HAVE_LIBPAM /* pam_nologin handles this */
Damien Miller95def091999-11-25 00:26:21 +11002386 /* Check /etc/nologin. */
2387 f = fopen("/etc/nologin", "r");
2388 if (f) {
2389 /* /etc/nologin exists. Print its contents and exit. */
2390 while (fgets(buf, sizeof(buf), f))
2391 fputs(buf, stderr);
2392 fclose(f);
2393 if (pw->pw_uid != 0)
2394 exit(254);
2395 }
Damien Miller776af5d1999-11-12 08:49:09 +11002396#endif /* HAVE_LIBPAM */
2397
2398#ifdef HAVE_SETLOGIN
Damien Miller95def091999-11-25 00:26:21 +11002399 /* Set login name in the kernel. */
2400 if (setlogin(pw->pw_name) < 0)
2401 error("setlogin failed: %s", strerror(errno));
Damien Miller776af5d1999-11-12 08:49:09 +11002402#endif /* HAVE_SETLOGIN */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002403
Damien Miller95def091999-11-25 00:26:21 +11002404 /* Set uid, gid, and groups. */
2405 /* Login(1) does this as well, and it needs uid 0 for the "-h"
2406 switch, so we let login(1) to this for us. */
2407 if (!options.use_login) {
2408 if (getuid() == 0 || geteuid() == 0) {
2409 if (setgid(pw->pw_gid) < 0) {
2410 perror("setgid");
2411 exit(1);
2412 }
2413 /* Initialize the group list. */
2414 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
2415 perror("initgroups");
2416 exit(1);
2417 }
2418 endgrent();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002419
Damien Miller95def091999-11-25 00:26:21 +11002420 /* Permanently switch to the desired uid. */
2421 permanently_set_uid(pw->pw_uid);
2422 }
2423 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
2424 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
2425 }
Damien Miller5428f641999-11-25 11:54:57 +11002426 /*
2427 * Get the shell from the password data. An empty shell field is
2428 * legal, and means /bin/sh.
2429 */
Damien Miller95def091999-11-25 00:26:21 +11002430 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002431
2432#ifdef AFS
Damien Miller95def091999-11-25 00:26:21 +11002433 /* Try to get AFS tokens for the local cell. */
2434 if (k_hasafs()) {
2435 char cell[64];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002436
Damien Miller95def091999-11-25 00:26:21 +11002437 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
2438 krb_afslog(cell, 0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002439
Damien Miller95def091999-11-25 00:26:21 +11002440 krb_afslog(0, 0);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002441 }
Damien Miller95def091999-11-25 00:26:21 +11002442#endif /* AFS */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002443
Damien Miller5428f641999-11-25 11:54:57 +11002444 /* Initialize the environment. */
Damien Miller95def091999-11-25 00:26:21 +11002445 envsize = 100;
2446 env = xmalloc(envsize * sizeof(char *));
2447 env[0] = NULL;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002448
Damien Miller95def091999-11-25 00:26:21 +11002449 if (!options.use_login) {
2450 /* Set basic environment. */
2451 child_set_env(&env, &envsize, "USER", pw->pw_name);
2452 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
2453 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2454 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002455
Damien Miller95def091999-11-25 00:26:21 +11002456 snprintf(buf, sizeof buf, "%.200s/%.50s",
2457 _PATH_MAILDIR, pw->pw_name);
2458 child_set_env(&env, &envsize, "MAIL", buf);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002459
Damien Miller95def091999-11-25 00:26:21 +11002460 /* Normal systems set SHELL by default. */
2461 child_set_env(&env, &envsize, "SHELL", shell);
2462 }
Damien Miller95def091999-11-25 00:26:21 +11002463 if (getenv("TZ"))
2464 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
2465
2466 /* Set custom environment options from RSA authentication. */
2467 while (custom_environment) {
2468 struct envstring *ce = custom_environment;
2469 char *s = ce->s;
2470 int i;
2471 for (i = 0; s[i] != '=' && s[i]; i++);
2472 if (s[i] == '=') {
2473 s[i] = 0;
2474 child_set_env(&env, &envsize, s, s + i + 1);
2475 }
2476 custom_environment = ce->next;
2477 xfree(ce->s);
2478 xfree(ce);
2479 }
2480
Damien Miller95def091999-11-25 00:26:21 +11002481 snprintf(buf, sizeof buf, "%.50s %d %d",
2482 get_remote_ipaddr(), get_remote_port(), options.port);
2483 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2484
Damien Miller95def091999-11-25 00:26:21 +11002485 if (ttyname)
2486 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
Damien Miller95def091999-11-25 00:26:21 +11002487 if (term)
2488 child_set_env(&env, &envsize, "TERM", term);
Damien Miller95def091999-11-25 00:26:21 +11002489 if (display)
2490 child_set_env(&env, &envsize, "DISPLAY", display);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002491
2492#ifdef KRB4
Damien Miller95def091999-11-25 00:26:21 +11002493 {
2494 extern char *ticket;
2495
2496 if (ticket)
2497 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2498 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002499#endif /* KRB4 */
2500
Damien Miller94388161999-10-29 09:57:31 +10002501#ifdef HAVE_LIBPAM
Damien Miller95def091999-11-25 00:26:21 +11002502 /* Pull in any environment variables that may have been set by PAM. */
2503 {
2504 char *equals, var_name[512], var_val[512];
2505 char **pam_env = pam_getenvlist((pam_handle_t *)pamh);
2506 int i;
2507 for(i = 0; pam_env && pam_env[i]; i++) {
2508 equals = strstr(pam_env[i], "=");
2509 if ((strlen(pam_env[i]) < (sizeof(var_name) - 1)) && (equals != NULL))
2510 {
Damien Millerdc33fc31999-12-04 20:24:48 +11002511 debug("PAM environment: %s=%s", var_name, var_val);
Damien Miller95def091999-11-25 00:26:21 +11002512 memset(var_name, '\0', sizeof(var_name));
2513 memset(var_val, '\0', sizeof(var_val));
2514 strncpy(var_name, pam_env[i], equals - pam_env[i]);
2515 strcpy(var_val, equals + 1);
2516 child_set_env(&env, &envsize, var_name, var_val);
2517 }
2518 }
2519 }
Damien Miller94388161999-10-29 09:57:31 +10002520#endif /* HAVE_LIBPAM */
2521
Damien Miller95def091999-11-25 00:26:21 +11002522 if (xauthfile)
2523 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002524
Damien Miller95def091999-11-25 00:26:21 +11002525 if (auth_get_socket_name() != NULL)
2526 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
2527 auth_get_socket_name());
Damien Miller776af5d1999-11-12 08:49:09 +11002528
Damien Miller5428f641999-11-25 11:54:57 +11002529 /* read $HOME/.ssh/environment. */
Damien Miller95def091999-11-25 00:26:21 +11002530 if (!options.use_login) {
2531 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
2532 read_environment_file(&env, &envsize, buf);
2533 }
Damien Miller95def091999-11-25 00:26:21 +11002534 if (debug_flag) {
Damien Miller5428f641999-11-25 11:54:57 +11002535 /* dump the environment */
Damien Miller95def091999-11-25 00:26:21 +11002536 fprintf(stderr, "Environment:\n");
2537 for (i = 0; env[i]; i++)
2538 fprintf(stderr, " %.200s\n", env[i]);
2539 }
Damien Miller5428f641999-11-25 11:54:57 +11002540 /*
2541 * Close the connection descriptors; note that this is the child, and
2542 * the server will still have the socket open, and it is important
2543 * that we do not shutdown it. Note that the descriptors cannot be
2544 * closed before building the environment, as we call
2545 * get_remote_ipaddr there.
2546 */
Damien Miller95def091999-11-25 00:26:21 +11002547 if (packet_get_connection_in() == packet_get_connection_out())
2548 close(packet_get_connection_in());
2549 else {
2550 close(packet_get_connection_in());
2551 close(packet_get_connection_out());
2552 }
Damien Miller5428f641999-11-25 11:54:57 +11002553 /*
2554 * Close all descriptors related to channels. They will still remain
2555 * open in the parent.
2556 */
2557 /* XXX better use close-on-exec? -markus */
Damien Miller95def091999-11-25 00:26:21 +11002558 channel_close_all();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002559
Damien Miller5428f641999-11-25 11:54:57 +11002560 /*
2561 * Close any extra file descriptors. Note that there may still be
2562 * descriptors left by system functions. They will be closed later.
2563 */
Damien Miller95def091999-11-25 00:26:21 +11002564 endpwent();
2565 endhostent();
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002566
Damien Miller5428f641999-11-25 11:54:57 +11002567 /*
2568 * Close any extra open file descriptors so that we don\'t have them
2569 * hanging around in clients. Note that we want to do this after
2570 * initgroups, because at least on Solaris 2.3 it leaves file
2571 * descriptors open.
2572 */
Damien Miller95def091999-11-25 00:26:21 +11002573 for (i = 3; i < 64; i++)
2574 close(i);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002575
Damien Miller95def091999-11-25 00:26:21 +11002576 /* Change current directory to the user\'s home directory. */
2577 if (chdir(pw->pw_dir) < 0)
2578 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2579 pw->pw_dir, strerror(errno));
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002580
Damien Miller5428f641999-11-25 11:54:57 +11002581 /*
2582 * Must take new environment into use so that .ssh/rc, /etc/sshrc and
2583 * xauth are run in the proper environment.
2584 */
Damien Miller95def091999-11-25 00:26:21 +11002585 environ = env;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002586
Damien Miller5428f641999-11-25 11:54:57 +11002587 /*
2588 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first
2589 * in this order).
2590 */
Damien Miller95def091999-11-25 00:26:21 +11002591 if (!options.use_login) {
2592 if (stat(SSH_USER_RC, &st) >= 0) {
2593 if (debug_flag)
2594 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002595
Damien Miller95def091999-11-25 00:26:21 +11002596 f = popen("/bin/sh " SSH_USER_RC, "w");
2597 if (f) {
2598 if (auth_proto != NULL && auth_data != NULL)
2599 fprintf(f, "%s %s\n", auth_proto, auth_data);
2600 pclose(f);
2601 } else
2602 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2603 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
2604 if (debug_flag)
2605 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002606
Damien Miller95def091999-11-25 00:26:21 +11002607 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2608 if (f) {
2609 if (auth_proto != NULL && auth_data != NULL)
2610 fprintf(f, "%s %s\n", auth_proto, auth_data);
2611 pclose(f);
2612 } else
2613 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2614 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002615#ifdef XAUTH_PATH
Damien Miller95def091999-11-25 00:26:21 +11002616 else {
Damien Miller5428f641999-11-25 11:54:57 +11002617 /* Add authority data to .Xauthority if appropriate. */
Damien Miller95def091999-11-25 00:26:21 +11002618 if (auth_proto != NULL && auth_data != NULL) {
2619 if (debug_flag)
2620 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2621 XAUTH_PATH, display, auth_proto, auth_data);
2622
2623 f = popen(XAUTH_PATH " -q -", "w");
2624 if (f) {
2625 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
2626 fclose(f);
2627 } else
2628 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2629 }
2630 }
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002631#endif /* XAUTH_PATH */
2632
Damien Miller95def091999-11-25 00:26:21 +11002633 /* Get the last component of the shell name. */
2634 cp = strrchr(shell, '/');
2635 if (cp)
2636 cp++;
2637 else
2638 cp = shell;
2639 }
Damien Miller5428f641999-11-25 11:54:57 +11002640 /*
2641 * If we have no command, execute the shell. In this case, the shell
2642 * name to be passed in argv[0] is preceded by '-' to indicate that
2643 * this is a login shell.
2644 */
Damien Miller95def091999-11-25 00:26:21 +11002645 if (!command) {
2646 if (!options.use_login) {
2647 char buf[256];
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002648
Damien Miller5428f641999-11-25 11:54:57 +11002649 /*
2650 * Check for mail if we have a tty and it was enabled
2651 * in server options.
2652 */
Damien Miller95def091999-11-25 00:26:21 +11002653 if (ttyname && options.check_mail) {
2654 char *mailbox;
2655 struct stat mailstat;
2656 mailbox = getenv("MAIL");
2657 if (mailbox != NULL) {
2658 if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
2659 printf("No mail.\n");
2660 else if (mailstat.st_mtime < mailstat.st_atime)
2661 printf("You have mail.\n");
2662 else
2663 printf("You have new mail.\n");
2664 }
2665 }
2666 /* Start the shell. Set initial character to '-'. */
2667 buf[0] = '-';
2668 strncpy(buf + 1, cp, sizeof(buf) - 1);
2669 buf[sizeof(buf) - 1] = 0;
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002670
Damien Miller95def091999-11-25 00:26:21 +11002671 /* Execute the shell. */
2672 argv[0] = buf;
2673 argv[1] = NULL;
2674 execve(shell, argv, env);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002675
Damien Miller95def091999-11-25 00:26:21 +11002676 /* Executing the shell failed. */
2677 perror(shell);
2678 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002679
Damien Miller95def091999-11-25 00:26:21 +11002680 } else {
2681 /* Launch login(1). */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002682
Damien Miller95def091999-11-25 00:26:21 +11002683 execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(),
2684 "-p", "-f", "--", pw->pw_name, NULL);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002685
Damien Miller95def091999-11-25 00:26:21 +11002686 /* Login couldn't be executed, die. */
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002687
Damien Miller95def091999-11-25 00:26:21 +11002688 perror("login");
2689 exit(1);
2690 }
2691 }
Damien Miller5428f641999-11-25 11:54:57 +11002692 /*
2693 * Execute the command using the user's shell. This uses the -c
2694 * option to execute the command.
2695 */
Damien Miller95def091999-11-25 00:26:21 +11002696 argv[0] = (char *) cp;
2697 argv[1] = "-c";
2698 argv[2] = (char *) command;
2699 argv[3] = NULL;
2700 execve(shell, argv, env);
2701 perror(shell);
2702 exit(1);
Damien Millerd4a8b7e1999-10-27 13:42:43 +10002703}