summaryrefslogtreecommitdiff
path: root/sshd.c
diff options
context:
space:
mode:
authorDamien Miller <djm@mindrot.org>1999-11-25 00:26:21 +1100
committerDamien Miller <djm@mindrot.org>1999-11-25 00:26:21 +1100
commit95def09838fc61b37b6ea7cd5c234a465b4b129b (patch)
tree042744f76f40a326b873cb1c3690a6d7d966bc3e /sshd.c
parent4d2f15f895f4c795afc008aeff3fd2ceffbc44f4 (diff)
- Merged very large OpenBSD source code reformat
- OpenBSD CVS updates - [channels.c cipher.c compat.c log-client.c scp.c serverloop.c] [ssh.h sshd.8 sshd.c] syslog changes: * Unified Logmessage for all auth-types, for success and for failed * Standard connections get only ONE line in the LOG when level==LOG: Auth-attempts are logged only, if authentication is: a) successfull or b) with passwd or c) we had more than AUTH_FAIL_LOG failues * many log() became verbose() * old behaviour with level=VERBOSE - [readconf.c readconf.h ssh.1 ssh.h sshconnect.c sshd.c] tranfer s/key challenge/response data in SSH_SMSG_AUTH_TIS_CHALLENGE messages. allows use of s/key in windows (ttssh, securecrt) and ssh-1.2.27 clients without 'ssh -v', ok: niels@ - [sshd.8] -V, for fallback to openssh in SSH2 compatibility mode - [sshd.c] fix sigchld race; cjc5@po.cwru.edu
Diffstat (limited to 'sshd.c')
-rw-r--r--sshd.c4503
1 files changed, 2252 insertions, 2251 deletions
diff --git a/sshd.c b/sshd.c
index 5718eae94..dba2d474d 100644
--- a/sshd.c
+++ b/sshd.c
@@ -1,24 +1,17 @@
1/* 1/*
2 2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3sshd.c 3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 4 * All rights reserved
5Author: Tatu Ylonen <ylo@cs.hut.fi> 5 * Created: Fri Mar 17 17:09:28 1995 ylo
6 6 * This program is the ssh daemon. It listens for connections from clients, and
7Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 7 * performs authentication, executes use commands or shell, and forwards
8 All rights reserved 8 * information to/from the application to the user client over an encrypted
9 9 * connection. This can also handle forwarding of X11, TCP/IP, and authentication
10Created: Fri Mar 17 17:09:28 1995 ylo 10 * agent connections.
11 11 */
12This program is the ssh daemon. It listens for connections from clients, and
13performs authentication, executes use commands or shell, and forwards
14information to/from the application to the user client over an encrypted
15connection. This can also handle forwarding of X11, TCP/IP, and authentication
16agent connections.
17
18*/
19 12
20#include "includes.h" 13#include "includes.h"
21RCSID("$Id: sshd.c,v 1.29 1999/11/23 00:24:32 damien Exp $"); 14RCSID("$Id: sshd.c,v 1.30 1999/11/24 13:26:23 damien Exp $");
22 15
23#include "xmalloc.h" 16#include "xmalloc.h"
24#include "rsa.h" 17#include "rsa.h"
@@ -52,10 +45,12 @@ ServerOptions options;
52/* Name of the server configuration file. */ 45/* Name of the server configuration file. */
53char *config_file_name = SERVER_CONFIG_FILE; 46char *config_file_name = SERVER_CONFIG_FILE;
54 47
55/* Debug mode flag. This can be set on the command line. If debug 48/*
56 mode is enabled, extra debugging output will be sent to the system 49 * Debug mode flag. This can be set on the command line. If debug
57 log, the daemon will not go to background, and will exit after processing 50 * mode is enabled, extra debugging output will be sent to the system
58 the first connection. */ 51 * log, the daemon will not go to background, and will exit after processing
52 * the first connection.
53 */
59int debug_flag = 0; 54int debug_flag = 0;
60 55
61/* Flag indicating that the daemon is being started from inetd. */ 56/* Flag indicating that the daemon is being started from inetd. */
@@ -74,15 +69,21 @@ char **saved_argv;
74 the SIGHUP signal handler. */ 69 the SIGHUP signal handler. */
75int listen_sock; 70int listen_sock;
76 71
77/* Flags set in auth-rsa from authorized_keys flags. These are set in 72/* the client's version string, passed by sshd2 in compat mode.
78 auth-rsa.c. */ 73 if != NULL, sshd will skip the version-number exchange */
74char *client_version_string = NULL;
75
76/* Flags set in auth-rsa from authorized_keys flags. These are set in auth-rsa.c. */
79int no_port_forwarding_flag = 0; 77int no_port_forwarding_flag = 0;
80int no_agent_forwarding_flag = 0; 78int no_agent_forwarding_flag = 0;
81int no_x11_forwarding_flag = 0; 79int no_x11_forwarding_flag = 0;
82int no_pty_flag = 0; 80int no_pty_flag = 0;
83char *forced_command = NULL; /* RSA authentication "command=" option. */ 81
84struct envstring *custom_environment = NULL; 82/* RSA authentication "command=" option. */
85 /* RSA authentication "environment=" options. */ 83char *forced_command = NULL;
84
85/* RSA authentication "environment=" options. */
86struct envstring *custom_environment = NULL;
86 87
87/* Session id for the current session. */ 88/* Session id for the current session. */
88unsigned char session_id[16]; 89unsigned char session_id[16];
@@ -93,13 +94,9 @@ unsigned char session_id[16];
93 The private key contains BIGNUMs, and we do not (in principle) have 94 The private key contains BIGNUMs, and we do not (in principle) have
94 access to the internals of them, and locking just the structure is not 95 access to the internals of them, and locking just the structure is not
95 very useful. Currently, memory locking is not implemented. */ 96 very useful. Currently, memory locking is not implemented. */
96struct 97struct {
97{ 98 RSA *private_key; /* Private part of server key. */
98 /* Private part of server key. */ 99 RSA *host_key; /* Private part of host key. */
99 RSA *private_key;
100
101 /* Private part of host key. */
102 RSA *host_key;
103} sensitive_data; 100} sensitive_data;
104 101
105/* Flag indicating whether the current session key has been used. This flag 102/* Flag indicating whether the current session key has been used. This flag
@@ -116,2454 +113,2458 @@ RSA *public_key;
116/* Prototypes for various functions defined later in this file. */ 113/* Prototypes for various functions defined later in this file. */
117void do_connection(); 114void do_connection();
118void do_authentication(char *user); 115void do_authentication(char *user);
119void do_authloop(struct passwd *pw); 116void do_authloop(struct passwd * pw);
120void do_fake_authloop(char *user); 117void do_fake_authloop(char *user);
121void do_authenticated(struct passwd *pw); 118void do_authenticated(struct passwd * pw);
122void do_exec_pty(const char *command, int ptyfd, int ttyfd, 119void do_exec_pty(const char *command, int ptyfd, int ttyfd,
123 const char *ttyname, struct passwd *pw, const char *term, 120 const char *ttyname, struct passwd * pw, const char *term,
124 const char *display, const char *auth_proto, 121 const char *display, const char *auth_proto,
125 const char *auth_data); 122 const char *auth_data);
126void do_exec_no_pty(const char *command, struct passwd *pw, 123void do_exec_no_pty(const char *command, struct passwd * pw,
127 const char *display, const char *auth_proto, 124 const char *display, const char *auth_proto,
128 const char *auth_data); 125 const char *auth_data);
129void do_child(const char *command, struct passwd *pw, const char *term, 126void do_child(const char *command, struct passwd * pw, const char *term,
130 const char *display, const char *auth_proto, 127 const char *display, const char *auth_proto,
131 const char *auth_data, const char *ttyname); 128 const char *auth_data, const char *ttyname);
132 129
133#ifdef HAVE_LIBPAM 130#ifdef HAVE_LIBPAM
134static int pamconv(int num_msg, const struct pam_message **msg, 131static int pamconv(int num_msg, const struct pam_message **msg,
135 struct pam_response **resp, void *appdata_ptr); 132 struct pam_response **resp, void *appdata_ptr);
136void do_pam_account_and_session(char *username, char *remote_user, 133void do_pam_account_and_session(char *username, char *remote_user,
137 const char *remote_host); 134 const char *remote_host);
138void pam_cleanup_proc(void *context); 135void pam_cleanup_proc(void *context);
139 136
140static struct pam_conv conv = { 137static struct pam_conv conv = {
141 pamconv, 138 pamconv,
142 NULL 139 NULL
143}; 140};
144struct pam_handle_t *pamh = NULL; 141struct pam_handle_t *pamh = NULL;
145const char *pampasswd = NULL; 142const char *pampasswd = NULL;
146char *pamconv_msg = NULL; 143char *pamconv_msg = NULL;
147 144
148static int pamconv(int num_msg, const struct pam_message **msg, 145static int pamconv(int num_msg, const struct pam_message **msg,
149 struct pam_response **resp, void *appdata_ptr) 146 struct pam_response **resp, void *appdata_ptr)
150{ 147{
151 struct pam_response *reply; 148 struct pam_response *reply;
152 int count; 149 int count;
153 size_t msg_len; 150 size_t msg_len;
154 char *p; 151 char *p;
155 152
156 /* PAM will free this later */ 153 /* PAM will free this later */
157 reply = malloc(num_msg * sizeof(*reply)); 154 reply = malloc(num_msg * sizeof(*reply));
158 if (reply == NULL) 155 if (reply == NULL)
159 return PAM_CONV_ERR; 156 return PAM_CONV_ERR;
160 157
161 for(count = 0; count < num_msg; count++) 158 for(count = 0; count < num_msg; count++) {
162 { 159 switch (msg[count]->msg_style) {
163 switch (msg[count]->msg_style) 160 case PAM_PROMPT_ECHO_OFF:
164 { 161 if (pampasswd == NULL) {
165 case PAM_PROMPT_ECHO_OFF: 162 free(reply);
166 if (pampasswd == NULL) 163 return PAM_CONV_ERR;
167 { 164 }
168 free(reply); 165 reply[count].resp_retcode = PAM_SUCCESS;
169 return PAM_CONV_ERR; 166 reply[count].resp = xstrdup(pampasswd);
170 } 167 break;
171 reply[count].resp_retcode = PAM_SUCCESS; 168
172 reply[count].resp = xstrdup(pampasswd); 169 case PAM_TEXT_INFO:
173 break; 170 reply[count].resp_retcode = PAM_SUCCESS;
174 171 reply[count].resp = xstrdup("");
175 case PAM_TEXT_INFO: 172
176 reply[count].resp_retcode = PAM_SUCCESS; 173 if (msg[count]->msg == NULL)
177 reply[count].resp = xstrdup(""); 174 break;
178 175
179 if (msg[count]->msg == NULL) 176 debug("Adding PAM message: %s", msg[count]->msg);
180 break; 177
181 debug("Adding PAM message: %s", msg[count]->msg); 178 msg_len = strlen(msg[count]->msg);
182 179 if (pamconv_msg) {
183 msg_len = strlen(msg[count]->msg); 180 size_t n = strlen(pamconv_msg);
184 if (pamconv_msg) 181 pamconv_msg = xrealloc(pamconv_msg, n + msg_len + 2);
185 { 182 p = pamconv_msg + n;
186 size_t n = strlen(pamconv_msg); 183 } else {
187 pamconv_msg = xrealloc(pamconv_msg, n + msg_len + 2); 184 pamconv_msg = p = xmalloc(msg_len + 2);
188 p = pamconv_msg + n; 185 }
186 memcpy(p, msg[count]->msg, msg_len);
187 p[msg_len] = '\n';
188 p[msg_len + 1] = '\0';
189 break;
190
191 case PAM_PROMPT_ECHO_ON:
192 case PAM_ERROR_MSG:
193 default:
194 free(reply);
195 return PAM_CONV_ERR;
196 }
189 } 197 }
190 else 198
191 pamconv_msg = p = xmalloc(msg_len + 2); 199 *resp = reply;
192 memcpy(p, msg[count]->msg, msg_len); 200
193 p[msg_len] = '\n'; 201 return PAM_SUCCESS;
194 p[msg_len + 1] = '\0';
195 break;
196
197 case PAM_PROMPT_ECHO_ON:
198 case PAM_ERROR_MSG:
199 default:
200 free(reply);
201 return PAM_CONV_ERR;
202 }
203 }
204
205 *resp = reply;
206
207 return PAM_SUCCESS;
208} 202}
209 203
210void pam_cleanup_proc(void *context) 204void pam_cleanup_proc(void *context)
211{ 205{
212 int pam_retval; 206 int pam_retval;
213 207
214 if (pamh != NULL) 208 if (pamh != NULL)
215 { 209 {
216 pam_retval = pam_close_session((pam_handle_t *)pamh, 0); 210 pam_retval = pam_close_session((pam_handle_t *)pamh, 0);
217 if (pam_retval != PAM_SUCCESS) 211 if (pam_retval != PAM_SUCCESS) {
218 { 212 log("Cannot close PAM session: %.200s",
219 log("Cannot close PAM session: %.200s", 213 PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
220 PAM_STRERROR((pam_handle_t *)pamh, pam_retval)); 214 }
221 } 215
222 216 pam_retval = pam_end((pam_handle_t *)pamh, pam_retval);
223 pam_retval = pam_end((pam_handle_t *)pamh, pam_retval); 217 if (pam_retval != PAM_SUCCESS) {
224 if (pam_retval != PAM_SUCCESS) 218 log("Cannot release PAM authentication: %.200s",
225 { 219 PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
226 log("Cannot release PAM authentication: %.200s", 220 }
227 PAM_STRERROR((pam_handle_t *)pamh, pam_retval)); 221 }
228 }
229 }
230} 222}
231 223
232void do_pam_account_and_session(char *username, char *remote_user, 224void do_pam_account_and_session(char *username, char *remote_user,
233 const char *remote_host) 225 const char *remote_host)
234{ 226{
235 int pam_retval; 227 int pam_retval;
236 228
237 if (remote_host != NULL) 229 if (remote_host != NULL) {
238 { 230 debug("PAM setting rhost to \"%.200s\"", remote_host);
239 debug("PAM setting rhost to \"%.200s\"", remote_host); 231 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RHOST, remote_host);
240 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RHOST, remote_host); 232 if (pam_retval != PAM_SUCCESS) {
241 if (pam_retval != PAM_SUCCESS) 233 log("PAM set rhost failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
242 { 234 do_fake_authloop(username);
243 log("PAM set rhost failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval)); 235 }
244 do_fake_authloop(username); 236 }
245 } 237
246 } 238 if (remote_user != NULL) {
247 239 debug("PAM setting ruser to \"%.200s\"", remote_user);
248 if (remote_user != NULL) 240 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RUSER, remote_user);
249 { 241 if (pam_retval != PAM_SUCCESS) {
250 debug("PAM setting ruser to \"%.200s\"", remote_user); 242 log("PAM set ruser failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
251 pam_retval = pam_set_item((pam_handle_t *)pamh, PAM_RUSER, remote_user); 243 do_fake_authloop(username);
252 if (pam_retval != PAM_SUCCESS) 244 }
253 { 245 }
254 log("PAM set ruser failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval)); 246
255 do_fake_authloop(username); 247 pam_retval = pam_acct_mgmt((pam_handle_t *)pamh, 0);
256 } 248 if (pam_retval != PAM_SUCCESS) {
257 } 249 log("PAM rejected by account configuration: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
258 250 do_fake_authloop(username);
259 pam_retval = pam_acct_mgmt((pam_handle_t *)pamh, 0); 251 }
260 if (pam_retval != PAM_SUCCESS) 252
261 { 253 pam_retval = pam_open_session((pam_handle_t *)pamh, 0);
262 log("PAM rejected by account configuration: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval)); 254 if (pam_retval != PAM_SUCCESS) {
263 do_fake_authloop(username); 255 log("PAM session setup failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
264 } 256 do_fake_authloop(username);
265 257 }
266 pam_retval = pam_open_session((pam_handle_t *)pamh, 0);
267 if (pam_retval != PAM_SUCCESS)
268 {
269 log("PAM session setup failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
270 do_fake_authloop(username);
271 }
272} 258}
273#endif /* HAVE_LIBPAM */ 259#endif /* HAVE_LIBPAM */
274 260
275/* Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP; 261/*
276 the effect is to reread the configuration file (and to regenerate 262 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
277 the server key). */ 263 * the effect is to reread the configuration file (and to regenerate
278 264 * the server key).
279void sighup_handler(int sig) 265 */
266void
267sighup_handler(int sig)
280{ 268{
281 received_sighup = 1; 269 received_sighup = 1;
282 signal(SIGHUP, sighup_handler); 270 signal(SIGHUP, sighup_handler);
283} 271}
284 272
285/* Called from the main program after receiving SIGHUP. Restarts the 273/*
286 server. */ 274 * Called from the main program after receiving SIGHUP.
287 275 * Restarts the server.
288void sighup_restart() 276 */
277void
278sighup_restart()
289{ 279{
290 log("Received SIGHUP; restarting."); 280 log("Received SIGHUP; restarting.");
291 close(listen_sock); 281 close(listen_sock);
292 execv(saved_argv[0], saved_argv); 282 execv(saved_argv[0], saved_argv);
293 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno)); 283 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno));
294 exit(1); 284 exit(1);
295} 285}
296 286
297/* Generic signal handler for terminating signals in the master daemon. 287/*
298 These close the listen socket; not closing it seems to cause "Address 288 * Generic signal handler for terminating signals in the master daemon.
299 already in use" problems on some machines, which is inconvenient. */ 289 * These close the listen socket; not closing it seems to cause "Address
300 290 * already in use" problems on some machines, which is inconvenient.
301void sigterm_handler(int sig) 291 */
292void
293sigterm_handler(int sig)
302{ 294{
303 log("Received signal %d; terminating.", sig); 295 log("Received signal %d; terminating.", sig);
304 close(listen_sock); 296 close(listen_sock);
305 exit(255); 297 exit(255);
306} 298}
307 299
308/* SIGCHLD handler. This is called whenever a child dies. This will then 300/*
309 reap any zombies left by exited c. */ 301 * SIGCHLD handler. This is called whenever a child dies. This will then
310 302 * reap any zombies left by exited c.
311void main_sigchld_handler(int sig) 303 */
304void
305main_sigchld_handler(int sig)
312{ 306{
313 int save_errno = errno; 307 int save_errno = errno;
314 int status; 308 int status;
315 309
316 while (waitpid(-1, &status, WNOHANG) > 0) 310 while (waitpid(-1, &status, WNOHANG) > 0)
317 ; 311 ;
318 312
319 signal(SIGCHLD, main_sigchld_handler); 313 signal(SIGCHLD, main_sigchld_handler);
320 errno = save_errno; 314 errno = save_errno;
321} 315}
322 316
323/* Signal handler for the alarm after the login grace period has expired. */ 317/*
324 318 * Signal handler for the alarm after the login grace period has expired.
325void grace_alarm_handler(int sig) 319 */
320void
321grace_alarm_handler(int sig)
326{ 322{
327 /* Close the connection. */ 323 /* Close the connection. */
328 packet_close(); 324 packet_close();
329
330 /* Log error and exit. */
331 fatal("Timeout before authentication.");
332}
333 325
334/* Signal handler for the key regeneration alarm. Note that this 326 /* Log error and exit. */
335 alarm only occurs in the daemon waiting for connections, and it does not 327 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
336 do anything with the private key or random state before forking. Thus there 328}
337 should be no concurrency control/asynchronous execution problems. */
338 329
339void key_regeneration_alarm(int sig) 330/*
331 * convert ssh auth msg type into description
332 */
333char *
334get_authname(int type)
340{ 335{
341 int save_errno = errno; 336 switch (type) {
342 337 case SSH_CMSG_AUTH_PASSWORD:
343 /* Check if we should generate a new key. */ 338 return "password";
344 if (key_used) 339 case SSH_CMSG_AUTH_RSA:
345 { 340 return "rsa";
346 /* This should really be done in the background. */ 341 case SSH_CMSG_AUTH_RHOSTS_RSA:
347 log("Generating new %d bit RSA key.", options.server_key_bits); 342 return "rhosts-rsa";
348 343 case SSH_CMSG_AUTH_RHOSTS:
349 if (sensitive_data.private_key != NULL) 344 return "rhosts";
350 RSA_free(sensitive_data.private_key); 345#ifdef KRB4
351 sensitive_data.private_key = RSA_new(); 346 case SSH_CMSG_AUTH_KERBEROS:
352 347 return "kerberos";
353 if (public_key != NULL) 348#endif
354 RSA_free(public_key); 349#ifdef SKEY
355 public_key = RSA_new(); 350 case SSH_CMSG_AUTH_TIS_RESPONSE:
356 351 return "s/key";
357 rsa_generate_key(sensitive_data.private_key, public_key, 352#endif
358 options.server_key_bits); 353 }
359 arc4random_stir(); 354 fatal("get_authname: unknown auth %d: internal error", type);
360 key_used = 0; 355 return NULL;
361 log("RSA key generation complete.");
362 }
363
364 /* Reschedule the alarm. */
365 signal(SIGALRM, key_regeneration_alarm);
366 alarm(options.key_regeneration_time);
367 errno = save_errno;
368} 356}
369 357
370/* Main program for the daemon. */ 358/*
359 * Signal handler for the key regeneration alarm. Note that this
360 * alarm only occurs in the daemon waiting for connections, and it does not
361 * do anything with the private key or random state before forking.
362 * Thus there should be no concurrency control/asynchronous execution
363 * problems.
364 */
365void
366key_regeneration_alarm(int sig)
367{
368 int save_errno = errno;
369
370 /* Check if we should generate a new key. */
371 if (key_used) {
372 /* This should really be done in the background. */
373 log("Generating new %d bit RSA key.", options.server_key_bits);
374
375 if (sensitive_data.private_key != NULL)
376 RSA_free(sensitive_data.private_key);
377 sensitive_data.private_key = RSA_new();
378
379 if (public_key != NULL)
380 RSA_free(public_key);
381 public_key = RSA_new();
382
383 rsa_generate_key(sensitive_data.private_key, public_key,
384 options.server_key_bits);
385 arc4random_stir();
386 key_used = 0;
387 log("RSA key generation complete.");
388 }
389 /* Reschedule the alarm. */
390 signal(SIGALRM, key_regeneration_alarm);
391 alarm(options.key_regeneration_time);
392 errno = save_errno;
393}
371 394
395/*
396 * Main program for the daemon.
397 */
372int 398int
373main(int ac, char **av) 399main(int ac, char **av)
374{ 400{
375 extern char *optarg; 401 extern char *optarg;
376 extern int optind; 402 extern int optind;
377 int opt, aux, sock_in, sock_out, newsock, i, pid, on = 1; 403 int opt, aux, sock_in, sock_out, newsock, i, pid, on = 1;
378 int remote_major, remote_minor; 404 int remote_major, remote_minor;
379 int silentrsa = 0; 405 int silentrsa = 0;
380 struct sockaddr_in sin; 406 struct sockaddr_in sin;
381 char buf[100]; /* Must not be larger than remote_version. */ 407 char buf[100]; /* Must not be larger than remote_version. */
382 char remote_version[100]; /* Must be at least as big as buf. */ 408 char remote_version[100]; /* Must be at least as big as buf. */
383 int remote_port; 409 const char *remote_ip;
384 char *comment; 410 int remote_port;
385 FILE *f; 411 char *comment;
386 struct linger linger; 412 FILE *f;
387 413 struct linger linger;
388 /* Save argv[0]. */ 414
389 saved_argv = av; 415 /* Save argv[0]. */
390 if (strchr(av[0], '/')) 416 saved_argv = av;
391 av0 = strrchr(av[0], '/') + 1; 417 if (strchr(av[0], '/'))
392 else 418 av0 = strrchr(av[0], '/') + 1;
393 av0 = av[0]; 419 else
394 420 av0 = av[0];
395 /* Initialize configuration options to their default values. */ 421
396 initialize_server_options(&options); 422 /* Initialize configuration options to their default values. */
397 423 initialize_server_options(&options);
398 /* Parse command-line arguments. */ 424
399 while ((opt = getopt(ac, av, "f:p:b:k:h:g:diqQ")) != EOF) 425 /* Parse command-line arguments. */
400 { 426 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ")) != EOF) {
401 switch (opt) 427 switch (opt) {
402 { 428 case 'f':
403 case 'f': 429 config_file_name = optarg;
404 config_file_name = optarg; 430 break;
405 break; 431 case 'd':
406 case 'd': 432 debug_flag = 1;
407 debug_flag = 1; 433 options.log_level = SYSLOG_LEVEL_DEBUG;
408 options.log_level = SYSLOG_LEVEL_DEBUG; 434 break;
409 break; 435 case 'i':
410 case 'i': 436 inetd_flag = 1;
411 inetd_flag = 1; 437 break;
412 break; 438 case 'Q':
413 case 'Q': 439 silentrsa = 1;
414 silentrsa = 1; 440 break;
415 break; 441 case 'q':
416 case 'q': 442 options.log_level = SYSLOG_LEVEL_QUIET;
417 options.log_level = SYSLOG_LEVEL_QUIET; 443 break;
418 break; 444 case 'b':
419 case 'b': 445 options.server_key_bits = atoi(optarg);
420 options.server_key_bits = atoi(optarg); 446 break;
421 break; 447 case 'p':
422 case 'p': 448 options.port = atoi(optarg);
423 options.port = atoi(optarg); 449 break;
424 break; 450 case 'g':
425 case 'g': 451 options.login_grace_time = atoi(optarg);
426 options.login_grace_time = atoi(optarg); 452 break;
427 break; 453 case 'k':
428 case 'k': 454 options.key_regeneration_time = atoi(optarg);
429 options.key_regeneration_time = atoi(optarg); 455 break;
430 break; 456 case 'h':
431 case 'h': 457 options.host_key_file = optarg;
432 options.host_key_file = optarg; 458 break;
433 break; 459 case 'V':
434 case '?': 460 client_version_string = optarg;
435 default: 461 /* only makes sense with inetd_flag, i.e. no listen() */
436 fprintf(stderr, "sshd version %s\n", SSH_VERSION); 462 inetd_flag = 1;
437 fprintf(stderr, "Usage: %s [options]\n", av0); 463 break;
438 fprintf(stderr, "Options:\n"); 464 case '?':
439 fprintf(stderr, " -f file Configuration file (default %s/sshd_config)\n", ETCDIR); 465 default:
440 fprintf(stderr, " -d Debugging mode\n"); 466 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
441 fprintf(stderr, " -i Started from inetd\n"); 467 fprintf(stderr, "Usage: %s [options]\n", av0);
442 fprintf(stderr, " -q Quiet (no logging)\n"); 468 fprintf(stderr, "Options:\n");
443 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n"); 469 fprintf(stderr, " -f file Configuration file (default %s/sshd_config)\n", ETCDIR);
444 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n"); 470 fprintf(stderr, " -d Debugging mode\n");
445 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n"); 471 fprintf(stderr, " -i Started from inetd\n");
446 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n"); 472 fprintf(stderr, " -q Quiet (no logging)\n");
447 fprintf(stderr, " -h file File from which to read host key (default: %s)\n", 473 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
448 HOST_KEY_FILE); 474 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
449 exit(1); 475 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n");
476 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
477 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
478 HOST_KEY_FILE);
479 exit(1);
480 }
481 }
482
483 /* check if RSA support exists */
484 if (rsa_alive() == 0) {
485 if (silentrsa == 0)
486 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n");
487 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)");
488 exit(1);
489 }
490 /* Read server configuration options from the configuration file. */
491 read_server_config(&options, config_file_name);
492
493 /* Fill in default values for those options not explicitly set. */
494 fill_default_server_options(&options);
495
496 /* Check certain values for sanity. */
497 if (options.server_key_bits < 512 ||
498 options.server_key_bits > 32768) {
499 fprintf(stderr, "Bad server key size.\n");
500 exit(1);
501 }
502 if (options.port < 1 || options.port > 65535) {
503 fprintf(stderr, "Bad port number.\n");
504 exit(1);
505 }
506 /* Check that there are no remaining arguments. */
507 if (optind < ac) {
508 fprintf(stderr, "Extra argument %s.\n", av[optind]);
509 exit(1);
450 } 510 }
451 } 511 /* Force logging to stderr while loading the private host key
452 512 unless started from inetd */
453 /* check if RSA support exists */ 513 log_init(av0, options.log_level, options.log_facility, !inetd_flag);
454 if (rsa_alive() == 0) { 514
455 if (silentrsa == 0) 515 debug("sshd version %.100s", SSH_VERSION);
456 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n"); 516
457 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)"); 517 sensitive_data.host_key = RSA_new();
458 exit(1); 518 errno = 0;
459 } 519 /* Load the host key. It must have empty passphrase. */
460 520 if (!load_private_key(options.host_key_file, "",
461 /* Read server configuration options from the configuration file. */ 521 sensitive_data.host_key, &comment)) {
462 read_server_config(&options, config_file_name); 522 error("Could not load host key: %.200s: %.100s",
463 523 options.host_key_file, strerror(errno));
464 /* Fill in default values for those options not explicitly set. */ 524 exit(1);
465 fill_default_server_options(&options); 525 }
466 526 xfree(comment);
467 /* Check certain values for sanity. */ 527
468 if (options.server_key_bits < 512 || 528 /* Initialize the log (it is reinitialized below in case we
469 options.server_key_bits > 32768) 529 forked). */
470 { 530 if (debug_flag && !inetd_flag)
471 fprintf(stderr, "Bad server key size.\n"); 531 log_stderr = 1;
472 exit(1); 532 log_init(av0, options.log_level, options.log_facility, log_stderr);
473 } 533
474 if (options.port < 1 || options.port > 65535) 534 /* If not in debugging mode, and not started from inetd,
475 { 535 disconnect from the controlling terminal, and fork. The
476 fprintf(stderr, "Bad port number.\n"); 536 original process exits. */
477 exit(1); 537 if (!debug_flag && !inetd_flag) {
478 }
479
480 /* Check that there are no remaining arguments. */
481 if (optind < ac)
482 {
483 fprintf(stderr, "Extra argument %s.\n", av[optind]);
484 exit(1);
485 }
486
487 /* Force logging to stderr while loading the private host key
488 unless started from inetd */
489 log_init(av0, options.log_level, options.log_facility, !inetd_flag);
490
491 debug("sshd version %.100s", SSH_VERSION);
492
493 sensitive_data.host_key = RSA_new();
494 errno = 0;
495 /* Load the host key. It must have empty passphrase. */
496 if (!load_private_key(options.host_key_file, "",
497 sensitive_data.host_key, &comment))
498 {
499 error("Could not load host key: %.200s: %.100s",
500 options.host_key_file, strerror(errno));
501 exit(1);
502 }
503 xfree(comment);
504
505 /* Initialize the log (it is reinitialized below in case we forked). */
506 if (debug_flag && !inetd_flag)
507 log_stderr = 1;
508 log_init(av0, options.log_level, options.log_facility, log_stderr);
509
510 /* If not in debugging mode, and not started from inetd, disconnect from
511 the controlling terminal, and fork. The original process exits. */
512 if (!debug_flag && !inetd_flag)
513 {
514#ifdef TIOCNOTTY 538#ifdef TIOCNOTTY
515 int fd; 539 int fd;
516#endif /* TIOCNOTTY */ 540#endif /* TIOCNOTTY */
517 if (daemon(0, 0) < 0) 541 if (daemon(0, 0) < 0)
518 fatal("daemon() failed: %.200s", strerror(errno)); 542 fatal("daemon() failed: %.200s", strerror(errno));
519 543
520 /* Disconnect from the controlling tty. */ 544 /* Disconnect from the controlling tty. */
521#ifdef TIOCNOTTY 545#ifdef TIOCNOTTY
522 fd = open("/dev/tty", O_RDWR|O_NOCTTY); 546 fd = open("/dev/tty", O_RDWR | O_NOCTTY);
523 if (fd >= 0) 547 if (fd >= 0) {
524 { 548 (void) ioctl(fd, TIOCNOTTY, NULL);
525 (void)ioctl(fd, TIOCNOTTY, NULL); 549 close(fd);
526 close(fd); 550 }
527 }
528#endif /* TIOCNOTTY */ 551#endif /* TIOCNOTTY */
529 }
530
531 /* Reinitialize the log (because of the fork above). */
532 log_init(av0, options.log_level, options.log_facility, log_stderr);
533
534 /* Check that server and host key lengths differ sufficiently. This is
535 necessary to make double encryption work with rsaref. Oh, I hate
536 software patents. I dont know if this can go? Niels */
537 if (options.server_key_bits >
538 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
539 options.server_key_bits <
540 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED)
541 {
542 options.server_key_bits =
543 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
544 debug("Forcing server key to %d bits to make it differ from host key.",
545 options.server_key_bits);
546 }
547
548 /* Do not display messages to stdout in RSA code. */
549 rsa_set_verbose(0);
550
551 /* Initialize the random number generator. */
552 arc4random_stir();
553
554 /* Chdir to the root directory so that the current disk can be unmounted
555 if desired. */
556 chdir("/");
557
558 /* Close connection cleanly after attack. */
559 cipher_attack_detected = packet_disconnect;
560
561 /* Start listening for a socket, unless started from inetd. */
562 if (inetd_flag)
563 {
564 int s1, s2;
565 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
566 s2 = dup(s1);
567 sock_in = dup(0);
568 sock_out = dup(1);
569 /* We intentionally do not close the descriptors 0, 1, and 2 as our
570 code for setting the descriptors won\'t work if ttyfd happens to
571 be one of those. */
572 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
573
574 public_key = RSA_new();
575 sensitive_data.private_key = RSA_new();
576 /* Generate an rsa key. */
577 log("Generating %d bit RSA key.", options.server_key_bits);
578 rsa_generate_key(sensitive_data.private_key, public_key,
579 options.server_key_bits);
580 arc4random_stir();
581 log("RSA key generation complete.");
582 }
583 else
584 {
585 /* Create socket for listening. */
586 listen_sock = socket(AF_INET, SOCK_STREAM, 0);
587 if (listen_sock < 0)
588 fatal("socket: %.100s", strerror(errno));
589
590 /* Set socket options. We try to make the port reusable and have it
591 close as fast as possible without waiting in unnecessary wait states
592 on close. */
593 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
594 sizeof(on));
595 linger.l_onoff = 1;
596 linger.l_linger = 5;
597 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, (void *)&linger,
598 sizeof(linger));
599
600 /* Initialize the socket address. */
601 memset(&sin, 0, sizeof(sin));
602 sin.sin_family = AF_INET;
603 sin.sin_addr = options.listen_addr;
604 sin.sin_port = htons(options.port);
605
606 /* Bind the socket to the desired port. */
607 if (bind(listen_sock, (struct sockaddr *)&sin, sizeof(sin)) < 0)
608 {
609 error("bind: %.100s", strerror(errno));
610 shutdown(listen_sock, SHUT_RDWR);
611 close(listen_sock);
612 fatal("Bind to port %d failed.", options.port);
613 } 552 }
614 553 /* Reinitialize the log (because of the fork above). */
615 if (!debug_flag) 554 log_init(av0, options.log_level, options.log_facility, log_stderr);
616 { 555
617 /* Record our pid in /etc/sshd_pid to make it easier to kill the 556 /* Check that server and host key lengths differ sufficiently.
618 correct sshd. We don\'t want to do this before the bind above 557 This is necessary to make double encryption work with rsaref.
619 because the bind will fail if there already is a daemon, and this 558 Oh, I hate software patents. I dont know if this can go? Niels */
620 will overwrite any old pid in the file. */ 559 if (options.server_key_bits >
621 f = fopen(SSH_DAEMON_PID_FILE, "w"); 560 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED &&
622 if (f) 561 options.server_key_bits <
623 { 562 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
624 fprintf(f, "%u\n", (unsigned int)getpid()); 563 options.server_key_bits =
625 fclose(f); 564 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED;
626 } 565 debug("Forcing server key to %d bits to make it differ from host key.",
566 options.server_key_bits);
627 } 567 }
628 568 /* Do not display messages to stdout in RSA code. */
629 /* Start listening on the port. */ 569 rsa_set_verbose(0);
630 log("Server listening on port %d.", options.port); 570
631 if (listen(listen_sock, 5) < 0) 571 /* Initialize the random number generator. */
632 fatal("listen: %.100s", strerror(errno)); 572 arc4random_stir();
633 573
634 public_key = RSA_new(); 574 /* Chdir to the root directory so that the current disk can be
635 sensitive_data.private_key = RSA_new(); 575 unmounted if desired. */
636 /* Generate an rsa key. */ 576 chdir("/");
637 log("Generating %d bit RSA key.", options.server_key_bits); 577
638 rsa_generate_key(sensitive_data.private_key, public_key, 578 /* Close connection cleanly after attack. */
639 options.server_key_bits); 579 cipher_attack_detected = packet_disconnect;
640 arc4random_stir(); 580
641 log("RSA key generation complete."); 581 /* Start listening for a socket, unless started from inetd. */
642 582 if (inetd_flag) {
643 /* Schedule server key regeneration alarm. */ 583 int s1, s2;
644 signal(SIGALRM, key_regeneration_alarm); 584 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
645 alarm(options.key_regeneration_time); 585 s2 = dup(s1);
646 586 sock_in = dup(0);
647 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */ 587 sock_out = dup(1);
648 signal(SIGHUP, sighup_handler); 588 /* We intentionally do not close the descriptors 0, 1, and 2
649 signal(SIGTERM, sigterm_handler); 589 as our code for setting the descriptors won\'t work
650 signal(SIGQUIT, sigterm_handler); 590 if ttyfd happens to be one of those. */
651 591 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
652 /* Arrange SIGCHLD to be caught. */ 592
653 signal(SIGCHLD, main_sigchld_handler); 593 public_key = RSA_new();
654 594 sensitive_data.private_key = RSA_new();
655 /* Stay listening for connections until the system crashes or the 595
656 daemon is killed with a signal. */ 596 log("Generating %d bit RSA key.", options.server_key_bits);
657 for (;;) 597 rsa_generate_key(sensitive_data.private_key, public_key,
658 { 598 options.server_key_bits);
659 if (received_sighup) 599 arc4random_stir();
660 sighup_restart(); 600 log("RSA key generation complete.");
661 /* Wait in accept until there is a connection. */ 601 } else {
662 aux = sizeof(sin); 602 /* Create socket for listening. */
663 newsock = accept(listen_sock, (struct sockaddr *)&sin, &aux); 603 listen_sock = socket(AF_INET, SOCK_STREAM, 0);
664 if (received_sighup) 604 if (listen_sock < 0)
665 sighup_restart(); 605 fatal("socket: %.100s", strerror(errno));
666 if (newsock < 0) 606
667 { 607 /* Set socket options. We try to make the port reusable
668 if (errno == EINTR) 608 and have it close as fast as possible without waiting
669 continue; 609 in unnecessary wait states on close. */
670 error("accept: %.100s", strerror(errno)); 610 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on,
671 continue; 611 sizeof(on));
672 } 612 linger.l_onoff = 1;
673 613 linger.l_linger = 5;
674 /* Got connection. Fork a child to handle it, unless we are in 614 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, (void *) &linger,
675 debugging mode. */ 615 sizeof(linger));
676 if (debug_flag) 616
677 { 617 /* Initialize the socket address. */
678 /* In debugging mode. Close the listening socket, and start 618 memset(&sin, 0, sizeof(sin));
679 processing the connection without forking. */ 619 sin.sin_family = AF_INET;
680 debug("Server will not fork when running in debugging mode."); 620 sin.sin_addr = options.listen_addr;
681 close(listen_sock); 621 sin.sin_port = htons(options.port);
682 sock_in = newsock; 622
683 sock_out = newsock; 623 /* Bind the socket to the desired port. */
684 pid = getpid(); 624 if (bind(listen_sock, (struct sockaddr *) & sin, sizeof(sin)) < 0) {
685 break; 625 error("bind: %.100s", strerror(errno));
686 } 626 shutdown(listen_sock, SHUT_RDWR);
687 else 627 close(listen_sock);
688 { 628 fatal("Bind to port %d failed.", options.port);
689 /* Normal production daemon. Fork, and have the child process 629 }
690 the connection. The parent continues listening. */ 630 if (!debug_flag) {
691 if ((pid = fork()) == 0) 631 /* Record our pid in /etc/sshd_pid to make it
692 { 632 easier to kill the correct sshd. We don\'t
693 /* Child. Close the listening socket, and start using 633 want to do this before the bind above because
694 the accepted socket. Reinitialize logging (since our 634 the bind will fail if there already is a
695 pid has changed). We break out of the loop to handle 635 daemon, and this will overwrite any old pid in
696 the connection. */ 636 the file. */
697 close(listen_sock); 637 f = fopen(SSH_DAEMON_PID_FILE, "w");
698 sock_in = newsock; 638 if (f) {
699 sock_out = newsock; 639 fprintf(f, "%u\n", (unsigned int) getpid());
700 log_init(av0, options.log_level, options.log_facility, log_stderr); 640 fclose(f);
701 break; 641 }
702 } 642 }
703 }
704 643
705 /* Parent. Stay in the loop. */ 644 log("Server listening on port %d.", options.port);
706 if (pid < 0) 645 if (listen(listen_sock, 5) < 0)
707 error("fork: %.100s", strerror(errno)); 646 fatal("listen: %.100s", strerror(errno));
708 else 647
709 debug("Forked child %d.", pid); 648 public_key = RSA_new();
649 sensitive_data.private_key = RSA_new();
650
651 log("Generating %d bit RSA key.", options.server_key_bits);
652 rsa_generate_key(sensitive_data.private_key, public_key,
653 options.server_key_bits);
654 arc4random_stir();
655 log("RSA key generation complete.");
656
657 /* Schedule server key regeneration alarm. */
658 signal(SIGALRM, key_regeneration_alarm);
659 alarm(options.key_regeneration_time);
660
661 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
662 signal(SIGHUP, sighup_handler);
663 signal(SIGTERM, sigterm_handler);
664 signal(SIGQUIT, sigterm_handler);
665
666 /* Arrange SIGCHLD to be caught. */
667 signal(SIGCHLD, main_sigchld_handler);
668
669 /* Stay listening for connections until the system crashes
670 or the daemon is killed with a signal. */
671 for (;;) {
672 if (received_sighup)
673 sighup_restart();
674 /* Wait in accept until there is a connection. */
675 aux = sizeof(sin);
676 newsock = accept(listen_sock, (struct sockaddr *) & sin, &aux);
677 if (received_sighup)
678 sighup_restart();
679 if (newsock < 0) {
680 if (errno == EINTR)
681 continue;
682 error("accept: %.100s", strerror(errno));
683 continue;
684 }
685 /* Got connection. Fork a child to handle it,
686 unless we are in debugging mode. */
687 if (debug_flag) {
688 /* In debugging mode. Close the listening
689 socket, and start processing the
690 connection without forking. */
691 debug("Server will not fork when running in debugging mode.");
692 close(listen_sock);
693 sock_in = newsock;
694 sock_out = newsock;
695 pid = getpid();
696 break;
697 } else {
698 /* Normal production daemon. Fork, and
699 have the child process the connection.
700 The parent continues listening. */
701 if ((pid = fork()) == 0) {
702 /* Child. Close the listening
703 socket, and start using the
704 accepted socket. Reinitialize
705 logging (since our pid has
706 changed). We break out of the
707 loop to handle the connection. */
708 close(listen_sock);
709 sock_in = newsock;
710 sock_out = newsock;
711 log_init(av0, options.log_level, options.log_facility, log_stderr);
712 break;
713 }
714 }
715
716 /* Parent. Stay in the loop. */
717 if (pid < 0)
718 error("fork: %.100s", strerror(errno));
719 else
720 debug("Forked child %d.", pid);
721
722 /* Mark that the key has been used (it was "given" to the child). */
723 key_used = 1;
724
725 arc4random_stir();
726
727 /* Close the new socket (the child is now taking care of it). */
728 close(newsock);
729 }
730 }
710 731
711 /* Mark that the key has been used (it was "given" to the child). */ 732 /* This is the child processing a new connection. */
712 key_used = 1; 733
734 /* Disable the key regeneration alarm. We will not regenerate the
735 key since we are no longer in a position to give it to anyone.
736 We will not restart on SIGHUP since it no longer makes sense. */
737 alarm(0);
738 signal(SIGALRM, SIG_DFL);
739 signal(SIGHUP, SIG_DFL);
740 signal(SIGTERM, SIG_DFL);
741 signal(SIGQUIT, SIG_DFL);
742 signal(SIGCHLD, SIG_DFL);
743
744 /* Set socket options for the connection. We want the socket to
745 close as fast as possible without waiting for anything. If the
746 connection is not a socket, these will do nothing. */
747 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on,
748 sizeof(on)); */
749 linger.l_onoff = 1;
750 linger.l_linger = 5;
751 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
752
753 /* Register our connection. This turns encryption off because we
754 do not have a key. */
755 packet_set_connection(sock_in, sock_out);
756
757 remote_port = get_remote_port();
758 remote_ip = get_remote_ipaddr();
759
760 /* Check whether logins are denied from this host. */
761#ifdef LIBWRAP
762 {
763 struct request_info req;
713 764
714 arc4random_stir(); 765 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
766 fromhost(&req);
715 767
716 /* Close the new socket (the child is now taking care of it). */ 768 if (!hosts_access(&req)) {
717 close(newsock); 769 close(sock_in);
770 close(sock_out);
771 refuse(&req);
772 }
773 verbose("Connection from %.500s port %d", eval_client(&req), remote_port);
718 } 774 }
719 }
720
721 /* This is the child processing a new connection. */
722
723 /* Disable the key regeneration alarm. We will not regenerate the key
724 since we are no longer in a position to give it to anyone. We will
725 not restart on SIGHUP since it no longer makes sense. */
726 alarm(0);
727 signal(SIGALRM, SIG_DFL);
728 signal(SIGHUP, SIG_DFL);
729 signal(SIGTERM, SIG_DFL);
730 signal(SIGQUIT, SIG_DFL);
731 signal(SIGCHLD, SIG_DFL);
732
733 /* Set socket options for the connection. We want the socket to close
734 as fast as possible without waiting for anything. If the connection
735 is not a socket, these will do nothing. */
736 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
737 linger.l_onoff = 1;
738 linger.l_linger = 5;
739 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *)&linger, sizeof(linger));
740
741 /* Register our connection. This turns encryption off because we do not
742 have a key. */
743 packet_set_connection(sock_in, sock_out);
744
745 remote_port = get_remote_port();
746
747 /* Check whether logins are denied from this host. */
748#ifdef LIBWRAP
749 {
750 struct request_info req;
751
752 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL);
753 fromhost(&req);
754
755 if (!hosts_access(&req)) {
756 close(sock_in);
757 close(sock_out);
758 refuse(&req);
759 }
760 log("Connection from %.500s port %d", eval_client(&req), remote_port);
761 }
762#else 775#else
763 /* Log the connection. */ 776 /* Log the connection. */
764 log("Connection from %.100s port %d", get_remote_ipaddr(), remote_port); 777 verbose("Connection from %.500s port %d", remote_ip, remote_port);
765#endif /* LIBWRAP */ 778#endif /* LIBWRAP */
766 779
767 /* We don\'t want to listen forever unless the other side successfully 780 /* We don\'t want to listen forever unless the other side
768 authenticates itself. So we set up an alarm which is cleared after 781 successfully authenticates itself. So we set up an alarm which
769 successful authentication. A limit of zero indicates no limit. 782 is cleared after successful authentication. A limit of zero
770 Note that we don\'t set the alarm in debugging mode; it is just annoying 783 indicates no limit. Note that we don\'t set the alarm in
771 to have the server exit just when you are about to discover the bug. */ 784 debugging mode; it is just annoying to have the server exit
772 signal(SIGALRM, grace_alarm_handler); 785 just when you are about to discover the bug. */
773 if (!debug_flag) 786 signal(SIGALRM, grace_alarm_handler);
774 alarm(options.login_grace_time); 787 if (!debug_flag)
775 788 alarm(options.login_grace_time);
776 /* Send our protocol version identification. */ 789
777 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", 790 if (client_version_string != NULL) {
778 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION); 791 /* we are exec'ed by sshd2, so skip exchange of protocol version */
779 if (write(sock_out, buf, strlen(buf)) != strlen(buf)) 792 strlcpy(buf, client_version_string, sizeof(buf));
780 fatal("Could not write ident string."); 793 } else {
781 794 /* Send our protocol version identification. */
782 /* Read other side\'s version identification. */ 795 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n",
783 for (i = 0; i < sizeof(buf) - 1; i++) 796 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION);
784 { 797 if (write(sock_out, buf, strlen(buf)) != strlen(buf))
785 if (read(sock_in, &buf[i], 1) != 1) 798 fatal("Could not write ident string to %s.", get_remote_ipaddr());
786 fatal("Did not receive ident string."); 799
787 if (buf[i] == '\r') 800 /* Read other side\'s version identification. */
788 { 801 for (i = 0; i < sizeof(buf) - 1; i++) {
789 buf[i] = '\n'; 802 if (read(sock_in, &buf[i], 1) != 1)
790 buf[i + 1] = 0; 803 fatal("Did not receive ident string from %s.", get_remote_ipaddr());
791 break; 804 if (buf[i] == '\r') {
805 buf[i] = '\n';
806 buf[i + 1] = 0;
807 break;
808 }
809 if (buf[i] == '\n') {
810 /* buf[i] == '\n' */
811 buf[i + 1] = 0;
812 break;
813 }
814 }
815 buf[sizeof(buf) - 1] = 0;
792 } 816 }
793 if (buf[i] == '\n') 817
794 { 818 /* Check that the versions match. In future this might accept
795 /* buf[i] == '\n' */ 819 several versions and set appropriate flags to handle them. */
796 buf[i + 1] = 0; 820 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor,
797 break; 821 remote_version) != 3) {
822 const char *s = "Protocol mismatch.\n";
823 (void) write(sock_out, s, strlen(s));
824 close(sock_in);
825 close(sock_out);
826 fatal("Bad protocol version identification '%.100s' from %s",
827 buf, get_remote_ipaddr());
828 }
829 debug("Client protocol version %d.%d; client software version %.100s",
830 remote_major, remote_minor, remote_version);
831 if (remote_major != PROTOCOL_MAJOR) {
832 const char *s = "Protocol major versions differ.\n";
833 (void) write(sock_out, s, strlen(s));
834 close(sock_in);
835 close(sock_out);
836 fatal("Protocol major versions differ for %s: %d vs. %d",
837 get_remote_ipaddr(),
838 PROTOCOL_MAJOR, remote_major);
798 } 839 }
799 } 840 /* Check that the client has sufficiently high software version. */
800 buf[sizeof(buf) - 1] = 0; 841 if (remote_major == 1 && remote_minor < 3)
801 842 packet_disconnect("Your ssh version is too old and is no longer supported. Please install a newer version.");
802 /* Check that the versions match. In future this might accept several 843
803 versions and set appropriate flags to handle them. */ 844 if (remote_major == 1 && remote_minor == 3) {
804 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor, 845 enable_compat13();
805 remote_version) != 3) 846 if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
806 { 847 debug("Agent forwarding disabled, remote version is not compatible.");
807 const char *s = "Protocol mismatch.\n"; 848 no_agent_forwarding_flag = 1;
808 (void) write(sock_out, s, strlen(s)); 849 }
809 close(sock_in); 850 }
810 close(sock_out); 851 /* Check that the connection comes from a privileged port. Rhosts-
811 fatal("Bad protocol version identification: %.100s", buf); 852 and Rhosts-RSA-Authentication only make sense from priviledged
812 } 853 programs. Of course, if the intruder has root access on his
813 debug("Client protocol version %d.%d; client software version %.100s", 854 local machine, he can connect from any port. So do not use
814 remote_major, remote_minor, remote_version); 855 these authentication methods from machines that you do not trust. */
815 if (remote_major != PROTOCOL_MAJOR) 856 if (remote_port >= IPPORT_RESERVED ||
816 { 857 remote_port < IPPORT_RESERVED / 2) {
817 const char *s = "Protocol major versions differ.\n"; 858 options.rhosts_authentication = 0;
818 (void) write(sock_out, s, strlen(s)); 859 options.rhosts_rsa_authentication = 0;
819 close(sock_in); 860 }
820 close(sock_out); 861 packet_set_nonblocking();
821 fatal("Protocol major versions differ: %d vs. %d", 862
822 PROTOCOL_MAJOR, remote_major); 863 /* Handle the connection. */
823 } 864 do_connection();
824
825 /* Check that the client has sufficiently high software version. */
826 if (remote_major == 1 && remote_minor < 3)
827 packet_disconnect("Your ssh version is too old and is no longer supported. Please install a newer version.");
828
829 if (remote_major == 1 && remote_minor == 3) {
830 enable_compat13();
831 if (strcmp(remote_version, "OpenSSH-1.1") != 0) {
832 debug("Agent forwarding disabled, remote version is not compatible.");
833 no_agent_forwarding_flag = 1;
834 }
835 }
836
837 /* Check that the connection comes from a privileged port.
838 Rhosts- and Rhosts-RSA-Authentication only make sense
839 from priviledged programs.
840 Of course, if the intruder has root access on his local machine,
841 he can connect from any port. So do not use these authentication
842 methods from machines that you do not trust. */
843 if (remote_port >= IPPORT_RESERVED ||
844 remote_port < IPPORT_RESERVED / 2)
845 {
846 options.rhosts_authentication = 0;
847 options.rhosts_rsa_authentication = 0;
848 }
849
850 packet_set_nonblocking();
851
852 /* Handle the connection. */
853 do_connection();
854 865
855#ifdef KRB4 866#ifdef KRB4
856 /* Cleanup user's ticket cache file. */ 867 /* Cleanup user's ticket cache file. */
857 if (options.kerberos_ticket_cleanup) 868 if (options.kerberos_ticket_cleanup)
858 (void) dest_tkt(); 869 (void) dest_tkt();
859#endif /* KRB4 */ 870#endif /* KRB4 */
860 871
861 /* Cleanup user's local Xauthority file. */ 872 /* Cleanup user's local Xauthority file. */
862 if (xauthfile) unlink(xauthfile); 873 if (xauthfile)
874 unlink(xauthfile);
863 875
864 /* The connection has been terminated. */ 876 /* The connection has been terminated. */
865 log("Closing connection to %.100s", inet_ntoa(sin.sin_addr)); 877 verbose("Closing connection to %.100s", remote_ip);
866 878
867#ifdef HAVE_LIBPAM 879#ifdef HAVE_LIBPAM
868 { 880 {
869 int retval; 881 int retval;
870
871 if (pamh != NULL)
872 {
873 debug("Closing PAM session.");
874 retval = pam_close_session((pam_handle_t *)pamh, 0);
875
876 debug("Terminating PAM library.");
877 if (pam_end((pam_handle_t *)pamh, retval) != PAM_SUCCESS)
878 log("Cannot release PAM authentication.");
879
880 fatal_remove_cleanup(&pam_cleanup_proc, NULL);
881 }
882 }
883#endif /* HAVE_LIBPAM */
884 882
885 packet_close(); 883 if (pamh != NULL) {
884 debug("Closing PAM session.");
885 retval = pam_close_session((pam_handle_t *)pamh, 0);
886 886
887 exit(0); 887 debug("Terminating PAM library.");
888} 888 if (pam_end((pam_handle_t *)pamh, retval) != PAM_SUCCESS)
889 log("Cannot release PAM authentication.");
890
891 fatal_remove_cleanup(&pam_cleanup_proc, NULL);
892 }
893 }
894#endif /* HAVE_LIBPAM */
889 895
890/* Process an incoming connection. Protocol version identifiers have already 896 packet_close();
891 been exchanged. This sends server key and performs the key exchange. 897 exit(0);
892 Server and host keys will no longer be needed after this functions. */ 898}
893 899
900/*
901 * Process an incoming connection. Protocol version identifiers have already
902 * been exchanged. This sends server key and performs the key exchange.
903 * Server and host keys will no longer be needed after this functions.
904 */
894void 905void
895do_connection() 906do_connection()
896{ 907{
897 int i, len; 908 int i, len;
898 BIGNUM *session_key_int; 909 BIGNUM *session_key_int;
899 unsigned char session_key[SSH_SESSION_KEY_LENGTH]; 910 unsigned char session_key[SSH_SESSION_KEY_LENGTH];
900 unsigned char check_bytes[8]; 911 unsigned char check_bytes[8];
901 char *user; 912 char *user;
902 unsigned int cipher_type, auth_mask, protocol_flags; 913 unsigned int cipher_type, auth_mask, protocol_flags;
903 int plen, slen; 914 int plen, slen;
904 u_int32_t rand = 0; 915 u_int32_t rand = 0;
905 916
906 /* Generate check bytes that the client must send back in the user packet 917 /* Generate check bytes that the client must send back in the user
907 in order for it to be accepted; this is used to defy ip spoofing 918 packet in order for it to be accepted; this is used to defy ip
908 attacks. Note that this only works against somebody doing IP spoofing 919 spoofing attacks. Note that this only works against somebody
909 from a remote machine; any machine on the local network can still see 920 doing IP spoofing from a remote machine; any machine on the
910 outgoing packets and catch the random cookie. This only affects 921 local network can still see outgoing packets and catch the
911 rhosts authentication, and this is one of the reasons why it is 922 random cookie. This only affects rhosts authentication, and
912 inherently insecure. */ 923 this is one of the reasons why it is inherently insecure. */
913 for (i = 0; i < 8; i++) { 924 for (i = 0; i < 8; i++) {
914 if (i % 4 == 0) 925 if (i % 4 == 0)
915 rand = arc4random(); 926 rand = arc4random();
916 check_bytes[i] = rand & 0xff; 927 check_bytes[i] = rand & 0xff;
917 rand >>= 8; 928 rand >>= 8;
918 } 929 }
919 930
920 /* Send our public key. We include in the packet 64 bits of random 931 /* Send our public key. We include in the packet 64 bits of
921 data that must be matched in the reply in order to prevent IP spoofing. */ 932 random data that must be matched in the reply in order to
922 packet_start(SSH_SMSG_PUBLIC_KEY); 933 prevent IP spoofing. */
923 for (i = 0; i < 8; i++) 934 packet_start(SSH_SMSG_PUBLIC_KEY);
924 packet_put_char(check_bytes[i]); 935 for (i = 0; i < 8; i++)
925 936 packet_put_char(check_bytes[i]);
926 /* Store our public server RSA key. */ 937
927 packet_put_int(BN_num_bits(public_key->n)); 938 /* Store our public server RSA key. */
928 packet_put_bignum(public_key->e); 939 packet_put_int(BN_num_bits(public_key->n));
929 packet_put_bignum(public_key->n); 940 packet_put_bignum(public_key->e);
930 941 packet_put_bignum(public_key->n);
931 /* Store our public host RSA key. */ 942
932 packet_put_int(BN_num_bits(sensitive_data.host_key->n)); 943 /* Store our public host RSA key. */
933 packet_put_bignum(sensitive_data.host_key->e); 944 packet_put_int(BN_num_bits(sensitive_data.host_key->n));
934 packet_put_bignum(sensitive_data.host_key->n); 945 packet_put_bignum(sensitive_data.host_key->e);
935 946 packet_put_bignum(sensitive_data.host_key->n);
936 /* Put protocol flags. */ 947
937 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN); 948 /* Put protocol flags. */
938 949 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
939 /* Declare which ciphers we support. */ 950
940 packet_put_int(cipher_mask()); 951 /* Declare which ciphers we support. */
941 952 packet_put_int(cipher_mask());
942 /* Declare supported authentication types. */ 953
943 auth_mask = 0; 954 /* Declare supported authentication types. */
944 if (options.rhosts_authentication) 955 auth_mask = 0;
945 auth_mask |= 1 << SSH_AUTH_RHOSTS; 956 if (options.rhosts_authentication)
946 if (options.rhosts_rsa_authentication) 957 auth_mask |= 1 << SSH_AUTH_RHOSTS;
947 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA; 958 if (options.rhosts_rsa_authentication)
948 if (options.rsa_authentication) 959 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
949 auth_mask |= 1 << SSH_AUTH_RSA; 960 if (options.rsa_authentication)
961 auth_mask |= 1 << SSH_AUTH_RSA;
950#ifdef KRB4 962#ifdef KRB4
951 if (options.kerberos_authentication) 963 if (options.kerberos_authentication)
952 auth_mask |= 1 << SSH_AUTH_KERBEROS; 964 auth_mask |= 1 << SSH_AUTH_KERBEROS;
953#endif 965#endif
954#ifdef AFS 966#ifdef AFS
955 if (options.kerberos_tgt_passing) 967 if (options.kerberos_tgt_passing)
956 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT; 968 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
957 if (options.afs_token_passing) 969 if (options.afs_token_passing)
958 auth_mask |= 1 << SSH_PASS_AFS_TOKEN; 970 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
959#endif 971#endif
960 if (options.password_authentication) 972#ifdef SKEY
961 auth_mask |= 1 << SSH_AUTH_PASSWORD; 973 if (options.skey_authentication == 1)
962 packet_put_int(auth_mask); 974 auth_mask |= 1 << SSH_AUTH_TIS;
963 975#endif
964 /* Send the packet and wait for it to be sent. */ 976 if (options.password_authentication)
965 packet_send(); 977 auth_mask |= 1 << SSH_AUTH_PASSWORD;
966 packet_write_wait(); 978 packet_put_int(auth_mask);
967 979
968 debug("Sent %d bit public key and %d bit host key.", 980 /* Send the packet and wait for it to be sent. */
969 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n)); 981 packet_send();
970 982 packet_write_wait();
971 /* Read clients reply (cipher type and session key). */ 983
972 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY); 984 debug("Sent %d bit public key and %d bit host key.",
973 985 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n));
974 /* Get cipher type. */ 986
975 cipher_type = packet_get_char(); 987 /* Read clients reply (cipher type and session key). */
976 988 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
977 /* Get check bytes from the packet. These must match those we sent earlier 989
978 with the public key packet. */ 990 /* Get cipher type. */
979 for (i = 0; i < 8; i++) 991 cipher_type = packet_get_char();
980 if (check_bytes[i] != packet_get_char()) 992
981 packet_disconnect("IP Spoofing check bytes do not match."); 993 /* Get check bytes from the packet. These must match those we
982 994 sent earlier with the public key packet. */
983 debug("Encryption type: %.200s", cipher_name(cipher_type)); 995 for (i = 0; i < 8; i++)
984 996 if (check_bytes[i] != packet_get_char())
985 /* Get the encrypted integer. */ 997 packet_disconnect("IP Spoofing check bytes do not match.");
986 session_key_int = BN_new(); 998
987 packet_get_bignum(session_key_int, &slen); 999 debug("Encryption type: %.200s", cipher_name(cipher_type));
988 1000
989 /* Get protocol flags. */ 1001 /* Get the encrypted integer. */
990 protocol_flags = packet_get_int(); 1002 session_key_int = BN_new();
991 packet_set_protocol_flags(protocol_flags); 1003 packet_get_bignum(session_key_int, &slen);
992 1004
993 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY); 1005 /* Get protocol flags. */
994 1006 protocol_flags = packet_get_int();
995 /* Decrypt it using our private server key and private host key (key with 1007 packet_set_protocol_flags(protocol_flags);
996 larger modulus first). */ 1008
997 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) 1009 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
998 { 1010
999 /* Private key has bigger modulus. */ 1011 /* Decrypt it using our private server key and private host key
1000 if (BN_num_bits(sensitive_data.private_key->n) < 1012 (key with larger modulus first). */
1001 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) { 1013 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) {
1002 fatal("do_connection: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d", 1014 /* Private key has bigger modulus. */
1003 BN_num_bits(sensitive_data.private_key->n), 1015 if (BN_num_bits(sensitive_data.private_key->n) <
1004 BN_num_bits(sensitive_data.host_key->n), 1016 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) {
1005 SSH_KEY_BITS_RESERVED); 1017 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1006 } 1018 get_remote_ipaddr(),
1007 1019 BN_num_bits(sensitive_data.private_key->n),
1008 rsa_private_decrypt(session_key_int, session_key_int, 1020 BN_num_bits(sensitive_data.host_key->n),
1009 sensitive_data.private_key); 1021 SSH_KEY_BITS_RESERVED);
1010 rsa_private_decrypt(session_key_int, session_key_int, 1022 }
1011 sensitive_data.host_key); 1023 rsa_private_decrypt(session_key_int, session_key_int,
1012 } 1024 sensitive_data.private_key);
1013 else 1025 rsa_private_decrypt(session_key_int, session_key_int,
1014 { 1026 sensitive_data.host_key);
1015 /* Host key has bigger modulus (or they are equal). */ 1027 } else {
1016 if (BN_num_bits(sensitive_data.host_key->n) < 1028 /* Host key has bigger modulus (or they are equal). */
1017 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) { 1029 if (BN_num_bits(sensitive_data.host_key->n) <
1018 fatal("do_connection: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d", 1030 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) {
1019 BN_num_bits(sensitive_data.host_key->n), 1031 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d",
1020 BN_num_bits(sensitive_data.private_key->n), 1032 get_remote_ipaddr(),
1021 SSH_KEY_BITS_RESERVED); 1033 BN_num_bits(sensitive_data.host_key->n),
1022 } 1034 BN_num_bits(sensitive_data.private_key->n),
1023 rsa_private_decrypt(session_key_int, session_key_int, 1035 SSH_KEY_BITS_RESERVED);
1024 sensitive_data.host_key); 1036 }
1025 rsa_private_decrypt(session_key_int, session_key_int, 1037 rsa_private_decrypt(session_key_int, session_key_int,
1026 sensitive_data.private_key); 1038 sensitive_data.host_key);
1027 } 1039 rsa_private_decrypt(session_key_int, session_key_int,
1028 1040 sensitive_data.private_key);
1029 /* Compute session id for this session. */ 1041 }
1030 compute_session_id(session_id, check_bytes, 1042
1031 sensitive_data.host_key->n, 1043 /* Compute session id for this session. */
1032 sensitive_data.private_key->n); 1044 compute_session_id(session_id, check_bytes,
1033 1045 sensitive_data.host_key->n,
1034 /* Extract session key from the decrypted integer. The key is in the 1046 sensitive_data.private_key->n);
1035 least significant 256 bits of the integer; the first byte of the 1047
1036 key is in the highest bits. */ 1048 /* Extract session key from the decrypted integer. The key is in
1037 BN_mask_bits(session_key_int, sizeof(session_key) * 8); 1049 the least significant 256 bits of the integer; the first byte
1038 len = BN_num_bytes(session_key_int); 1050 of the key is in the highest bits. */
1039 if (len < 0 || len > sizeof(session_key)) 1051 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1040 fatal("do_connection: bad len: session_key_int %d > sizeof(session_key) %d", 1052 len = BN_num_bytes(session_key_int);
1041 len, sizeof(session_key)); 1053 if (len < 0 || len > sizeof(session_key))
1042 memset(session_key, 0, sizeof(session_key)); 1054 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d",
1043 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len); 1055 get_remote_ipaddr(),
1044 1056 len, sizeof(session_key));
1045 /* Xor the first 16 bytes of the session key with the session id. */ 1057 memset(session_key, 0, sizeof(session_key));
1046 for (i = 0; i < 16; i++) 1058 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len);
1047 session_key[i] ^= session_id[i]; 1059
1048 1060 /* Xor the first 16 bytes of the session key with the session id. */
1049 /* Destroy the decrypted integer. It is no longer needed. */ 1061 for (i = 0; i < 16; i++)
1050 BN_clear_free(session_key_int); 1062 session_key[i] ^= session_id[i];
1051 1063
1052 /* Set the session key. From this on all communications will be 1064 /* Destroy the decrypted integer. It is no longer needed. */
1053 encrypted. */ 1065 BN_clear_free(session_key_int);
1054 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type); 1066
1055 1067 /* Set the session key. From this on all communications will be encrypted. */
1056 /* Destroy our copy of the session key. It is no longer needed. */ 1068 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1057 memset(session_key, 0, sizeof(session_key)); 1069
1058 1070 /* Destroy our copy of the session key. It is no longer needed. */
1059 debug("Received session key; encryption turned on."); 1071 memset(session_key, 0, sizeof(session_key));
1060 1072
1061 /* Send an acknowledgement packet. Note that this packet is sent 1073 debug("Received session key; encryption turned on.");
1062 encrypted. */ 1074
1063 packet_start(SSH_SMSG_SUCCESS); 1075 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1064 packet_send(); 1076 packet_start(SSH_SMSG_SUCCESS);
1065 packet_write_wait(); 1077 packet_send();
1066 1078 packet_write_wait();
1067 /* Get the name of the user that we wish to log in as. */ 1079
1068 packet_read_expect(&plen, SSH_CMSG_USER); 1080 /* Get the name of the user that we wish to log in as. */
1069 1081 packet_read_expect(&plen, SSH_CMSG_USER);
1070 /* Get the user name. */ 1082
1071 { 1083 /* Get the user name. */
1072 int ulen; 1084 {
1073 user = packet_get_string(&ulen); 1085 int ulen;
1074 packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER); 1086 user = packet_get_string(&ulen);
1075 } 1087 packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER);
1076 1088 }
1077 /* Destroy the private and public keys. They will no longer be needed. */ 1089
1078 RSA_free(public_key); 1090 /* Destroy the private and public keys. They will no longer be needed. */
1079 RSA_free(sensitive_data.private_key); 1091 RSA_free(public_key);
1080 RSA_free(sensitive_data.host_key); 1092 RSA_free(sensitive_data.private_key);
1081 1093 RSA_free(sensitive_data.host_key);
1082 setproctitle("%s", user);
1083 /* Do the authentication. */
1084 do_authentication(user);
1085}
1086 1094
1087/* Check if the user is allowed to log in via ssh. If user is listed in 1095 setproctitle("%s", user);
1088 DenyUsers or user's primary group is listed in DenyGroups, false will 1096 /* Do the authentication. */
1089 be returned. If AllowUsers isn't empty and user isn't listed there, or 1097 do_authentication(user);
1090 if AllowGroups isn't empty and user isn't listed there, false will be 1098}
1091 returned. Otherwise true is returned.
1092 XXX This function should also check if user has a valid shell */
1093 1099
1100/*
1101 * Check if the user is allowed to log in via ssh. If user is listed in
1102 * DenyUsers or user's primary group is listed in DenyGroups, false will
1103 * be returned. If AllowUsers isn't empty and user isn't listed there, or
1104 * if AllowGroups isn't empty and user isn't listed there, false will be
1105 * returned. Otherwise true is returned.
1106 * XXX This function should also check if user has a valid shell
1107 */
1094static int 1108static int
1095allowed_user(struct passwd *pw) 1109allowed_user(struct passwd * pw)
1096{ 1110{
1097 struct group *grp; 1111 struct group *grp;
1098 int i; 1112 int i;
1099 1113
1100 /* Shouldn't be called if pw is NULL, but better safe than sorry... */ 1114 /* Shouldn't be called if pw is NULL, but better safe than sorry... */
1101 if (!pw) 1115 if (!pw)
1102 return 0; 1116 return 0;
1103 1117
1104 /* XXX Should check for valid login shell */ 1118 /* XXX Should check for valid login shell */
1105 1119
1106 /* Return false if user is listed in DenyUsers */ 1120 /* Return false if user is listed in DenyUsers */
1107 if (options.num_deny_users > 0) 1121 if (options.num_deny_users > 0) {
1108 { 1122 if (!pw->pw_name)
1109 if (!pw->pw_name) 1123 return 0;
1110 return 0; 1124 for (i = 0; i < options.num_deny_users; i++)
1111 for (i = 0; i < options.num_deny_users; i++) 1125 if (match_pattern(pw->pw_name, options.deny_users[i]))
1112 if (match_pattern(pw->pw_name, options.deny_users[i])) 1126 return 0;
1113 return 0; 1127 }
1114 } 1128 /* Return false if AllowUsers isn't empty and user isn't listed
1115 1129 there */
1116 /* Return false if AllowUsers isn't empty and user isn't listed there */ 1130 if (options.num_allow_users > 0) {
1117 if (options.num_allow_users > 0) 1131 if (!pw->pw_name)
1118 { 1132 return 0;
1119 if (!pw->pw_name) 1133 for (i = 0; i < options.num_allow_users; i++)
1120 return 0; 1134 if (match_pattern(pw->pw_name, options.allow_users[i]))
1121 for (i = 0; i < options.num_allow_users; i++) 1135 break;
1122 if (match_pattern(pw->pw_name, options.allow_users[i])) 1136 /* i < options.num_allow_users iff we break for loop */
1123 break; 1137 if (i >= options.num_allow_users)
1124 /* i < options.num_allow_users iff we break for loop */ 1138 return 0;
1125 if (i >= options.num_allow_users) 1139 }
1126 return 0; 1140 /* Get the primary group name if we need it. Return false if it fails */
1127 } 1141 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) {
1128 1142 grp = getgrgid(pw->pw_gid);
1129 /* Get the primary group name if we need it. Return false if it fails */ 1143 if (!grp)
1130 if (options.num_deny_groups > 0 || options.num_allow_groups > 0 ) 1144 return 0;
1131 { 1145
1132 grp = getgrgid(pw->pw_gid); 1146 /* Return false if user's group is listed in DenyGroups */
1133 if (!grp) 1147 if (options.num_deny_groups > 0) {
1134 return 0; 1148 if (!grp->gr_name)
1135 1149 return 0;
1136 /* Return false if user's group is listed in DenyGroups */ 1150 for (i = 0; i < options.num_deny_groups; i++)
1137 if (options.num_deny_groups > 0) 1151 if (match_pattern(grp->gr_name, options.deny_groups[i]))
1138 { 1152 return 0;
1139 if (!grp->gr_name) 1153 }
1140 return 0; 1154 /* Return false if AllowGroups isn't empty and user's
1141 for (i = 0; i < options.num_deny_groups; i++) 1155 group isn't listed there */
1142 if (match_pattern(grp->gr_name, options.deny_groups[i])) 1156 if (options.num_allow_groups > 0) {
1143 return 0; 1157 if (!grp->gr_name)
1144 } 1158 return 0;
1145 1159 for (i = 0; i < options.num_allow_groups; i++)
1146 /* Return false if AllowGroups isn't empty and user's group isn't 1160 if (match_pattern(grp->gr_name, options.allow_groups[i]))
1147 listed there */ 1161 break;
1148 if (options.num_allow_groups > 0) 1162 /* i < options.num_allow_groups iff we break for
1149 { 1163 loop */
1150 if (!grp->gr_name) 1164 if (i >= options.num_allow_groups)
1151 return 0; 1165 return 0;
1152 for (i = 0; i < options.num_allow_groups; i++) 1166 }
1153 if (match_pattern(grp->gr_name, options.allow_groups[i])) 1167 }
1154 break; 1168 /* We found no reason not to let this user try to log on... */
1155 /* i < options.num_allow_groups iff we break for loop */ 1169 return 1;
1156 if (i >= options.num_allow_groups)
1157 return 0;
1158 }
1159 }
1160
1161 /* We found no reason not to let this user try to log on... */
1162 return 1;
1163} 1170}
1164 1171
1165/* Performs authentication of an incoming connection. Session key has already 1172/*
1166 been exchanged and encryption is enabled. User is the user name to log 1173 * Performs authentication of an incoming connection. Session key has already
1167 in as (received from the client). */ 1174 * been exchanged and encryption is enabled. User is the user name to log
1168 1175 * in as (received from the client).
1176 */
1169void 1177void
1170do_authentication(char *user) 1178do_authentication(char *user)
1171{ 1179{
1172 struct passwd *pw, pwcopy; 1180 struct passwd *pw, pwcopy;
1173 1181
1174#ifdef AFS 1182#ifdef AFS
1175 /* If machine has AFS, set process authentication group. */ 1183 /* If machine has AFS, set process authentication group. */
1176 if (k_hasafs()) { 1184 if (k_hasafs()) {
1177 k_setpag(); 1185 k_setpag();
1178 k_unlog(); 1186 k_unlog();
1179 } 1187 }
1180#endif /* AFS */ 1188#endif /* AFS */
1181 1189
1182 /* Verify that the user is a valid user. */ 1190 /* Verify that the user is a valid user. */
1183 pw = getpwnam(user); 1191 pw = getpwnam(user);
1184 if (!pw || !allowed_user(pw)) 1192 if (!pw || !allowed_user(pw))
1185 do_fake_authloop(user); 1193 do_fake_authloop(user);
1186 1194
1187 /* Take a copy of the returned structure. */ 1195 /* Take a copy of the returned structure. */
1188 memset(&pwcopy, 0, sizeof(pwcopy)); 1196 memset(&pwcopy, 0, sizeof(pwcopy));
1189 pwcopy.pw_name = xstrdup(pw->pw_name); 1197 pwcopy.pw_name = xstrdup(pw->pw_name);
1190 pwcopy.pw_passwd = xstrdup(pw->pw_passwd); 1198 pwcopy.pw_passwd = xstrdup(pw->pw_passwd);
1191 pwcopy.pw_uid = pw->pw_uid; 1199 pwcopy.pw_uid = pw->pw_uid;
1192 pwcopy.pw_gid = pw->pw_gid; 1200 pwcopy.pw_gid = pw->pw_gid;
1193 pwcopy.pw_dir = xstrdup(pw->pw_dir); 1201 pwcopy.pw_dir = xstrdup(pw->pw_dir);
1194 pwcopy.pw_shell = xstrdup(pw->pw_shell); 1202 pwcopy.pw_shell = xstrdup(pw->pw_shell);
1195 pw = &pwcopy; 1203 pw = &pwcopy;
1196 1204
1197#ifdef HAVE_LIBPAM 1205#ifdef HAVE_LIBPAM
1198 { 1206 {
1199 int pam_retval; 1207 int pam_retval;
1200 1208
1201 debug("Starting up PAM with username \"%.200s\"", pw->pw_name); 1209 debug("Starting up PAM with username \"%.200s\"", pw->pw_name);
1202 1210
1203 pam_retval = pam_start("sshd", pw->pw_name, &conv, (pam_handle_t**)&pamh); 1211 pam_retval = pam_start("sshd", pw->pw_name, &conv, (pam_handle_t**)&pamh);
1204 if (pam_retval != PAM_SUCCESS) 1212 if (pam_retval != PAM_SUCCESS)
1205 fatal("PAM initialisation failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval)); 1213 fatal("PAM initialisation failed: %.200s", PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
1206 1214
1207 fatal_add_cleanup(&pam_cleanup_proc, NULL); 1215 fatal_add_cleanup(&pam_cleanup_proc, NULL);
1208 } 1216 }
1209#endif 1217#endif
1210 1218
1211 /* If we are not running as root, the user must have the same uid as the 1219 /* If we are not running as root, the user must have the same uid
1212 server. */ 1220 as the server. */
1213 if (getuid() != 0 && pw->pw_uid != getuid()) 1221 if (getuid() != 0 && pw->pw_uid != getuid())
1214 packet_disconnect("Cannot change user when server not running as root."); 1222 packet_disconnect("Cannot change user when server not running as root.");
1215 1223
1216 debug("Attempting authentication for %.100s.", user); 1224 debug("Attempting authentication for %.100s.", user);
1217 1225
1218 /* If the user has no password, accept authentication immediately. */ 1226 /* If the user has no password, accept authentication immediately. */
1219 if (options.password_authentication && 1227 if (options.password_authentication &&
1220#ifdef KRB4 1228#ifdef KRB4
1221 (!options.kerberos_authentication || options.kerberos_or_local_passwd) && 1229 (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
1222#endif /* KRB4 */ 1230#endif /* KRB4 */
1223 auth_password(pw, "")) 1231 auth_password(pw, "")) {
1224 { 1232 /* Authentication with empty password succeeded. */
1225 /* Authentication with empty password succeeded. */ 1233 log("Login for user %s from %.100s, accepted without authentication.",
1226 debug("Login for user %.100s accepted without authentication.", user); 1234 pw->pw_name, get_remote_ipaddr());
1227 } else { 1235 } else {
1228 /* Loop until the user has been authenticated or the connection is closed, 1236 /* Loop until the user has been authenticated or the
1229 do_authloop() returns only if authentication is successfull */ 1237 connection is closed, do_authloop() returns only if
1230 do_authloop(pw); 1238 authentication is successfull */
1231 } 1239 do_authloop(pw);
1232 1240 }
1233 /* XXX log unified auth message */ 1241
1234 1242 /* Check if the user is logging in as root and root logins are disallowed. */
1235 /* Check if the user is logging in as root and root logins are disallowed. */ 1243 if (pw->pw_uid == 0 && !options.permit_root_login) {
1236 if (pw->pw_uid == 0 && !options.permit_root_login) 1244 if (forced_command)
1237 { 1245 log("Root login accepted for forced command.");
1238 if (forced_command) 1246 else
1239 log("Root login accepted for forced command."); 1247 packet_disconnect("ROOT LOGIN REFUSED FROM %.200s",
1240 else 1248 get_canonical_hostname());
1241 packet_disconnect("ROOT LOGIN REFUSED FROM %.200s", 1249 }
1242 get_canonical_hostname()); 1250 /* The user has been authenticated and accepted. */
1243 } 1251 packet_start(SSH_SMSG_SUCCESS);
1244 1252 packet_send();
1245 /* The user has been authenticated and accepted. */ 1253 packet_write_wait();
1246 packet_start(SSH_SMSG_SUCCESS); 1254
1247 packet_send(); 1255 /* Perform session preparation. */
1248 packet_write_wait(); 1256 do_authenticated(pw);
1249
1250 /* Perform session preparation. */
1251 do_authenticated(pw);
1252} 1257}
1253 1258
1254#define MAX_AUTH_FAILURES 5 1259#define AUTH_FAIL_MAX 6
1260#define AUTH_FAIL_LOG (AUTH_FAIL_MAX/2)
1261#define AUTH_FAIL_MSG "Too many authentication failures for %.100s"
1255 1262
1256/* read packets and try to authenticate local user *pw. 1263/*
1257 return if authentication is successfull */ 1264 * read packets and try to authenticate local user *pw.
1265 * return if authentication is successfull
1266 */
1258void 1267void
1259do_authloop(struct passwd *pw) 1268do_authloop(struct passwd * pw)
1260{ 1269{
1261 int authentication_failures = 0; 1270 int attempt = 0;
1262 unsigned int bits; 1271 unsigned int bits;
1263 BIGNUM *client_host_key_e, *client_host_key_n; 1272 BIGNUM *client_host_key_e, *client_host_key_n;
1264 BIGNUM *n; 1273 BIGNUM *n;
1265 char *client_user = NULL, *password = NULL; 1274 char *client_user = NULL, *password = NULL;
1266 int plen, dlen, nlen, ulen, elen; 1275 char user[1024];
1276 int plen, dlen, nlen, ulen, elen;
1277 int type = 0;
1278 void (*authlog) (const char *fmt,...) = verbose;
1267#ifdef HAVE_LIBPAM 1279#ifdef HAVE_LIBPAM
1268 int pam_retval; 1280 int pam_retval;
1269#endif /* HAVE_LIBPAM */ 1281#endif /* HAVE_LIBPAM */
1270 1282
1271 /* Indicate that authentication is needed. */ 1283 /* Indicate that authentication is needed. */
1272 packet_start(SSH_SMSG_FAILURE); 1284 packet_start(SSH_SMSG_FAILURE);
1273 packet_send(); 1285 packet_send();
1274 packet_write_wait(); 1286 packet_write_wait();
1275 1287
1276 for (;;) { 1288 for (attempt = 1;; attempt++) {
1277 int authenticated = 0; 1289 int authenticated = 0;
1290 strlcpy(user, "", sizeof user);
1278 1291
1279 /* Get a packet from the client. */ 1292 /* Get a packet from the client. */
1280 int type = packet_read(&plen); 1293 type = packet_read(&plen);
1281 1294
1282 /* Process the packet. */ 1295 /* Process the packet. */
1283 switch (type) 1296 switch (type) {
1284 {
1285#ifdef AFS 1297#ifdef AFS
1286 case SSH_CMSG_HAVE_KERBEROS_TGT: 1298 case SSH_CMSG_HAVE_KERBEROS_TGT:
1287 if (!options.kerberos_tgt_passing) 1299 if (!options.kerberos_tgt_passing) {
1288 { 1300 /* packet_get_all(); */
1289 /* packet_get_all(); */ 1301 verbose("Kerberos tgt passing disabled.");
1290 log("Kerberos tgt passing disabled."); 1302 break;
1291 break; 1303 } else {
1292 } 1304 /* Accept Kerberos tgt. */
1293 else { 1305 char *tgt = packet_get_string(&dlen);
1294 /* Accept Kerberos tgt. */ 1306 packet_integrity_check(plen, 4 + dlen, type);
1295 char *tgt = packet_get_string(&dlen); 1307 if (!auth_kerberos_tgt(pw, tgt))
1296 packet_integrity_check(plen, 4 + dlen, type); 1308 verbose("Kerberos tgt REFUSED for %s", pw->pw_name);
1297 if (!auth_kerberos_tgt(pw, tgt)) 1309 xfree(tgt);
1298 debug("Kerberos tgt REFUSED for %s", pw->pw_name); 1310 }
1299 xfree(tgt); 1311 continue;
1300 } 1312
1301 continue; 1313 case SSH_CMSG_HAVE_AFS_TOKEN:
1302 1314 if (!options.afs_token_passing || !k_hasafs()) {
1303 case SSH_CMSG_HAVE_AFS_TOKEN: 1315 /* packet_get_all(); */
1304 if (!options.afs_token_passing || !k_hasafs()) { 1316 verbose("AFS token passing disabled.");
1305 /* packet_get_all(); */ 1317 break;
1306 log("AFS token passing disabled."); 1318 } else {
1307 break; 1319 /* Accept AFS token. */
1308 } 1320 char *token_string = packet_get_string(&dlen);
1309 else { 1321 packet_integrity_check(plen, 4 + dlen, type);
1310 /* Accept AFS token. */ 1322 if (!auth_afs_token(pw, token_string))
1311 char *token_string = packet_get_string(&dlen); 1323 verbose("AFS token REFUSED for %s", pw->pw_name);
1312 packet_integrity_check(plen, 4 + dlen, type); 1324 xfree(token_string);
1313 if (!auth_afs_token(pw, token_string)) 1325 }
1314 debug("AFS token REFUSED for %s", pw->pw_name); 1326 continue;
1315 xfree(token_string);
1316 }
1317 continue;
1318#endif /* AFS */ 1327#endif /* AFS */
1319
1320#ifdef KRB4 1328#ifdef KRB4
1321 case SSH_CMSG_AUTH_KERBEROS: 1329 case SSH_CMSG_AUTH_KERBEROS:
1322 if (!options.kerberos_authentication) 1330 if (!options.kerberos_authentication) {
1323 { 1331 /* packet_get_all(); */
1324 /* packet_get_all(); */ 1332 verbose("Kerberos authentication disabled.");
1325 log("Kerberos authentication disabled."); 1333 break;
1326 break; 1334 } else {
1327 } 1335 /* Try Kerberos v4 authentication. */
1328 else { 1336 KTEXT_ST auth;
1329 /* Try Kerberos v4 authentication. */ 1337 char *tkt_user = NULL;
1330 KTEXT_ST auth; 1338 char *kdata = packet_get_string((unsigned int *) &auth.length);
1331 char *tkt_user = NULL; 1339 packet_integrity_check(plen, 4 + auth.length, type);
1332 char *kdata = packet_get_string((unsigned int *)&auth.length); 1340
1333 packet_integrity_check(plen, 4 + auth.length, type); 1341 if (auth.length < MAX_KTXT_LEN)
1334 1342 memcpy(auth.dat, kdata, auth.length);
1335 if (auth.length < MAX_KTXT_LEN) 1343 xfree(kdata);
1336 memcpy(auth.dat, kdata, auth.length); 1344
1337 xfree(kdata); 1345 authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user);
1338 1346
1339 authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user); 1347 if (authenticated) {
1340 1348 snprintf(user, sizeof user, " tktuser %s", tkt_user);
1341 log("Kerberos authentication %s%s for account %s from %s", 1349 xfree(tkt_user);
1342 authenticated ? "accepted " : "failed", 1350 }
1343 tkt_user != NULL ? tkt_user : "", 1351 }
1344 pw->pw_name, get_canonical_hostname()); 1352 break;
1345 if (authenticated)
1346 xfree(tkt_user);
1347 }
1348 break;
1349#endif /* KRB4 */ 1353#endif /* KRB4 */
1350 1354
1351 case SSH_CMSG_AUTH_RHOSTS: 1355 case SSH_CMSG_AUTH_RHOSTS:
1352 if (!options.rhosts_authentication) 1356 if (!options.rhosts_authentication) {
1353 { 1357 verbose("Rhosts authentication disabled.");
1354 log("Rhosts authentication disabled."); 1358 break;
1355 break; 1359 }
1356 } 1360 /* Get client user name. Note that we just have
1357 1361 to trust the client; this is one reason why
1358 /* Get client user name. Note that we just have to trust the client; 1362 rhosts authentication is insecure. (Another is
1359 this is one reason why rhosts authentication is insecure. 1363 IP-spoofing on a local network.) */
1360 (Another is IP-spoofing on a local network.) */ 1364 client_user = packet_get_string(&ulen);
1361 client_user = packet_get_string(&dlen); 1365 packet_integrity_check(plen, 4 + ulen, type);
1362 packet_integrity_check(plen, 4 + dlen, type); 1366
1363 1367 /* Try to authenticate using /etc/hosts.equiv and
1364 /* Try to authenticate using /etc/hosts.equiv and .rhosts. */ 1368 .rhosts. */
1365 authenticated = auth_rhosts(pw, client_user); 1369 authenticated = auth_rhosts(pw, client_user);
1366 1370
1367 log("Rhosts authentication %s for %.100s, remote %.100s on %.700s.", 1371 snprintf(user, sizeof user, " ruser %s", client_user);
1368 authenticated ? "accepted" : "failed",
1369 pw->pw_name, client_user, get_canonical_hostname());
1370#ifndef HAVE_LIBPAM 1372#ifndef HAVE_LIBPAM
1371 xfree(client_user); 1373 xfree(client_user);
1372#endif /* HAVE_LIBPAM */ 1374#endif /* HAVE_LIBPAM */
1373 break; 1375 break;
1374 1376
1375 case SSH_CMSG_AUTH_RHOSTS_RSA: 1377 case SSH_CMSG_AUTH_RHOSTS_RSA:
1376 if (!options.rhosts_rsa_authentication) 1378 if (!options.rhosts_rsa_authentication) {
1377 { 1379 verbose("Rhosts with RSA authentication disabled.");
1378 log("Rhosts with RSA authentication disabled."); 1380 break;
1379 break; 1381 }
1380 } 1382 /* Get client user name. Note that we just have
1381 1383 to trust the client; root on the client machine
1382 /* Get client user name. Note that we just have to trust 1384 can claim to be any user. */
1383 the client; root on the client machine can claim to be 1385 client_user = packet_get_string(&ulen);
1384 any user. */ 1386
1385 client_user = packet_get_string(&ulen); 1387 /* Get the client host key. */
1386 1388 client_host_key_e = BN_new();
1387 /* Get the client host key. */ 1389 client_host_key_n = BN_new();
1388 client_host_key_e = BN_new(); 1390 bits = packet_get_int();
1389 client_host_key_n = BN_new(); 1391 packet_get_bignum(client_host_key_e, &elen);
1390 bits = packet_get_int(); 1392 packet_get_bignum(client_host_key_n, &nlen);
1391 packet_get_bignum(client_host_key_e, &elen); 1393
1392 packet_get_bignum(client_host_key_n, &nlen); 1394 if (bits != BN_num_bits(client_host_key_n))
1393 1395 error("Warning: keysize mismatch for client_host_key: "
1394 if (bits != BN_num_bits(client_host_key_n)) 1396 "actual %d, announced %d", BN_num_bits(client_host_key_n), bits);
1395 error("Warning: keysize mismatch for client_host_key: " 1397 packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type);
1396 "actual %d, announced %d", BN_num_bits(client_host_key_n), bits); 1398
1397 packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type); 1399 authenticated = auth_rhosts_rsa(pw, client_user,
1398 1400 client_host_key_e, client_host_key_n);
1399 authenticated = auth_rhosts_rsa(pw, client_user, 1401 BN_clear_free(client_host_key_e);
1400 client_host_key_e, client_host_key_n); 1402 BN_clear_free(client_host_key_n);
1401 log("Rhosts authentication %s for %.100s, remote %.100s.", 1403
1402 authenticated ? "accepted" : "failed", 1404 snprintf(user, sizeof user, " ruser %s", client_user);
1403 pw->pw_name, client_user);
1404#ifndef HAVE_LIBPAM 1405#ifndef HAVE_LIBPAM
1405 xfree(client_user); 1406 xfree(client_user);
1406#endif /* HAVE_LIBPAM */ 1407#endif /* HAVE_LIBPAM */
1407 BN_clear_free(client_host_key_e); 1408 break;
1408 BN_clear_free(client_host_key_n); 1409
1409 break; 1410 case SSH_CMSG_AUTH_RSA:
1410 1411 if (!options.rsa_authentication) {
1411 case SSH_CMSG_AUTH_RSA: 1412 verbose("RSA authentication disabled.");
1412 if (!options.rsa_authentication) 1413 break;
1413 { 1414 }
1414 log("RSA authentication disabled."); 1415 /* RSA authentication requested. */
1415 break; 1416 n = BN_new();
1416 } 1417 packet_get_bignum(n, &nlen);
1417 1418 packet_integrity_check(plen, nlen, type);
1418 /* RSA authentication requested. */ 1419 authenticated = auth_rsa(pw, n);
1419 n = BN_new(); 1420 BN_clear_free(n);
1420 packet_get_bignum(n, &nlen); 1421 break;
1421 packet_integrity_check(plen, nlen, type); 1422
1422 1423 case SSH_CMSG_AUTH_PASSWORD:
1423 authenticated = auth_rsa(pw, n); 1424 if (!options.password_authentication) {
1424 log("RSA authentication %s for %.100s.", 1425 verbose("Password authentication disabled.");
1425 authenticated ? "accepted" : "failed", 1426 break;
1426 pw->pw_name); 1427 }
1427 BN_clear_free(n); 1428 /* Read user password. It is in plain text, but
1428 break; 1429 was transmitted over the encrypted channel so
1429 1430 it is not visible to an outside observer. */
1430 case SSH_CMSG_AUTH_PASSWORD: 1431 password = packet_get_string(&dlen);
1431 if (!options.password_authentication) 1432 packet_integrity_check(plen, 4 + dlen, type);
1432 { 1433
1433 log("Password authentication disabled.");
1434 break;
1435 }
1436
1437 /* Read user password. It is in plain text, but was transmitted
1438 over the encrypted channel so it is not visible to an outside
1439 observer. */
1440 password = packet_get_string(&dlen);
1441 packet_integrity_check(plen, 4 + dlen, type);
1442
1443#ifdef HAVE_LIBPAM 1434#ifdef HAVE_LIBPAM
1444 /* Do PAM auth with password */ 1435 /* Do PAM auth with password */
1445 pampasswd = password; 1436 pampasswd = password;
1446 pam_retval = pam_authenticate((pam_handle_t *)pamh, 0); 1437 pam_retval = pam_authenticate((pam_handle_t *)pamh, 0);
1447 if (pam_retval == PAM_SUCCESS) 1438 if (pam_retval == PAM_SUCCESS) {
1448 { 1439 log("PAM Password authentication accepted for user \"%.100s\"", pw->pw_name);
1449 log("PAM Password authentication accepted for user \"%.100s\"", pw->pw_name); 1440 authenticated = 1;
1450 authenticated = 1; 1441 break;
1451 break; 1442 }
1452 } 1443
1453 1444 log("PAM Password authentication for \"%.100s\" failed: %s",
1454 log("PAM Password authentication for \"%.100s\" failed: %s", 1445 pw->pw_name, PAM_STRERROR((pam_handle_t *)pamh, pam_retval));
1455 pw->pw_name, PAM_STRERROR((pam_handle_t *)pamh, pam_retval)); 1446 break;
1456 break;
1457#else /* HAVE_LIBPAM */ 1447#else /* HAVE_LIBPAM */
1458 /* Try authentication with the password. */ 1448 /* Try authentication with the password. */
1459 authenticated = auth_password(pw, password); 1449 authenticated = auth_password(pw, password);
1460 log("Password authentication %s for %.100s.", 1450
1461 authenticated ? "accepted" : "failed", 1451 memset(password, 0, strlen(password));
1462 pw->pw_name); 1452 xfree(password);
1463 1453 break;
1464 memset(password, 0, strlen(password));
1465 xfree(password);
1466 break;
1467#endif /* HAVE_LIBPAM */ 1454#endif /* HAVE_LIBPAM */
1468 1455
1469 case SSH_CMSG_AUTH_TIS: 1456#ifdef SKEY
1470 /* TIS Authentication is unsupported */ 1457 case SSH_CMSG_AUTH_TIS:
1471 log("TIS authentication disabled."); 1458 debug("rcvd SSH_CMSG_AUTH_TIS");
1472 break; 1459 if (options.skey_authentication == 1) {
1473 1460 char *skeyinfo = skey_keyinfo(pw->pw_name);
1474 default: 1461 if (skeyinfo == NULL) {
1475 /* Any unknown messages will be ignored (and failure returned) 1462 debug("generating fake skeyinfo for %.100s.", pw->pw_name);
1476 during authentication. */ 1463 skeyinfo = skey_fake_keyinfo(pw->pw_name);
1477 log("Unknown message during authentication: type %d", type); 1464 }
1478 break; /* Respond with a failure message. */ 1465 if (skeyinfo != NULL) {
1479 } 1466 /* we send our s/key- in
1480 1467 tis-challenge messages */
1481 if (authenticated) 1468 debug("sending challenge '%s'", skeyinfo);
1482 break; 1469 packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
1483 if (++authentication_failures >= MAX_AUTH_FAILURES) 1470 packet_put_string(skeyinfo, strlen(skeyinfo));
1484 packet_disconnect("Too many authentication failures for %.100s from %.200s", 1471 packet_send();
1485 pw->pw_name, get_canonical_hostname()); 1472 packet_write_wait();
1486 /* Send a message indicating that the authentication attempt failed. */ 1473 continue;
1487 packet_start(SSH_SMSG_FAILURE); 1474 }
1488 packet_send(); 1475 }
1489 packet_write_wait(); 1476 break;
1490 } 1477 case SSH_CMSG_AUTH_TIS_RESPONSE:
1478 debug("rcvd SSH_CMSG_AUTH_TIS_RESPONSE");
1479 if (options.skey_authentication == 1) {
1480 char *response = packet_get_string(&dlen);
1481 debug("skey response == '%s'", response);
1482 packet_integrity_check(plen, 4 + dlen, type);
1483 authenticated = (skey_haskey(pw->pw_name) == 0 &&
1484 skey_passcheck(pw->pw_name, response) != -1);
1485 xfree(response);
1486 }
1487 break;
1488#else
1489 case SSH_CMSG_AUTH_TIS:
1490 /* TIS Authentication is unsupported */
1491 log("TIS authentication unsupported.");
1492 break;
1493#endif
1494
1495 default:
1496 /* Any unknown messages will be ignored (and
1497 failure returned) during authentication. */
1498 log("Unknown message during authentication: type %d", type);
1499 break;
1500 }
1501
1502 /* Raise logging level */
1503 if (authenticated ||
1504 attempt == AUTH_FAIL_LOG ||
1505 type == SSH_CMSG_AUTH_PASSWORD)
1506 authlog = log;
1507
1508 authlog("%s %s for %.200s from %.200s port %d%s",
1509 authenticated ? "Accepted" : "Failed",
1510 get_authname(type),
1511 pw->pw_uid == 0 ? "ROOT" : pw->pw_name,
1512 get_remote_ipaddr(),
1513 get_remote_port(),
1514 user);
1491 1515
1492#ifdef HAVE_LIBPAM 1516#ifdef HAVE_LIBPAM
1493 do_pam_account_and_session(pw->pw_name, client_user, get_canonical_hostname()); 1517 do_pam_account_and_session(pw->pw_name, client_user,
1518 get_canonical_hostname());
1494 1519
1495 /* Clean up */ 1520 /* Clean up */
1496 if (client_user != NULL) 1521 if (client_user != NULL)
1497 xfree(client_user); 1522 xfree(client_user);
1498 1523
1499 if (password != NULL) 1524 if (password != NULL) {
1500 { 1525 memset(password, 0, strlen(password));
1501 memset(password, 0, strlen(password)); 1526 xfree(password);
1502 xfree(password); 1527 }
1503 }
1504#endif /* HAVE_LIBPAM */ 1528#endif /* HAVE_LIBPAM */
1529
1530 if (authenticated)
1531 return;
1532
1533 if (attempt > AUTH_FAIL_MAX)
1534 packet_disconnect(AUTH_FAIL_MSG, pw->pw_name);
1535
1536 /* Send a message indicating that the authentication attempt failed. */
1537 packet_start(SSH_SMSG_FAILURE);
1538 packet_send();
1539 packet_write_wait();
1540 }
1505} 1541}
1506 1542
1507/* The user does not exist or access is denied, 1543/*
1508 but fake indication that authentication is needed. */ 1544 * The user does not exist or access is denied,
1545 * but fake indication that authentication is needed.
1546 */
1509void 1547void
1510do_fake_authloop(char *user) 1548do_fake_authloop(char *user)
1511{ 1549{
1512 int authentication_failures = 0; 1550 int attempt = 0;
1513 1551
1514 /* Indicate that authentication is needed. */ 1552 log("Faking authloop for illegal user %.200s from %.200s port %d",
1515 packet_start(SSH_SMSG_FAILURE); 1553 user,
1516 packet_send(); 1554 get_remote_ipaddr(),
1517 packet_write_wait(); 1555 get_remote_port());
1518 1556
1519 /* Keep reading packets, and always respond with a failure. This is to 1557 /* Indicate that authentication is needed. */
1520 avoid disclosing whether such a user really exists. */ 1558 packet_start(SSH_SMSG_FAILURE);
1521 for (;;) 1559 packet_send();
1522 { 1560 packet_write_wait();
1523 /* Read a packet. This will not return if the client disconnects. */ 1561
1524 int plen; 1562 /* Keep reading packets, and always respond with a failure. This
1525 int type = packet_read(&plen); 1563 is to avoid disclosing whether such a user really exists. */
1564 for (attempt = 1;; attempt++) {
1565 /* Read a packet. This will not return if the client
1566 disconnects. */
1567 int plen;
1568 int type = packet_read(&plen);
1526#ifdef SKEY 1569#ifdef SKEY
1527 int passw_len; 1570 int dlen;
1528 char *password, *skeyinfo; 1571 char *password, *skeyinfo;
1529 if (options.password_authentication && 1572 if (options.password_authentication &&
1530 options.skey_authentication == 1 && 1573 options.skey_authentication == 1 &&
1531 type == SSH_CMSG_AUTH_PASSWORD && 1574 type == SSH_CMSG_AUTH_PASSWORD &&
1532 (password = packet_get_string(&passw_len)) != NULL && 1575 (password = packet_get_string(&dlen)) != NULL &&
1533 passw_len == 5 && 1576 dlen == 5 &&
1534 strncasecmp(password, "s/key", 5) == 0 && 1577 strncasecmp(password, "s/key", 5) == 0 &&
1535 (skeyinfo = skey_fake_keyinfo(user)) != NULL ){ 1578 (skeyinfo = skey_fake_keyinfo(user)) != NULL) {
1536 /* Send a fake s/key challenge. */ 1579 /* Send a fake s/key challenge. */
1537 packet_send_debug(skeyinfo); 1580 packet_send_debug(skeyinfo);
1538 } 1581 }
1539#endif 1582#endif
1540 if (++authentication_failures >= MAX_AUTH_FAILURES) 1583 if (attempt > AUTH_FAIL_MAX)
1541 packet_disconnect("Too many authentication failures for %.100s from %.200s", 1584 packet_disconnect(AUTH_FAIL_MSG, user);
1542 user, get_canonical_hostname()); 1585
1543 /* Send failure. This should be indistinguishable from a failed 1586 /* Send failure. This should be indistinguishable from a
1544 authentication. */ 1587 failed authentication. */
1545 packet_start(SSH_SMSG_FAILURE); 1588 packet_start(SSH_SMSG_FAILURE);
1546 packet_send(); 1589 packet_send();
1547 packet_write_wait(); 1590 packet_write_wait();
1548 } 1591 }
1549 /*NOTREACHED*/ 1592 /* NOTREACHED */
1550 abort(); 1593 abort();
1551} 1594}
1552 1595
1553 1596
1554/* Remove local Xauthority file. */ 1597/*
1598 * Remove local Xauthority file.
1599 */
1555static void 1600static void
1556xauthfile_cleanup_proc(void *ignore) 1601xauthfile_cleanup_proc(void *ignore)
1557{ 1602{
1558 debug("xauthfile_cleanup_proc called"); 1603 debug("xauthfile_cleanup_proc called");
1559 1604
1560 if (xauthfile != NULL) { 1605 if (xauthfile != NULL) {
1561 unlink(xauthfile); 1606 unlink(xauthfile);
1562 xfree(xauthfile); 1607 xfree(xauthfile);
1563 xauthfile = NULL; 1608 xauthfile = NULL;
1564 } 1609 }
1565} 1610}
1566 1611
1567/* Prepares for an interactive session. This is called after the user has 1612/*
1568 been successfully authenticated. During this message exchange, pseudo 1613 * Prepares for an interactive session. This is called after the user has
1569 terminals are allocated, X11, TCP/IP, and authentication agent forwardings 1614 * been successfully authenticated. During this message exchange, pseudo
1570 are requested, etc. */ 1615 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
1571 1616 * are requested, etc.
1572void do_authenticated(struct passwd *pw) 1617 */
1618void
1619do_authenticated(struct passwd * pw)
1573{ 1620{
1574 int type; 1621 int type;
1575 int compression_level = 0, enable_compression_after_reply = 0; 1622 int compression_level = 0, enable_compression_after_reply = 0;
1576 int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1; 1623 int have_pty = 0, ptyfd = -1, ttyfd = -1, xauthfd = -1;
1577 int row, col, xpixel, ypixel, screen; 1624 int row, col, xpixel, ypixel, screen;
1578 char ttyname[64]; 1625 char ttyname[64];
1579 char *command, *term = NULL, *display = NULL, *proto = NULL, *data = NULL; 1626 char *command, *term = NULL, *display = NULL, *proto = NULL,
1580 struct group *grp; 1627 *data = NULL;
1581 gid_t tty_gid; 1628 struct group *grp;
1582 mode_t tty_mode; 1629 gid_t tty_gid;
1583 int n_bytes; 1630 mode_t tty_mode;
1584 1631 int n_bytes;
1585 /* Cancel the alarm we set to limit the time taken for authentication. */ 1632
1586 alarm(0); 1633 /* Cancel the alarm we set to limit the time taken for
1587 1634 authentication. */
1588 /* Inform the channel mechanism that we are the server side and that 1635 alarm(0);
1589 the client may request to connect to any port at all. (The user could 1636
1590 do it anyway, and we wouldn\'t know what is permitted except by the 1637 /* Inform the channel mechanism that we are the server side and
1591 client telling us, so we can equally well trust the client not to request 1638 that the client may request to connect to any port at all.
1592 anything bogus.) */ 1639 (The user could do it anyway, and we wouldn\'t know what is
1593 channel_permit_all_opens(); 1640 permitted except by the client telling us, so we can equally
1594 1641 well trust the client not to request anything bogus.) */
1595 /* We stay in this loop until the client requests to execute a shell or a 1642 channel_permit_all_opens();
1596 command. */ 1643
1597 while (1) 1644 /* We stay in this loop until the client requests to execute a
1598 { 1645 shell or a command. */
1599 int plen, dlen; 1646 while (1) {
1600 1647 int plen, dlen;
1601 /* Get a packet from the client. */ 1648
1602 type = packet_read(&plen); 1649 /* Get a packet from the client. */
1603 1650 type = packet_read(&plen);
1604 /* Process the packet. */ 1651
1605 switch (type) 1652 /* Process the packet. */
1606 { 1653 switch (type) {
1607 case SSH_CMSG_REQUEST_COMPRESSION: 1654 case SSH_CMSG_REQUEST_COMPRESSION:
1608 packet_integrity_check(plen, 4, type); 1655 packet_integrity_check(plen, 4, type);
1609 compression_level = packet_get_int(); 1656 compression_level = packet_get_int();
1610 if (compression_level < 1 || compression_level > 9) 1657 if (compression_level < 1 || compression_level > 9) {
1611 { 1658 packet_send_debug("Received illegal compression level %d.",
1612 packet_send_debug("Received illegal compression level %d.", 1659 compression_level);
1613 compression_level); 1660 goto fail;
1614 goto fail; 1661 }
1615 } 1662 /* Enable compression after we have responded with SUCCESS. */
1616 /* Enable compression after we have responded with SUCCESS. */ 1663 enable_compression_after_reply = 1;
1617 enable_compression_after_reply = 1; 1664 break;
1618 break; 1665
1619 1666 case SSH_CMSG_REQUEST_PTY:
1620 case SSH_CMSG_REQUEST_PTY: 1667 if (no_pty_flag) {
1621 if (no_pty_flag) 1668 debug("Allocating a pty not permitted for this authentication.");
1622 { 1669 goto fail;
1623 debug("Allocating a pty not permitted for this authentication."); 1670 }
1624 goto fail; 1671 if (have_pty)
1625 } 1672 packet_disconnect("Protocol error: you already have a pty.");
1626 if (have_pty) 1673
1627 packet_disconnect("Protocol error: you already have a pty."); 1674 debug("Allocating pty.");
1628 1675
1629 debug("Allocating pty."); 1676 /* Allocate a pty and open it. */
1630 1677 if (!pty_allocate(&ptyfd, &ttyfd, ttyname)) {
1631 /* Allocate a pty and open it. */ 1678 error("Failed to allocate pty.");
1632 if (!pty_allocate(&ptyfd, &ttyfd, ttyname)) 1679 goto fail;
1633 { 1680 }
1634 error("Failed to allocate pty."); 1681 /* Determine the group to make the owner of the tty. */
1635 goto fail; 1682 grp = getgrnam("tty");
1636 } 1683 if (grp) {
1637 1684 tty_gid = grp->gr_gid;
1638 /* Determine the group to make the owner of the tty. */ 1685 tty_mode = S_IRUSR | S_IWUSR | S_IWGRP;
1639 grp = getgrnam("tty"); 1686 } else {
1640 if (grp) 1687 tty_gid = pw->pw_gid;
1641 { 1688 tty_mode = S_IRUSR | S_IWUSR | S_IWGRP | S_IWOTH;
1642 tty_gid = grp->gr_gid; 1689 }
1643 tty_mode = S_IRUSR|S_IWUSR|S_IWGRP; 1690
1644 } 1691 /* Change ownership of the tty. */
1645 else 1692 if (chown(ttyname, pw->pw_uid, tty_gid) < 0)
1646 { 1693 fatal("chown(%.100s, %d, %d) failed: %.100s",
1647 tty_gid = pw->pw_gid; 1694 ttyname, pw->pw_uid, tty_gid, strerror(errno));
1648 tty_mode = S_IRUSR|S_IWUSR|S_IWGRP|S_IWOTH; 1695 if (chmod(ttyname, tty_mode) < 0)
1649 } 1696 fatal("chmod(%.100s, 0%o) failed: %.100s",
1650 1697 ttyname, tty_mode, strerror(errno));
1651 /* Change ownership of the tty. */ 1698
1652 if (chown(ttyname, pw->pw_uid, tty_gid) < 0) 1699 /* Get TERM from the packet. Note that the value may be of arbitrary length. */
1653 fatal("chown(%.100s, %d, %d) failed: %.100s", 1700 term = packet_get_string(&dlen);
1654 ttyname, pw->pw_uid, tty_gid, strerror(errno)); 1701 packet_integrity_check(dlen, strlen(term), type);
1655 if (chmod(ttyname, tty_mode) < 0) 1702 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */
1656 fatal("chmod(%.100s, 0%o) failed: %.100s", 1703 /* Remaining bytes */
1657 ttyname, tty_mode, strerror(errno)); 1704 n_bytes = plen - (4 + dlen + 4 * 4);
1658 1705
1659 /* Get TERM from the packet. Note that the value may be of arbitrary 1706 if (strcmp(term, "") == 0)
1660 length. */ 1707 term = NULL;
1661 1708
1662 term = packet_get_string(&dlen); 1709 /* Get window size from the packet. */
1663 packet_integrity_check(dlen, strlen(term), type); 1710 row = packet_get_int();
1664 /* packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); */ 1711 col = packet_get_int();
1665 /* Remaining bytes */ 1712 xpixel = packet_get_int();
1666 n_bytes = plen - (4 + dlen + 4*4); 1713 ypixel = packet_get_int();
1667 1714 pty_change_window_size(ptyfd, row, col, xpixel, ypixel);
1668 if (strcmp(term, "") == 0) 1715
1669 term = NULL; 1716 /* Get tty modes from the packet. */
1670 1717 tty_parse_modes(ttyfd, &n_bytes);
1671 /* Get window size from the packet. */ 1718 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type);
1672 row = packet_get_int(); 1719
1673 col = packet_get_int(); 1720 /* Indicate that we now have a pty. */
1674 xpixel = packet_get_int(); 1721 have_pty = 1;
1675 ypixel = packet_get_int(); 1722 break;
1676 pty_change_window_size(ptyfd, row, col, xpixel, ypixel); 1723
1677 1724 case SSH_CMSG_X11_REQUEST_FORWARDING:
1678 /* Get tty modes from the packet. */ 1725 if (!options.x11_forwarding) {
1679 tty_parse_modes(ttyfd, &n_bytes); 1726 packet_send_debug("X11 forwarding disabled in server configuration file.");
1680 packet_integrity_check(plen, 4 + dlen + 4*4 + n_bytes, type); 1727 goto fail;
1681 1728 }
1682 /* Indicate that we now have a pty. */
1683 have_pty = 1;
1684 break;
1685
1686 case SSH_CMSG_X11_REQUEST_FORWARDING:
1687 if (!options.x11_forwarding)
1688 {
1689 packet_send_debug("X11 forwarding disabled in server configuration file.");
1690 goto fail;
1691 }
1692#ifdef XAUTH_PATH 1729#ifdef XAUTH_PATH
1693 if (no_x11_forwarding_flag) 1730 if (no_x11_forwarding_flag) {
1694 { 1731 packet_send_debug("X11 forwarding not permitted for this authentication.");
1695 packet_send_debug("X11 forwarding not permitted for this authentication."); 1732 goto fail;
1696 goto fail; 1733 }
1697 } 1734 debug("Received request for X11 forwarding with auth spoofing.");
1698 debug("Received request for X11 forwarding with auth spoofing."); 1735 if (display)
1699 if (display) 1736 packet_disconnect("Protocol error: X11 display already set.");
1700 packet_disconnect("Protocol error: X11 display already set."); 1737 {
1701 { 1738 int proto_len, data_len;
1702 int proto_len, data_len; 1739 proto = packet_get_string(&proto_len);
1703 proto = packet_get_string(&proto_len); 1740 data = packet_get_string(&data_len);
1704 data = packet_get_string(&data_len); 1741 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type);
1705 packet_integrity_check(plen, 4+proto_len + 4+data_len + 4, type); 1742 }
1706 } 1743 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER)
1707 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER) 1744 screen = packet_get_int();
1708 screen = packet_get_int(); 1745 else
1709 else 1746 screen = 0;
1710 screen = 0; 1747 display = x11_create_display_inet(screen);
1711 display = x11_create_display_inet(screen); 1748 if (!display)
1712 if (!display) 1749 goto fail;
1713 goto fail; 1750
1714 1751 /* Setup to always have a local .Xauthority. */
1715 /* Setup to always have a local .Xauthority. */ 1752 xauthfile = xmalloc(MAXPATHLEN);
1716 xauthfile = xmalloc(MAXPATHLEN); 1753 snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX");
1717 snprintf(xauthfile, MAXPATHLEN, "/tmp/XauthXXXXXX"); 1754
1718 1755 if ((xauthfd = mkstemp(xauthfile)) != -1) {
1719 if ((xauthfd = mkstemp(xauthfile)) != -1) { 1756 fchown(xauthfd, pw->pw_uid, pw->pw_gid);
1720 fchown(xauthfd, pw->pw_uid, pw->pw_gid); 1757 close(xauthfd);
1721 close(xauthfd); 1758 fatal_add_cleanup(xauthfile_cleanup_proc, NULL);
1722 fatal_add_cleanup(xauthfile_cleanup_proc, NULL); 1759 } else {
1723 } 1760 xfree(xauthfile);
1724 else { 1761 xauthfile = NULL;
1725 xfree(xauthfile); 1762 }
1726 xauthfile = NULL; 1763 break;
1727 }
1728 break;
1729#else /* XAUTH_PATH */ 1764#else /* XAUTH_PATH */
1730 /* No xauth program; we won't accept forwarding with spoofing. */ 1765 packet_send_debug("No xauth program; cannot forward with spoofing.");
1731 packet_send_debug("No xauth program; cannot forward with spoofing."); 1766 goto fail;
1732 goto fail;
1733#endif /* XAUTH_PATH */ 1767#endif /* XAUTH_PATH */
1734 1768
1735 case SSH_CMSG_AGENT_REQUEST_FORWARDING: 1769 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
1736 if (no_agent_forwarding_flag) 1770 if (no_agent_forwarding_flag) {
1737 { 1771 debug("Authentication agent forwarding not permitted for this authentication.");
1738 debug("Authentication agent forwarding not permitted for this authentication."); 1772 goto fail;
1739 goto fail; 1773 }
1740 } 1774 debug("Received authentication agent forwarding request.");
1741 debug("Received authentication agent forwarding request."); 1775 auth_input_request_forwarding(pw);
1742 auth_input_request_forwarding(pw); 1776 break;
1743 break; 1777
1744 1778 case SSH_CMSG_PORT_FORWARD_REQUEST:
1745 case SSH_CMSG_PORT_FORWARD_REQUEST: 1779 if (no_port_forwarding_flag) {
1746 if (no_port_forwarding_flag) 1780 debug("Port forwarding not permitted for this authentication.");
1747 { 1781 goto fail;
1748 debug("Port forwarding not permitted for this authentication."); 1782 }
1749 goto fail; 1783 debug("Received TCP/IP port forwarding request.");
1750 } 1784 channel_input_port_forward_request(pw->pw_uid == 0);
1751 debug("Received TCP/IP port forwarding request."); 1785 break;
1752 channel_input_port_forward_request(pw->pw_uid == 0); 1786
1753 break; 1787 case SSH_CMSG_MAX_PACKET_SIZE:
1754 1788 if (packet_set_maxsize(packet_get_int()) < 0)
1755 case SSH_CMSG_MAX_PACKET_SIZE: 1789 goto fail;
1756 if (packet_set_maxsize(packet_get_int()) < 0) 1790 break;
1757 goto fail; 1791
1758 break; 1792 case SSH_CMSG_EXEC_SHELL:
1759 1793 /* Set interactive/non-interactive mode. */
1760 case SSH_CMSG_EXEC_SHELL: 1794 packet_set_interactive(have_pty || display != NULL,
1761 /* Set interactive/non-interactive mode. */ 1795 options.keepalives);
1762 packet_set_interactive(have_pty || display != NULL, 1796
1763 options.keepalives); 1797 if (forced_command != NULL)
1764 1798 goto do_forced_command;
1765 if (forced_command != NULL) 1799 debug("Forking shell.");
1766 goto do_forced_command; 1800 packet_integrity_check(plen, 0, type);
1767 debug("Forking shell."); 1801 if (have_pty)
1768 packet_integrity_check(plen, 0, type); 1802 do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1769 if (have_pty) 1803 else
1770 do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto, 1804 do_exec_no_pty(NULL, pw, display, proto, data);
1771 data); 1805 return;
1772 else 1806
1773 do_exec_no_pty(NULL, pw, display, proto, data); 1807 case SSH_CMSG_EXEC_CMD:
1774 return; 1808 /* Set interactive/non-interactive mode. */
1775 1809 packet_set_interactive(have_pty || display != NULL,
1776 case SSH_CMSG_EXEC_CMD: 1810 options.keepalives);
1777 /* Set interactive/non-interactive mode. */ 1811
1778 packet_set_interactive(have_pty || display != NULL, 1812 if (forced_command != NULL)
1779 options.keepalives); 1813 goto do_forced_command;
1780 1814 /* Get command from the packet. */
1781 if (forced_command != NULL) 1815 {
1782 goto do_forced_command; 1816 int dlen;
1783 /* Get command from the packet. */ 1817 command = packet_get_string(&dlen);
1784 { 1818 debug("Executing command '%.500s'", command);
1785 int dlen; 1819 packet_integrity_check(plen, 4 + dlen, type);
1786 command = packet_get_string(&dlen); 1820 }
1787 debug("Executing command '%.500s'", command); 1821 if (have_pty)
1788 packet_integrity_check(plen, 4 + dlen, type); 1822 do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1789 } 1823 else
1790 if (have_pty) 1824 do_exec_no_pty(command, pw, display, proto, data);
1791 do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display, 1825 xfree(command);
1792 proto, data); 1826 return;
1793 else 1827
1794 do_exec_no_pty(command, pw, display, proto, data); 1828 default:
1795 xfree(command); 1829 /* Any unknown messages in this phase are ignored,
1796 return; 1830 and a failure message is returned. */
1797 1831 log("Unknown packet type received after authentication: %d", type);
1798 default: 1832 goto fail;
1799 /* Any unknown messages in this phase are ignored, and a failure 1833 }
1800 message is returned. */
1801 log("Unknown packet type received after authentication: %d", type);
1802 goto fail;
1803 }
1804 1834
1805 /* The request was successfully processed. */ 1835 /* The request was successfully processed. */
1806 packet_start(SSH_SMSG_SUCCESS); 1836 packet_start(SSH_SMSG_SUCCESS);
1807 packet_send(); 1837 packet_send();
1808 packet_write_wait(); 1838 packet_write_wait();
1809 1839
1810 /* Enable compression now that we have replied if appropriate. */ 1840 /* Enable compression now that we have replied if appropriate. */
1811 if (enable_compression_after_reply) 1841 if (enable_compression_after_reply) {
1812 { 1842 enable_compression_after_reply = 0;
1813 enable_compression_after_reply = 0; 1843 packet_start_compression(compression_level);
1814 packet_start_compression(compression_level); 1844 }
1815 } 1845 continue;
1816 1846
1817 continue; 1847fail:
1818 1848 /* The request failed. */
1819 fail: 1849 packet_start(SSH_SMSG_FAILURE);
1820 /* The request failed. */ 1850 packet_send();
1821 packet_start(SSH_SMSG_FAILURE); 1851 packet_write_wait();
1822 packet_send(); 1852 continue;
1823 packet_write_wait();
1824 continue;
1825
1826 do_forced_command:
1827 /* There is a forced command specified for this login. Execute it. */
1828 debug("Executing forced command: %.900s", forced_command);
1829 if (have_pty)
1830 do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display,
1831 proto, data);
1832 else
1833 do_exec_no_pty(forced_command, pw, display, proto, data);
1834 return;
1835 }
1836}
1837 1853
1838/* This is called to fork and execute a command when we have no tty. This 1854do_forced_command:
1839 will call do_child from the child, and server_loop from the parent after 1855 /* There is a forced command specified for this login.
1840 setting up file descriptors and such. */ 1856 Execute it. */
1857 debug("Executing forced command: %.900s", forced_command);
1858 if (have_pty)
1859 do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data);
1860 else
1861 do_exec_no_pty(forced_command, pw, display, proto, data);
1862 return;
1863 }
1864}
1841 1865
1842void do_exec_no_pty(const char *command, struct passwd *pw, 1866/*
1843 const char *display, const char *auth_proto, 1867 * This is called to fork and execute a command when we have no tty. This
1844 const char *auth_data) 1868 * will call do_child from the child, and server_loop from the parent after
1845{ 1869 * setting up file descriptors and such.
1846 int pid; 1870 */
1871void
1872do_exec_no_pty(const char *command, struct passwd * pw,
1873 const char *display, const char *auth_proto,
1874 const char *auth_data)
1875{
1876 int pid;
1847 1877
1848#ifdef USE_PIPES 1878#ifdef USE_PIPES
1849 int pin[2], pout[2], perr[2]; 1879 int pin[2], pout[2], perr[2];
1850 /* Allocate pipes for communicating with the program. */ 1880 /* Allocate pipes for communicating with the program. */
1851 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0) 1881 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0)
1852 packet_disconnect("Could not create pipes: %.100s", 1882 packet_disconnect("Could not create pipes: %.100s",
1853 strerror(errno)); 1883 strerror(errno));
1854#else /* USE_PIPES */ 1884#else /* USE_PIPES */
1855 int inout[2], err[2]; 1885 int inout[2], err[2];
1856 /* Uses socket pairs to communicate with the program. */ 1886 /* Uses socket pairs to communicate with the program. */
1857 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 || 1887 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 ||
1858 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) 1888 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0)
1859 packet_disconnect("Could not create socket pairs: %.100s", 1889 packet_disconnect("Could not create socket pairs: %.100s",
1860 strerror(errno)); 1890 strerror(errno));
1861#endif /* USE_PIPES */ 1891#endif /* USE_PIPES */
1862
1863 setproctitle("%s@notty", pw->pw_name);
1864 1892
1865 /* Fork the child. */ 1893 setproctitle("%s@notty", pw->pw_name);
1866 if ((pid = fork()) == 0)
1867 {
1868 /* Child. Reinitialize the log since the pid has changed. */
1869 log_init(av0, options.log_level, options.log_facility, log_stderr);
1870 1894
1871 /* Create a new session and process group since the 4.4BSD setlogin() 1895 /* Fork the child. */
1872 affects the entire process group. */ 1896 if ((pid = fork()) == 0) {
1873 if (setsid() < 0) 1897 /* Child. Reinitialize the log since the pid has changed. */
1874 error("setsid failed: %.100s", strerror(errno)); 1898 log_init(av0, options.log_level, options.log_facility, log_stderr);
1899
1900 /* Create a new session and process group since the 4.4BSD
1901 setlogin() affects the entire process group. */
1902 if (setsid() < 0)
1903 error("setsid failed: %.100s", strerror(errno));
1875 1904
1876#ifdef USE_PIPES 1905#ifdef USE_PIPES
1877 /* Redirect stdin. We close the parent side of the socket pair, 1906 /* Redirect stdin. We close the parent side of the socket
1878 and make the child side the standard input. */ 1907 pair, and make the child side the standard input. */
1879 close(pin[1]); 1908 close(pin[1]);
1880 if (dup2(pin[0], 0) < 0) 1909 if (dup2(pin[0], 0) < 0)
1881 perror("dup2 stdin"); 1910 perror("dup2 stdin");
1882 close(pin[0]); 1911 close(pin[0]);
1883 1912
1884 /* Redirect stdout. */ 1913 /* Redirect stdout. */
1885 close(pout[0]); 1914 close(pout[0]);
1886 if (dup2(pout[1], 1) < 0) 1915 if (dup2(pout[1], 1) < 0)
1887 perror("dup2 stdout"); 1916 perror("dup2 stdout");
1888 close(pout[1]); 1917 close(pout[1]);
1889 1918
1890 /* Redirect stderr. */ 1919 /* Redirect stderr. */
1891 close(perr[0]); 1920 close(perr[0]);
1892 if (dup2(perr[1], 2) < 0) 1921 if (dup2(perr[1], 2) < 0)
1893 perror("dup2 stderr"); 1922 perror("dup2 stderr");
1894 close(perr[1]); 1923 close(perr[1]);
1895#else /* USE_PIPES */ 1924#else /* USE_PIPES */
1896 /* Redirect stdin, stdout, and stderr. Stdin and stdout will use the 1925 /* Redirect stdin, stdout, and stderr. Stdin and stdout
1897 same socket, as some programs (particularly rdist) seem to depend 1926 will use the same socket, as some programs
1898 on it. */ 1927 (particularly rdist) seem to depend on it. */
1899 close(inout[1]); 1928 close(inout[1]);
1900 close(err[1]); 1929 close(err[1]);
1901 if (dup2(inout[0], 0) < 0) /* stdin */ 1930 if (dup2(inout[0], 0) < 0) /* stdin */
1902 perror("dup2 stdin"); 1931 perror("dup2 stdin");
1903 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */ 1932 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */
1904 perror("dup2 stdout"); 1933 perror("dup2 stdout");
1905 if (dup2(err[0], 2) < 0) /* stderr */ 1934 if (dup2(err[0], 2) < 0) /* stderr */
1906 perror("dup2 stderr"); 1935 perror("dup2 stderr");
1907#endif /* USE_PIPES */ 1936#endif /* USE_PIPES */
1908 1937
1909 /* Do processing for the child (exec command etc). */ 1938 /* Do processing for the child (exec command etc). */
1910 do_child(command, pw, NULL, display, auth_proto, auth_data, NULL); 1939 do_child(command, pw, NULL, display, auth_proto, auth_data, NULL);
1911 /*NOTREACHED*/ 1940 /* NOTREACHED */
1912 } 1941 }
1913 if (pid < 0) 1942 if (pid < 0)
1914 packet_disconnect("fork failed: %.100s", strerror(errno)); 1943 packet_disconnect("fork failed: %.100s", strerror(errno));
1915#ifdef USE_PIPES 1944#ifdef USE_PIPES
1916 /* We are the parent. Close the child sides of the pipes. */ 1945 /* We are the parent. Close the child sides of the pipes. */
1917 close(pin[0]); 1946 close(pin[0]);
1918 close(pout[1]); 1947 close(pout[1]);
1919 close(perr[1]); 1948 close(perr[1]);
1920 1949
1921 /* Enter the interactive session. */ 1950 /* Enter the interactive session. */
1922 server_loop(pid, pin[1], pout[0], perr[0]); 1951 server_loop(pid, pin[1], pout[0], perr[0]);
1923 /* server_loop has closed pin[1], pout[1], and perr[1]. */ 1952 /* server_loop has closed pin[1], pout[1], and perr[1]. */
1924#else /* USE_PIPES */ 1953#else /* USE_PIPES */
1925 /* We are the parent. Close the child sides of the socket pairs. */ 1954 /* We are the parent. Close the child sides of the socket pairs. */
1926 close(inout[0]); 1955 close(inout[0]);
1927 close(err[0]); 1956 close(err[0]);
1928 1957
1929 /* Enter the interactive session. Note: server_loop must be able to handle 1958 /* Enter the interactive session. Note: server_loop must be able
1930 the case that fdin and fdout are the same. */ 1959 to handle the case that fdin and fdout are the same. */
1931 server_loop(pid, inout[1], inout[1], err[1]); 1960 server_loop(pid, inout[1], inout[1], err[1]);
1932 /* server_loop has closed inout[1] and err[1]. */ 1961 /* server_loop has closed inout[1] and err[1]. */
1933#endif /* USE_PIPES */ 1962#endif /* USE_PIPES */
1934} 1963}
1935 1964
1936struct pty_cleanup_context 1965struct pty_cleanup_context {
1937{ 1966 const char *ttyname;
1938 const char *ttyname; 1967 int pid;
1939 int pid;
1940}; 1968};
1941 1969
1942/* Function to perform cleanup if we get aborted abnormally (e.g., due to a 1970/*
1943 dropped connection). */ 1971 * Function to perform cleanup if we get aborted abnormally (e.g., due to a
1944 1972 * dropped connection).
1945void pty_cleanup_proc(void *context) 1973 */
1974void
1975pty_cleanup_proc(void *context)
1946{ 1976{
1947 struct pty_cleanup_context *cu = context; 1977 struct pty_cleanup_context *cu = context;
1948 1978
1949 debug("pty_cleanup_proc called"); 1979 debug("pty_cleanup_proc called");
1950 1980
1951 /* Record that the user has logged out. */ 1981 /* Record that the user has logged out. */
1952 record_logout(cu->pid, cu->ttyname); 1982 record_logout(cu->pid, cu->ttyname);
1953 1983
1954 /* Release the pseudo-tty. */ 1984 /* Release the pseudo-tty. */
1955 pty_release(cu->ttyname); 1985 pty_release(cu->ttyname);
1956} 1986}
1957 1987
1958/* This is called to fork and execute a command when we have a tty. This 1988/*
1959 will call do_child from the child, and server_loop from the parent after 1989 * This is called to fork and execute a command when we have a tty. This
1960 setting up file descriptors, controlling tty, updating wtmp, utmp, 1990 * will call do_child from the child, and server_loop from the parent after
1961 lastlog, and other such operations. */ 1991 * setting up file descriptors, controlling tty, updating wtmp, utmp,
1962 1992 * lastlog, and other such operations.
1963void do_exec_pty(const char *command, int ptyfd, int ttyfd, 1993 */
1964 const char *ttyname, struct passwd *pw, const char *term, 1994void
1965 const char *display, const char *auth_proto, 1995do_exec_pty(const char *command, int ptyfd, int ttyfd,
1966 const char *auth_data) 1996 const char *ttyname, struct passwd * pw, const char *term,
1997 const char *display, const char *auth_proto,
1998 const char *auth_data)
1967{ 1999{
1968 int pid, fdout; 2000 int pid, fdout;
1969 const char *hostname; 2001 const char *hostname;
1970 time_t last_login_time; 2002 time_t last_login_time;
1971 char buf[100], *time_string; 2003 char buf[100], *time_string;
1972 FILE *f; 2004 FILE *f;
1973 char line[256]; 2005 char line[256];
1974 struct stat st; 2006 struct stat st;
1975 int quiet_login; 2007 int quiet_login;
1976 struct sockaddr_in from; 2008 struct sockaddr_in from;
1977 int fromlen; 2009 int fromlen;
1978 struct pty_cleanup_context cleanup_context; 2010 struct pty_cleanup_context cleanup_context;
1979 2011
1980 /* Get remote host name. */ 2012 /* Get remote host name. */
1981 hostname = get_canonical_hostname(); 2013 hostname = get_canonical_hostname();
1982 2014
1983 /* Get the time when the user last logged in. Buf will be set to contain 2015 /* Get the time when the user last logged in. Buf will be set to
1984 the hostname the last login was from. */ 2016 contain the hostname the last login was from. */
1985 if(!options.use_login) { 2017 if (!options.use_login) {
1986 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name, 2018 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name,
1987 buf, sizeof(buf)); 2019 buf, sizeof(buf));
1988 }
1989
1990 setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
1991
1992 /* Fork the child. */
1993 if ((pid = fork()) == 0)
1994 {
1995 pid = getpid();
1996
1997 /* Child. Reinitialize the log because the pid has changed. */
1998 log_init(av0, options.log_level, options.log_facility, log_stderr);
1999
2000 /* Close the master side of the pseudo tty. */
2001 close(ptyfd);
2002
2003 /* Make the pseudo tty our controlling tty. */
2004 pty_make_controlling_tty(&ttyfd, ttyname);
2005
2006 /* Redirect stdin from the pseudo tty. */
2007 if (dup2(ttyfd, fileno(stdin)) < 0)
2008 error("dup2 stdin failed: %.100s", strerror(errno));
2009
2010 /* Redirect stdout to the pseudo tty. */
2011 if (dup2(ttyfd, fileno(stdout)) < 0)
2012 error("dup2 stdin failed: %.100s", strerror(errno));
2013
2014 /* Redirect stderr to the pseudo tty. */
2015 if (dup2(ttyfd, fileno(stderr)) < 0)
2016 error("dup2 stdin failed: %.100s", strerror(errno));
2017
2018 /* Close the extra descriptor for the pseudo tty. */
2019 close(ttyfd);
2020
2021 /* Get IP address of client. This is needed because we want to record
2022 where the user logged in from. If the connection is not a socket,
2023 let the ip address be 0.0.0.0. */
2024 memset(&from, 0, sizeof(from));
2025 if (packet_get_connection_in() == packet_get_connection_out())
2026 {
2027 fromlen = sizeof(from);
2028 if (getpeername(packet_get_connection_in(),
2029 (struct sockaddr *)&from, &fromlen) < 0) {
2030 debug("getpeername: %.100s", strerror(errno));
2031 fatal_cleanup();
2032 }
2033 } 2020 }
2021 setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1);
2022
2023 /* Fork the child. */
2024 if ((pid = fork()) == 0) {
2025 pid = getpid();
2026
2027 /* Child. Reinitialize the log because the pid has
2028 changed. */
2029 log_init(av0, options.log_level, options.log_facility, log_stderr);
2030
2031 /* Close the master side of the pseudo tty. */
2032 close(ptyfd);
2033
2034 /* Make the pseudo tty our controlling tty. */
2035 pty_make_controlling_tty(&ttyfd, ttyname);
2036
2037 /* Redirect stdin from the pseudo tty. */
2038 if (dup2(ttyfd, fileno(stdin)) < 0)
2039 error("dup2 stdin failed: %.100s", strerror(errno));
2040
2041 /* Redirect stdout to the pseudo tty. */
2042 if (dup2(ttyfd, fileno(stdout)) < 0)
2043 error("dup2 stdin failed: %.100s", strerror(errno));
2044
2045 /* Redirect stderr to the pseudo tty. */
2046 if (dup2(ttyfd, fileno(stderr)) < 0)
2047 error("dup2 stdin failed: %.100s", strerror(errno));
2048
2049 /* Close the extra descriptor for the pseudo tty. */
2050 close(ttyfd);
2051
2052 /* Get IP address of client. This is needed because we
2053 want to record where the user logged in from. If the
2054 connection is not a socket, let the ip address be 0.0.0.0. */
2055 memset(&from, 0, sizeof(from));
2056 if (packet_get_connection_in() == packet_get_connection_out()) {
2057 fromlen = sizeof(from);
2058 if (getpeername(packet_get_connection_in(),
2059 (struct sockaddr *) & from, &fromlen) < 0) {
2060 debug("getpeername: %.100s", strerror(errno));
2061 fatal_cleanup();
2062 }
2063 }
2064 /* Record that there was a login on that terminal. */
2065 record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname,
2066 &from);
2034 2067
2035 /* Record that there was a login on that terminal. */ 2068 /* Check if .hushlogin exists. */
2036 record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname, 2069 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2037 &from); 2070 quiet_login = stat(line, &st) >= 0;
2038
2039 /* Check if .hushlogin exists. */
2040 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir);
2041 quiet_login = stat(line, &st) >= 0;
2042 2071
2043#ifdef HAVE_LIBPAM 2072#ifdef HAVE_LIBPAM
2044 /* output the results of the pamconv() */ 2073 /* output the results of the pamconv() */
2045 if (!quiet_login && pamconv_msg != NULL) 2074 if (!quiet_login && pamconv_msg != NULL)
2046 fprintf(stderr, pamconv_msg); 2075 fprintf(stderr, pamconv_msg);
2047#endif 2076#endif
2048
2049 /* If the user has logged in before, display the time of last login.
2050 However, don't display anything extra if a command has been
2051 specified (so that ssh can be used to execute commands on a remote
2052 machine without users knowing they are going to another machine).
2053 Login(1) will do this for us as well, so check if login(1) is used */
2054 if (command == NULL && last_login_time != 0 && !quiet_login &&
2055 !options.use_login)
2056 {
2057 /* Convert the date to a string. */
2058 time_string = ctime(&last_login_time);
2059 /* Remove the trailing newline. */
2060 if (strchr(time_string, '\n'))
2061 *strchr(time_string, '\n') = 0;
2062 /* Display the last login time. Host if displayed if known. */
2063 if (strcmp(buf, "") == 0)
2064 printf("Last login: %s\r\n", time_string);
2065 else
2066 printf("Last login: %s from %s\r\n", time_string, buf);
2067 }
2068 2077
2069 /* Print /etc/motd unless a command was specified or printing it was 2078 /* If the user has logged in before, display the time of
2070 disabled in server options or login(1) will be used. Note that 2079 last login. However, don't display anything extra if a
2071 some machines appear to print it in /etc/profile or similar. */ 2080 command has been specified (so that ssh can be used to
2072 if (command == NULL && options.print_motd && !quiet_login && 2081 execute commands on a remote machine without users
2073 !options.use_login) 2082 knowing they are going to another machine). Login(1)
2074 { 2083 will do this for us as well, so check if login(1) is used */
2075 /* Print /etc/motd if it exists. */ 2084 if (command == NULL && last_login_time != 0 && !quiet_login &&
2076 f = fopen("/etc/motd", "r"); 2085 !options.use_login) {
2077 if (f) 2086 /* Convert the date to a string. */
2078 { 2087 time_string = ctime(&last_login_time);
2079 while (fgets(line, sizeof(line), f)) 2088 /* Remove the trailing newline. */
2080 fputs(line, stdout); 2089 if (strchr(time_string, '\n'))
2081 fclose(f); 2090 *strchr(time_string, '\n') = 0;
2082 } 2091 /* Display the last login time. Host if displayed
2092 if known. */
2093 if (strcmp(buf, "") == 0)
2094 printf("Last login: %s\r\n", time_string);
2095 else
2096 printf("Last login: %s from %s\r\n", time_string, buf);
2097 }
2098 /* Print /etc/motd unless a command was specified or
2099 printing it was disabled in server options or login(1)
2100 will be used. Note that some machines appear to print
2101 it in /etc/profile or similar. */
2102 if (command == NULL && options.print_motd && !quiet_login &&
2103 !options.use_login) {
2104 /* Print /etc/motd if it exists. */
2105 f = fopen("/etc/motd", "r");
2106 if (f) {
2107 while (fgets(line, sizeof(line), f))
2108 fputs(line, stdout);
2109 fclose(f);
2110 }
2111 }
2112 /* Do common processing for the child, such as execing the command. */
2113 do_child(command, pw, term, display, auth_proto, auth_data, ttyname);
2114 /* NOTREACHED */
2083 } 2115 }
2084 2116 if (pid < 0)
2085 /* Do common processing for the child, such as execing the command. */ 2117 packet_disconnect("fork failed: %.100s", strerror(errno));
2086 do_child(command, pw, term, display, auth_proto, auth_data, ttyname); 2118 /* Parent. Close the slave side of the pseudo tty. */
2087 /*NOTREACHED*/ 2119 close(ttyfd);
2088 } 2120
2089 if (pid < 0) 2121 /* Create another descriptor of the pty master side for use as the
2090 packet_disconnect("fork failed: %.100s", strerror(errno)); 2122 standard input. We could use the original descriptor, but this
2091 /* Parent. Close the slave side of the pseudo tty. */ 2123 simplifies code in server_loop. The descriptor is bidirectional. */
2092 close(ttyfd); 2124 fdout = dup(ptyfd);
2093 2125 if (fdout < 0)
2094 /* Create another descriptor of the pty master side for use as the standard 2126 packet_disconnect("dup failed: %.100s", strerror(errno));
2095 input. We could use the original descriptor, but this simplifies code 2127
2096 in server_loop. The descriptor is bidirectional. */ 2128 /* Add a cleanup function to clear the utmp entry and record logout
2097 fdout = dup(ptyfd); 2129 time in case we call fatal() (e.g., the connection gets closed). */
2098 if (fdout < 0) 2130 cleanup_context.pid = pid;
2099 packet_disconnect("dup failed: %.100s", strerror(errno)); 2131 cleanup_context.ttyname = ttyname;
2100 2132 fatal_add_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
2101 /* Add a cleanup function to clear the utmp entry and record logout time 2133
2102 in case we call fatal() (e.g., the connection gets closed). */ 2134 /* Enter interactive session. */
2103 cleanup_context.pid = pid; 2135 server_loop(pid, ptyfd, fdout, -1);
2104 cleanup_context.ttyname = ttyname; 2136 /* server_loop has not closed ptyfd and fdout. */
2105 fatal_add_cleanup(pty_cleanup_proc, (void *)&cleanup_context); 2137
2106 2138 /* Cancel the cleanup function. */
2107 /* Enter interactive session. */ 2139 fatal_remove_cleanup(pty_cleanup_proc, (void *) &cleanup_context);
2108 server_loop(pid, ptyfd, fdout, -1); 2140
2109 /* server_loop has not closed ptyfd and fdout. */ 2141 /* Record that the user has logged out. */
2110 2142 record_logout(pid, ttyname);
2111 /* Cancel the cleanup function. */ 2143
2112 fatal_remove_cleanup(pty_cleanup_proc, (void *)&cleanup_context); 2144 /* Release the pseudo-tty. */
2113 2145 pty_release(ttyname);
2114 /* Record that the user has logged out. */ 2146
2115 record_logout(pid, ttyname); 2147 /* Close the server side of the socket pairs. We must do this
2116 2148 after the pty cleanup, so that another process doesn't get this
2117 /* Release the pseudo-tty. */ 2149 pty while we're still cleaning up. */
2118 pty_release(ttyname); 2150 close(ptyfd);
2119 2151 close(fdout);
2120 /* Close the server side of the socket pairs. We must do this after the
2121 pty cleanup, so that another process doesn't get this pty while we're
2122 still cleaning up. */
2123 close(ptyfd);
2124 close(fdout);
2125} 2152}
2126 2153
2127/* Sets the value of the given variable in the environment. If the variable 2154/*
2128 already exists, its value is overriden. */ 2155 * Sets the value of the given variable in the environment. If the variable
2129 2156 * already exists, its value is overriden.
2130void child_set_env(char ***envp, unsigned int *envsizep, const char *name, 2157 */
2131 const char *value) 2158void
2159child_set_env(char ***envp, unsigned int *envsizep, const char *name,
2160 const char *value)
2132{ 2161{
2133 unsigned int i, namelen; 2162 unsigned int i, namelen;
2134 char **env; 2163 char **env;
2135 2164
2136 /* Find the slot where the value should be stored. If the variable already 2165 /* Find the slot where the value should be stored. If the
2137 exists, we reuse the slot; otherwise we append a new slot at the end 2166 variable already exists, we reuse the slot; otherwise we append
2138 of the array, expanding if necessary. */ 2167 a new slot at the end of the array, expanding if necessary. */
2139 env = *envp; 2168 env = *envp;
2140 namelen = strlen(name); 2169 namelen = strlen(name);
2141 for (i = 0; env[i]; i++) 2170 for (i = 0; env[i]; i++)
2142 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=') 2171 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=')
2143 break; 2172 break;
2144 if (env[i]) 2173 if (env[i]) {
2145 { 2174 /* Name already exists. Reuse the slot. */
2146 /* Name already exists. Reuse the slot. */ 2175 xfree(env[i]);
2147 xfree(env[i]); 2176 } else {
2148 } 2177 /* New variable. Expand the array if necessary. */
2149 else 2178 if (i >= (*envsizep) - 1) {
2150 { 2179 (*envsizep) += 50;
2151 /* New variable. Expand the array if necessary. */ 2180 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2152 if (i >= (*envsizep) - 1) 2181 }
2153 { 2182 /* Need to set the NULL pointer at end of array beyond the new slot. */
2154 (*envsizep) += 50; 2183 env[i + 1] = NULL;
2155 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *));
2156 } 2184 }
2157 2185
2158 /* Need to set the NULL pointer at end of array beyond the new 2186 /* Allocate space and format the variable in the appropriate slot. */
2159 slot. */ 2187 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2160 env[i + 1] = NULL; 2188 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2161 }
2162
2163 /* Allocate space and format the variable in the appropriate slot. */
2164 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1);
2165 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value);
2166} 2189}
2167 2190
2168/* Reads environment variables from the given file and adds/overrides them 2191/*
2169 into the environment. If the file does not exist, this does nothing. 2192 * Reads environment variables from the given file and adds/overrides them
2170 Otherwise, it must consist of empty lines, comments (line starts with '#') 2193 * into the environment. If the file does not exist, this does nothing.
2171 and assignments of the form name=value. No other forms are allowed. */ 2194 * Otherwise, it must consist of empty lines, comments (line starts with '#')
2172 2195 * and assignments of the form name=value. No other forms are allowed.
2173void read_environment_file(char ***env, unsigned int *envsize, 2196 */
2174 const char *filename) 2197void
2198read_environment_file(char ***env, unsigned int *envsize,
2199 const char *filename)
2175{ 2200{
2176 FILE *f; 2201 FILE *f;
2177 char buf[4096]; 2202 char buf[4096];
2178 char *cp, *value; 2203 char *cp, *value;
2179 2204
2180 /* Open the environment file. */ 2205 /* Open the environment file. */
2181 f = fopen(filename, "r"); 2206 f = fopen(filename, "r");
2182 if (!f) 2207 if (!f)
2183 return; /* Not found. */ 2208 return;
2184 2209
2185 /* Process each line. */ 2210 /* Process each line. */
2186 while (fgets(buf, sizeof(buf), f)) 2211 while (fgets(buf, sizeof(buf), f)) {
2187 { 2212 /* Skip leading whitespace. */
2188 /* Skip leading whitespace. */ 2213 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++);
2189 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++) 2214
2190 ; 2215 /* Ignore empty and comment lines. */
2191 2216 if (!*cp || *cp == '#' || *cp == '\n')
2192 /* Ignore empty and comment lines. */ 2217 continue;
2193 if (!*cp || *cp == '#' || *cp == '\n') 2218
2194 continue; 2219 /* Remove newline. */
2195 2220 if (strchr(cp, '\n'))
2196 /* Remove newline. */ 2221 *strchr(cp, '\n') = '\0';
2197 if (strchr(cp, '\n')) 2222
2198 *strchr(cp, '\n') = '\0'; 2223 /* Find the equals sign. Its lack indicates badly
2199 2224 formatted line. */
2200 /* Find the equals sign. Its lack indicates badly formatted line. */ 2225 value = strchr(cp, '=');
2201 value = strchr(cp, '='); 2226 if (value == NULL) {
2202 if (value == NULL) 2227 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf);
2203 { 2228 continue;
2204 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf); 2229 }
2205 continue; 2230 /* Replace the equals sign by nul, and advance value to
2206 } 2231 the value string. */
2232 *value = '\0';
2233 value++;
2207 2234
2208 /* Replace the equals sign by nul, and advance value to the value 2235 /* Set the value in environment. */
2209 string. */ 2236 child_set_env(env, envsize, cp, value);
2210 *value = '\0'; 2237 }
2211 value++;
2212 2238
2213 /* Set the value in environment. */ 2239 fclose(f);
2214 child_set_env(env, envsize, cp, value);
2215 }
2216
2217 fclose(f);
2218} 2240}
2219 2241
2220/* Performs common processing for the child, such as setting up the 2242/*
2221 environment, closing extra file descriptors, setting the user and group 2243 * Performs common processing for the child, such as setting up the
2222 ids, and executing the command or shell. */ 2244 * environment, closing extra file descriptors, setting the user and group
2223 2245 * ids, and executing the command or shell.
2224void do_child(const char *command, struct passwd *pw, const char *term, 2246 */
2225 const char *display, const char *auth_proto, 2247void
2226 const char *auth_data, const char *ttyname) 2248do_child(const char *command, struct passwd * pw, const char *term,
2249 const char *display, const char *auth_proto,
2250 const char *auth_data, const char *ttyname)
2227{ 2251{
2228 const char *shell, *cp = NULL; 2252 const char *shell, *cp = NULL;
2229 char buf[256]; 2253 char buf[256];
2230 FILE *f; 2254 FILE *f;
2231 unsigned int envsize, i; 2255 unsigned int envsize, i;
2232 char **env; 2256 char **env;
2233 extern char **environ; 2257 extern char **environ;
2234 struct stat st; 2258 struct stat st;
2235 char *argv[10]; 2259 char *argv[10];
2236 2260
2237#ifndef HAVE_LIBPAM /* pam_nologin handles this */ 2261#ifndef HAVE_LIBPAM /* pam_nologin handles this */
2238 /* Check /etc/nologin. */ 2262 /* Check /etc/nologin. */
2239 f = fopen("/etc/nologin", "r"); 2263 f = fopen("/etc/nologin", "r");
2240 if (f) 2264 if (f) {
2241 { /* /etc/nologin exists. Print its contents and exit. */ 2265 /* /etc/nologin exists. Print its contents and exit. */
2242 while (fgets(buf, sizeof(buf), f)) 2266 while (fgets(buf, sizeof(buf), f))
2243 fputs(buf, stderr); 2267 fputs(buf, stderr);
2244 fclose(f); 2268 fclose(f);
2245 if (pw->pw_uid != 0) 2269 if (pw->pw_uid != 0)
2246 exit(254); 2270 exit(254);
2247 } 2271 }
2248#endif /* HAVE_LIBPAM */ 2272#endif /* HAVE_LIBPAM */
2249 2273
2250#ifdef HAVE_SETLOGIN 2274#ifdef HAVE_SETLOGIN
2251 /* Set login name in the kernel. */ 2275 /* Set login name in the kernel. */
2252 if (setlogin(pw->pw_name) < 0) 2276 if (setlogin(pw->pw_name) < 0)
2253 error("setlogin failed: %s", strerror(errno)); 2277 error("setlogin failed: %s", strerror(errno));
2254#endif /* HAVE_SETLOGIN */ 2278#endif /* HAVE_SETLOGIN */
2255 2279
2256 /* Set uid, gid, and groups. */ 2280 /* Set uid, gid, and groups. */
2257 /* Login(1) does this as well, and it needs uid 0 for the "-h" switch, 2281 /* Login(1) does this as well, and it needs uid 0 for the "-h"
2258 so we let login(1) to this for us. */ 2282 switch, so we let login(1) to this for us. */
2259 if(!options.use_login) { 2283 if (!options.use_login) {
2260 if (getuid() == 0 || geteuid() == 0) 2284 if (getuid() == 0 || geteuid() == 0) {
2261 { 2285 if (setgid(pw->pw_gid) < 0) {
2262 if (setgid(pw->pw_gid) < 0) 2286 perror("setgid");
2263 { 2287 exit(1);
2264 perror("setgid"); 2288 }
2265 exit(1); 2289 /* Initialize the group list. */
2266 } 2290 if (initgroups(pw->pw_name, pw->pw_gid) < 0) {
2267 /* Initialize the group list. */ 2291 perror("initgroups");
2268 if (initgroups(pw->pw_name, pw->pw_gid) < 0) 2292 exit(1);
2269 { 2293 }
2270 perror("initgroups"); 2294 endgrent();
2271 exit(1); 2295
2272 } 2296 /* Permanently switch to the desired uid. */
2273 endgrent(); 2297 permanently_set_uid(pw->pw_uid);
2274 2298 }
2275 /* Permanently switch to the desired uid. */ 2299 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid)
2276 permanently_set_uid(pw->pw_uid); 2300 fatal("Failed to set uids to %d.", (int) pw->pw_uid);
2277 } 2301 }
2278 2302 /* Get the shell from the password data. An empty shell field is
2279 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid) 2303 legal, and means /bin/sh. */
2280 fatal("Failed to set uids to %d.", (int)pw->pw_uid); 2304 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
2281 }
2282
2283 /* Get the shell from the password data. An empty shell field is legal,
2284 and means /bin/sh. */
2285 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell;
2286 2305
2287#ifdef AFS 2306#ifdef AFS
2288 /* Try to get AFS tokens for the local cell. */ 2307 /* Try to get AFS tokens for the local cell. */
2289 if (k_hasafs()) { 2308 if (k_hasafs()) {
2290 char cell[64]; 2309 char cell[64];
2291 2310
2292 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0) 2311 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0)
2293 krb_afslog(cell, 0); 2312 krb_afslog(cell, 0);
2294 2313
2295 krb_afslog(0, 0); 2314 krb_afslog(0, 0);
2296 } 2315 }
2297#endif /* AFS */ 2316#endif /* AFS */
2298 2317
2299 /* Initialize the environment. In the first part we allocate space for 2318 /* Initialize the environment. In the first part we allocate
2300 all environment variables. */ 2319 space for all environment variables. */
2301 envsize = 100; 2320 envsize = 100;
2302 env = xmalloc(envsize * sizeof(char *)); 2321 env = xmalloc(envsize * sizeof(char *));
2303 env[0] = NULL; 2322 env[0] = NULL;
2304 2323
2305 if(!options.use_login) { 2324 if (!options.use_login) {
2306 /* Set basic environment. */ 2325 /* Set basic environment. */
2307 child_set_env(&env, &envsize, "USER", pw->pw_name); 2326 child_set_env(&env, &envsize, "USER", pw->pw_name);
2308 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name); 2327 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name);
2309 child_set_env(&env, &envsize, "HOME", pw->pw_dir); 2328 child_set_env(&env, &envsize, "HOME", pw->pw_dir);
2310 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH); 2329 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH);
2311 2330
2312 snprintf(buf, sizeof buf, "%.200s/%.50s", 2331 snprintf(buf, sizeof buf, "%.200s/%.50s",
2313 _PATH_MAILDIR, pw->pw_name); 2332 _PATH_MAILDIR, pw->pw_name);
2314 child_set_env(&env, &envsize, "MAIL", buf); 2333 child_set_env(&env, &envsize, "MAIL", buf);
2315 2334
2316 /* Normal systems set SHELL by default. */ 2335 /* Normal systems set SHELL by default. */
2317 child_set_env(&env, &envsize, "SHELL", shell); 2336 child_set_env(&env, &envsize, "SHELL", shell);
2318 } 2337 }
2319 2338 /* Let it inherit timezone if we have one. */
2320 /* Let it inherit timezone if we have one. */ 2339 if (getenv("TZ"))
2321 if (getenv("TZ")) 2340 child_set_env(&env, &envsize, "TZ", getenv("TZ"));
2322 child_set_env(&env, &envsize, "TZ", getenv("TZ")); 2341
2323 2342 /* Set custom environment options from RSA authentication. */
2324 /* Set custom environment options from RSA authentication. */ 2343 while (custom_environment) {
2325 while (custom_environment) 2344 struct envstring *ce = custom_environment;
2326 { 2345 char *s = ce->s;
2327 struct envstring *ce = custom_environment; 2346 int i;
2328 char *s = ce->s; 2347 for (i = 0; s[i] != '=' && s[i]; i++);
2329 int i; 2348 if (s[i] == '=') {
2330 for (i = 0; s[i] != '=' && s[i]; i++) 2349 s[i] = 0;
2331 ; 2350 child_set_env(&env, &envsize, s, s + i + 1);
2332 if (s[i] == '=') 2351 }
2333 { 2352 custom_environment = ce->next;
2334 s[i] = 0; 2353 xfree(ce->s);
2335 child_set_env(&env, &envsize, s, s + i + 1); 2354 xfree(ce);
2336 } 2355 }
2337 custom_environment = ce->next;
2338 xfree(ce->s);
2339 xfree(ce);
2340 }
2341 2356
2342 /* Set SSH_CLIENT. */ 2357 /* Set SSH_CLIENT. */
2343 snprintf(buf, sizeof buf, "%.50s %d %d", 2358 snprintf(buf, sizeof buf, "%.50s %d %d",
2344 get_remote_ipaddr(), get_remote_port(), options.port); 2359 get_remote_ipaddr(), get_remote_port(), options.port);
2345 child_set_env(&env, &envsize, "SSH_CLIENT", buf); 2360 child_set_env(&env, &envsize, "SSH_CLIENT", buf);
2346 2361
2347 /* Set SSH_TTY if we have a pty. */ 2362 /* Set SSH_TTY if we have a pty. */
2348 if (ttyname) 2363 if (ttyname)
2349 child_set_env(&env, &envsize, "SSH_TTY", ttyname); 2364 child_set_env(&env, &envsize, "SSH_TTY", ttyname);
2350 2365
2351 /* Set TERM if we have a pty. */ 2366 /* Set TERM if we have a pty. */
2352 if (term) 2367 if (term)
2353 child_set_env(&env, &envsize, "TERM", term); 2368 child_set_env(&env, &envsize, "TERM", term);
2354 2369
2355 /* Set DISPLAY if we have one. */ 2370 /* Set DISPLAY if we have one. */
2356 if (display) 2371 if (display)
2357 child_set_env(&env, &envsize, "DISPLAY", display); 2372 child_set_env(&env, &envsize, "DISPLAY", display);
2358 2373
2359#ifdef KRB4 2374#ifdef KRB4
2360 { 2375 {
2361 extern char *ticket; 2376 extern char *ticket;
2362 2377
2363 if (ticket) 2378 if (ticket)
2364 child_set_env(&env, &envsize, "KRBTKFILE", ticket); 2379 child_set_env(&env, &envsize, "KRBTKFILE", ticket);
2365 } 2380 }
2366#endif /* KRB4 */ 2381#endif /* KRB4 */
2367 2382
2368#ifdef HAVE_LIBPAM 2383#ifdef HAVE_LIBPAM
2369 /* Pull in any environment variables that may have been set by PAM. */ 2384 /* Pull in any environment variables that may have been set by PAM. */
2370 { 2385 {
2371 char *equal_sign, var_name[256], var_val[256]; 2386 char *equals, var_name[512], var_val[512];
2372 long this_var; 2387 char **pam_env = pam_getenvlist((pam_handle_t *)pamh);
2373 char **pam_env = pam_getenvlist((pam_handle_t *)pamh); 2388 int i;
2374 for(this_var = 0; pam_env && pam_env[this_var]; this_var++) 2389 for(i = 0; pam_env && pam_env[i]; i++) {
2375 { 2390 equals = strstr(pam_env[i], "=");
2376 if(strlen(pam_env[this_var]) < (sizeof(var_name) - 1)) 2391 if ((strlen(pam_env[i]) < (sizeof(var_name) - 1)) && (equals != NULL))
2377 if((equal_sign = strstr(pam_env[this_var], "=")) != NULL) 2392 {
2378 { 2393 memset(var_name, '\0', sizeof(var_name));
2379 memset(var_name, 0, sizeof(var_name)); 2394 memset(var_val, '\0', sizeof(var_val));
2380 memset(var_val, 0, sizeof(var_val)); 2395 strncpy(var_name, pam_env[i], equals - pam_env[i]);
2381 strncpy(var_name, pam_env[this_var], 2396 strcpy(var_val, equals + 1);
2382 equal_sign - pam_env[this_var]); 2397 child_set_env(&env, &envsize, var_name, var_val);
2383 strcpy(var_val, equal_sign + 1); 2398 }
2384 child_set_env(&env, &envsize, var_name, var_val); 2399 }
2385 } 2400 }
2386 }
2387 }
2388#endif /* HAVE_LIBPAM */ 2401#endif /* HAVE_LIBPAM */
2389 2402
2390 /* Set XAUTHORITY to always be a local file. */ 2403 /* Set XAUTHORITY to always be a local file. */
2391 if (xauthfile) 2404 if (xauthfile)
2392 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile); 2405 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile);
2393 2406
2394 /* Set variable for forwarded authentication connection, if we have one. */ 2407 /* Set variable for forwarded authentication connection, if we
2395 if (auth_get_socket_name() != NULL) 2408 have one. */
2396 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME, 2409 if (auth_get_socket_name() != NULL)
2397 auth_get_socket_name()); 2410 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME,
2398 2411 auth_get_socket_name());
2399 /* Read $HOME/.ssh/environment. */ 2412
2400 if(!options.use_login) { 2413 /* Read $HOME/.ssh/environment. */
2401 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir); 2414 if (!options.use_login) {
2402 read_environment_file(&env, &envsize, buf); 2415 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir);
2403 } 2416 read_environment_file(&env, &envsize, buf);
2404 2417 }
2405 /* If debugging, dump the environment to stderr. */ 2418 /* If debugging, dump the environment to stderr. */
2406 if (debug_flag) 2419 if (debug_flag) {
2407 { 2420 fprintf(stderr, "Environment:\n");
2408 fprintf(stderr, "Environment:\n"); 2421 for (i = 0; env[i]; i++)
2409 for (i = 0; env[i]; i++) 2422 fprintf(stderr, " %.200s\n", env[i]);
2410 fprintf(stderr, " %.200s\n", env[i]); 2423 }
2411 } 2424 /* Close the connection descriptors; note that this is the child,
2412 2425 and the server will still have the socket open, and it is
2413 /* Close the connection descriptors; note that this is the child, and the 2426 important that we do not shutdown it. Note that the
2414 server will still have the socket open, and it is important that we 2427 descriptors cannot be closed before building the environment,
2415 do not shutdown it. Note that the descriptors cannot be closed before 2428 as we call get_remote_ipaddr there. */
2416 building the environment, as we call get_remote_ipaddr there. */ 2429 if (packet_get_connection_in() == packet_get_connection_out())
2417 if (packet_get_connection_in() == packet_get_connection_out()) 2430 close(packet_get_connection_in());
2418 close(packet_get_connection_in()); 2431 else {
2419 else 2432 close(packet_get_connection_in());
2420 { 2433 close(packet_get_connection_out());
2421 close(packet_get_connection_in()); 2434 }
2422 close(packet_get_connection_out()); 2435 /* Close all descriptors related to channels. They will still
2423 } 2436 remain open in the parent. */
2424 /* Close all descriptors related to channels. They will still remain 2437 channel_close_all();
2425 open in the parent. */ 2438
2426 channel_close_all(); 2439 /* Close any extra file descriptors. Note that there may still be
2427 2440 descriptors left by system functions. They will be closed
2428 /* Close any extra file descriptors. Note that there may still be 2441 later. */
2429 descriptors left by system functions. They will be closed later. */ 2442 endpwent();
2430 endpwent(); 2443 endhostent();
2431 endhostent(); 2444
2432 2445 /* Close any extra open file descriptors so that we don\'t have
2433 /* Close any extra open file descriptors so that we don\'t have them 2446 them hanging around in clients. Note that we want to do this
2434 hanging around in clients. Note that we want to do this after 2447 after initgroups, because at least on Solaris 2.3 it leaves
2435 initgroups, because at least on Solaris 2.3 it leaves file descriptors 2448 file descriptors open. */
2436 open. */ 2449 for (i = 3; i < 64; i++)
2437 for (i = 3; i < 64; i++) 2450 close(i);
2438 close(i); 2451
2439 2452 /* Change current directory to the user\'s home directory. */
2440 /* Change current directory to the user\'s home directory. */ 2453 if (chdir(pw->pw_dir) < 0)
2441 if (chdir(pw->pw_dir) < 0) 2454 fprintf(stderr, "Could not chdir to home directory %s: %s\n",
2442 fprintf(stderr, "Could not chdir to home directory %s: %s\n", 2455 pw->pw_dir, strerror(errno));
2443 pw->pw_dir, strerror(errno)); 2456
2444 2457 /* Must take new environment into use so that .ssh/rc, /etc/sshrc
2445 /* Must take new environment into use so that .ssh/rc, /etc/sshrc and 2458 and xauth are run in the proper environment. */
2446 xauth are run in the proper environment. */ 2459 environ = env;
2447 environ = env; 2460
2448 2461 /* Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found
2449 /* Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first 2462 first in this order). */
2450 in this order). */ 2463 if (!options.use_login) {
2451 if(!options.use_login) { 2464 if (stat(SSH_USER_RC, &st) >= 0) {
2452 if (stat(SSH_USER_RC, &st) >= 0) 2465 if (debug_flag)
2453 { 2466 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC);
2454 if (debug_flag) 2467
2455 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC); 2468 f = popen("/bin/sh " SSH_USER_RC, "w");
2456 2469 if (f) {
2457 f = popen("/bin/sh " SSH_USER_RC, "w"); 2470 if (auth_proto != NULL && auth_data != NULL)
2458 if (f) 2471 fprintf(f, "%s %s\n", auth_proto, auth_data);
2459 { 2472 pclose(f);
2460 if (auth_proto != NULL && auth_data != NULL) 2473 } else
2461 fprintf(f, "%s %s\n", auth_proto, auth_data); 2474 fprintf(stderr, "Could not run %s\n", SSH_USER_RC);
2462 pclose(f); 2475 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) {
2463 } 2476 if (debug_flag)
2464 else 2477 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC);
2465 fprintf(stderr, "Could not run %s\n", SSH_USER_RC); 2478
2466 } 2479 f = popen("/bin/sh " SSH_SYSTEM_RC, "w");
2467 else 2480 if (f) {
2468 if (stat(SSH_SYSTEM_RC, &st) >= 0) 2481 if (auth_proto != NULL && auth_data != NULL)
2469 { 2482 fprintf(f, "%s %s\n", auth_proto, auth_data);
2470 if (debug_flag) 2483 pclose(f);
2471 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC); 2484 } else
2472 2485 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2473 f = popen("/bin/sh " SSH_SYSTEM_RC, "w"); 2486 }
2474 if (f)
2475 {
2476 if (auth_proto != NULL && auth_data != NULL)
2477 fprintf(f, "%s %s\n", auth_proto, auth_data);
2478 pclose(f);
2479 }
2480 else
2481 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC);
2482 }
2483#ifdef XAUTH_PATH 2487#ifdef XAUTH_PATH
2484 else 2488 else {
2485 { 2489 /* Add authority data to .Xauthority if
2486 /* Add authority data to .Xauthority if appropriate. */ 2490 appropriate. */
2487 if (auth_proto != NULL && auth_data != NULL) 2491 if (auth_proto != NULL && auth_data != NULL) {
2488 { 2492 if (debug_flag)
2489 if (debug_flag) 2493 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n",
2490 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n", 2494 XAUTH_PATH, display, auth_proto, auth_data);
2491 XAUTH_PATH, display, auth_proto, auth_data); 2495
2492 2496 f = popen(XAUTH_PATH " -q -", "w");
2493 f = popen(XAUTH_PATH " -q -", "w"); 2497 if (f) {
2494 if (f) 2498 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data);
2495 { 2499 fclose(f);
2496 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data); 2500 } else
2497 fclose(f); 2501 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2498 } 2502 }
2499 else 2503 }
2500 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH);
2501 }
2502 }
2503#endif /* XAUTH_PATH */ 2504#endif /* XAUTH_PATH */
2504 2505
2505 /* Get the last component of the shell name. */ 2506 /* Get the last component of the shell name. */
2506 cp = strrchr(shell, '/'); 2507 cp = strrchr(shell, '/');
2507 if (cp) 2508 if (cp)
2508 cp++; 2509 cp++;
2509 else 2510 else
2510 cp = shell; 2511 cp = shell;
2511 } 2512 }
2512 2513 /* If we have no command, execute the shell. In this case, the
2513 /* If we have no command, execute the shell. In this case, the shell name 2514 shell name to be passed in argv[0] is preceded by '-' to
2514 to be passed in argv[0] is preceded by '-' to indicate that this is 2515 indicate that this is a login shell. */
2515 a login shell. */ 2516 if (!command) {
2516 if (!command) 2517 if (!options.use_login) {
2517 { 2518 char buf[256];
2518 if(!options.use_login) { 2519
2519 char buf[256]; 2520 /* Check for mail if we have a tty and it was
2520 2521 enabled in server options. */
2521 /* Check for mail if we have a tty and it was enabled in server options. */ 2522 if (ttyname && options.check_mail) {
2522 if (ttyname && options.check_mail) { 2523 char *mailbox;
2523 char *mailbox; 2524 struct stat mailstat;
2524 struct stat mailstat; 2525 mailbox = getenv("MAIL");
2525 mailbox = getenv("MAIL"); 2526 if (mailbox != NULL) {
2526 if(mailbox != NULL) { 2527 if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0)
2527 if(stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0) { 2528 printf("No mail.\n");
2528 printf("No mail.\n"); 2529 else if (mailstat.st_mtime < mailstat.st_atime)
2529 } else if(mailstat.st_mtime < mailstat.st_atime) { 2530 printf("You have mail.\n");
2530 printf("You have mail.\n"); 2531 else
2531 } else { 2532 printf("You have new mail.\n");
2532 printf("You have new mail.\n"); 2533 }
2533 } 2534 }
2534 } 2535 /* Start the shell. Set initial character to '-'. */
2535 } 2536 buf[0] = '-';
2536 /* Start the shell. Set initial character to '-'. */ 2537 strncpy(buf + 1, cp, sizeof(buf) - 1);
2537 buf[0] = '-'; 2538 buf[sizeof(buf) - 1] = 0;
2538 strncpy(buf + 1, cp, sizeof(buf) - 1); 2539
2539 buf[sizeof(buf) - 1] = 0; 2540 /* Execute the shell. */
2540 /* Execute the shell. */ 2541 argv[0] = buf;
2541 argv[0] = buf; 2542 argv[1] = NULL;
2542 argv[1] = NULL; 2543 execve(shell, argv, env);
2543 execve(shell, argv, env); 2544
2544 /* Executing the shell failed. */ 2545 /* Executing the shell failed. */
2545 perror(shell); 2546 perror(shell);
2546 exit(1); 2547 exit(1);
2547 2548
2548 } else { 2549 } else {
2549 /* Launch login(1). */ 2550 /* Launch login(1). */
2550 2551
2551 execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(), "-p", "-f", "--", pw->pw_name, NULL); 2552 execl(LOGIN_PROGRAM, "login", "-h", get_remote_ipaddr(),
2552 2553 "-p", "-f", "--", pw->pw_name, NULL);
2553 /* Login couldn't be executed, die. */ 2554
2554 2555 /* Login couldn't be executed, die. */
2555 perror("login"); 2556
2556 exit(1); 2557 perror("login");
2557 } 2558 exit(1);
2558 } 2559 }
2559 2560 }
2560 /* Execute the command using the user's shell. This uses the -c option 2561 /* Execute the command using the user's shell. This uses the -c
2561 to execute the command. */ 2562 option to execute the command. */
2562 argv[0] = (char *)cp; 2563 argv[0] = (char *) cp;
2563 argv[1] = "-c"; 2564 argv[1] = "-c";
2564 argv[2] = (char *)command; 2565 argv[2] = (char *) command;
2565 argv[3] = NULL; 2566 argv[3] = NULL;
2566 execve(shell, argv, env); 2567 execve(shell, argv, env);
2567 perror(shell); 2568 perror(shell);
2568 exit(1); 2569 exit(1);
2569} 2570}