summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Makefile.in6
-rw-r--r--auth-chall.c125
-rw-r--r--auth-rh-rsa.c109
-rw-r--r--auth-rhosts.c23
-rw-r--r--auth-rsa.c349
-rw-r--r--auth.c10
-rw-r--r--auth.h19
-rw-r--r--auth1.c444
-rw-r--r--monitor.c305
-rw-r--r--monitor_wrap.c151
-rw-r--r--monitor_wrap.h13
-rw-r--r--serverloop.c596
-rw-r--r--serverloop.h3
-rw-r--r--session.c212
-rw-r--r--session.h3
-rw-r--r--sshd.c479
16 files changed, 84 insertions, 2763 deletions
diff --git a/Makefile.in b/Makefile.in
index 12991cd9f..62fdb09f6 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -97,11 +97,11 @@ LIBSSH_OBJS=${LIBOPENSSH_OBJS} \
97SSHOBJS= ssh.o readconf.o clientloop.o sshtty.o \ 97SSHOBJS= ssh.o readconf.o clientloop.o sshtty.o \
98 sshconnect.o sshconnect1.o sshconnect2.o mux.o 98 sshconnect.o sshconnect1.o sshconnect2.o mux.o
99 99
100SSHDOBJS=sshd.o auth-rhosts.o auth-passwd.o auth-rsa.o auth-rh-rsa.o \ 100SSHDOBJS=sshd.o auth-rhosts.o auth-passwd.o \
101 audit.o audit-bsm.o audit-linux.o platform.o \ 101 audit.o audit-bsm.o audit-linux.o platform.o \
102 sshpty.o sshlogin.o servconf.o serverloop.o \ 102 sshpty.o sshlogin.o servconf.o serverloop.o \
103 auth.o auth1.o auth2.o auth-options.o session.o \ 103 auth.o auth2.o auth-options.o session.o \
104 auth-chall.o auth2-chall.o groupaccess.o \ 104 auth2-chall.o groupaccess.o \
105 auth-skey.o auth-bsdauth.o auth2-hostbased.o auth2-kbdint.o \ 105 auth-skey.o auth-bsdauth.o auth2-hostbased.o auth2-kbdint.o \
106 auth2-none.o auth2-passwd.o auth2-pubkey.o \ 106 auth2-none.o auth2-passwd.o auth2-pubkey.o \
107 monitor_mm.o monitor.o monitor_wrap.o auth-krb5.o \ 107 monitor_mm.o monitor.o monitor_wrap.o auth-krb5.o \
diff --git a/auth-chall.c b/auth-chall.c
deleted file mode 100644
index 60c9f14ca..000000000
--- a/auth-chall.c
+++ /dev/null
@@ -1,125 +0,0 @@
1/* $OpenBSD: auth-chall.c,v 1.14 2014/06/24 01:13:21 djm Exp $ */
2/*
3 * Copyright (c) 2001 Markus Friedl. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include "includes.h"
27
28#include <sys/types.h>
29#include <stdarg.h>
30#include <stdlib.h>
31#include <stdio.h>
32
33#include "xmalloc.h"
34#include "key.h"
35#include "hostfile.h"
36#include "auth.h"
37#include "log.h"
38#include "misc.h"
39#include "servconf.h"
40
41/* limited protocol v1 interface to kbd-interactive authentication */
42
43extern KbdintDevice *devices[];
44static KbdintDevice *device;
45extern ServerOptions options;
46
47char *
48get_challenge(Authctxt *authctxt)
49{
50 char *challenge, *name, *info, **prompts;
51 u_int i, numprompts;
52 u_int *echo_on;
53
54#ifdef USE_PAM
55 if (!options.use_pam)
56 remove_kbdint_device("pam");
57#endif
58
59 device = devices[0]; /* we always use the 1st device for protocol 1 */
60 if (device == NULL)
61 return NULL;
62 if ((authctxt->kbdintctxt = device->init_ctx(authctxt)) == NULL)
63 return NULL;
64 if (device->query(authctxt->kbdintctxt, &name, &info,
65 &numprompts, &prompts, &echo_on)) {
66 device->free_ctx(authctxt->kbdintctxt);
67 authctxt->kbdintctxt = NULL;
68 return NULL;
69 }
70 if (numprompts < 1)
71 fatal("get_challenge: numprompts < 1");
72 challenge = xstrdup(prompts[0]);
73 for (i = 0; i < numprompts; i++)
74 free(prompts[i]);
75 free(prompts);
76 free(name);
77 free(echo_on);
78 free(info);
79
80 return (challenge);
81}
82int
83verify_response(Authctxt *authctxt, const char *response)
84{
85 char *resp[1], *name, *info, **prompts;
86 u_int i, numprompts, *echo_on;
87 int authenticated = 0;
88
89 if (device == NULL)
90 return 0;
91 if (authctxt->kbdintctxt == NULL)
92 return 0;
93 resp[0] = (char *)response;
94 switch (device->respond(authctxt->kbdintctxt, 1, resp)) {
95 case 0: /* Success */
96 authenticated = 1;
97 break;
98 case 1: /* Postponed - retry with empty query for PAM */
99 if ((device->query(authctxt->kbdintctxt, &name, &info,
100 &numprompts, &prompts, &echo_on)) != 0)
101 break;
102 if (numprompts == 0 &&
103 device->respond(authctxt->kbdintctxt, 0, resp) == 0)
104 authenticated = 1;
105
106 for (i = 0; i < numprompts; i++)
107 free(prompts[i]);
108 free(prompts);
109 free(name);
110 free(echo_on);
111 free(info);
112 break;
113 }
114 device->free_ctx(authctxt->kbdintctxt);
115 authctxt->kbdintctxt = NULL;
116 return authenticated;
117}
118void
119abandon_challenge_response(Authctxt *authctxt)
120{
121 if (authctxt->kbdintctxt != NULL) {
122 device->free_ctx(authctxt->kbdintctxt);
123 authctxt->kbdintctxt = NULL;
124 }
125}
diff --git a/auth-rh-rsa.c b/auth-rh-rsa.c
deleted file mode 100644
index 057335ba4..000000000
--- a/auth-rh-rsa.c
+++ /dev/null
@@ -1,109 +0,0 @@
1/* $OpenBSD: auth-rh-rsa.c,v 1.45 2016/03/07 19:02:43 djm Exp $ */
2/*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * Rhosts or /etc/hosts.equiv authentication combined with RSA host
7 * authentication.
8 *
9 * As far as I am concerned, the code I have written for this software
10 * can be used freely for any purpose. Any derived versions of this
11 * software must be clearly marked as such, and if the derived work is
12 * incompatible with the protocol description in the RFC file, it must be
13 * called by a name other than "ssh" or "Secure Shell".
14 */
15
16#include "includes.h"
17
18#ifdef WITH_SSH1
19
20#include <sys/types.h>
21
22#include <pwd.h>
23#include <stdarg.h>
24
25#include "packet.h"
26#include "uidswap.h"
27#include "log.h"
28#include "buffer.h"
29#include "misc.h"
30#include "servconf.h"
31#include "key.h"
32#include "hostfile.h"
33#include "pathnames.h"
34#include "auth.h"
35#include "canohost.h"
36#ifdef GSSAPI
37#include "ssh-gss.h"
38#endif
39#include "monitor_wrap.h"
40
41/* import */
42extern ServerOptions options;
43
44int
45auth_rhosts_rsa_key_allowed(struct passwd *pw, const char *cuser,
46 const char *chost, Key *client_host_key)
47{
48 HostStatus host_status;
49
50 if (auth_key_is_revoked(client_host_key))
51 return 0;
52
53 /* Check if we would accept it using rhosts authentication. */
54 if (!auth_rhosts(pw, cuser))
55 return 0;
56
57 host_status = check_key_in_hostfiles(pw, client_host_key,
58 chost, _PATH_SSH_SYSTEM_HOSTFILE,
59 options.ignore_user_known_hosts ? NULL : _PATH_SSH_USER_HOSTFILE);
60
61 return (host_status == HOST_OK);
62}
63
64/*
65 * Tries to authenticate the user using the .rhosts file and the host using
66 * its host key. Returns true if authentication succeeds.
67 */
68int
69auth_rhosts_rsa(Authctxt *authctxt, char *cuser, Key *client_host_key)
70{
71 struct ssh *ssh = active_state; /* XXX */
72 const char *chost;
73 struct passwd *pw = authctxt->pw;
74
75 debug("Trying rhosts with RSA host authentication for client user %.100s",
76 cuser);
77
78 if (!authctxt->valid || client_host_key == NULL ||
79 client_host_key->rsa == NULL)
80 return 0;
81
82 chost = auth_get_canonical_hostname(ssh, options.use_dns);
83 debug("Rhosts RSA authentication: canonical host %.900s", chost);
84
85 if (!PRIVSEP(auth_rhosts_rsa_key_allowed(pw, cuser, chost, client_host_key))) {
86 debug("Rhosts with RSA host authentication denied: unknown or invalid host key");
87 packet_send_debug("Your host key cannot be verified: unknown or invalid host key.");
88 return 0;
89 }
90 /* A matching host key was found and is known. */
91
92 /* Perform the challenge-response dialog with the client for the host key. */
93 if (!auth_rsa_challenge_dialog(client_host_key)) {
94 logit("Client on %.800s failed to respond correctly to host authentication.",
95 chost);
96 return 0;
97 }
98 /*
99 * We have authenticated the user using .rhosts or /etc/hosts.equiv,
100 * and the host using RSA. We accept the authentication.
101 */
102
103 verbose("Rhosts with RSA host authentication accepted for %.100s, %.100s on %.700s.",
104 pw->pw_name, cuser, chost);
105 packet_send_debug("Rhosts with RSA host authentication accepted.");
106 return 1;
107}
108
109#endif /* WITH_SSH1 */
diff --git a/auth-rhosts.c b/auth-rhosts.c
index 0ef344712..ecf956f06 100644
--- a/auth-rhosts.c
+++ b/auth-rhosts.c
@@ -1,4 +1,4 @@
1/* $OpenBSD: auth-rhosts.c,v 1.47 2016/03/07 19:02:43 djm Exp $ */ 1/* $OpenBSD: auth-rhosts.c,v 1.48 2016/08/13 17:47:41 markus Exp $ */
2/* 2/*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi> 3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -186,20 +186,8 @@ check_rhosts_file(const char *filename, const char *hostname,
186 * true if authentication succeeds. If ignore_rhosts is true, only 186 * true if authentication succeeds. If ignore_rhosts is true, only
187 * /etc/hosts.equiv will be considered (.rhosts and .shosts are ignored). 187 * /etc/hosts.equiv will be considered (.rhosts and .shosts are ignored).
188 */ 188 */
189
190int 189int
191auth_rhosts(struct passwd *pw, const char *client_user) 190auth_rhosts2(struct passwd *pw, const char *client_user, const char *hostname,
192{
193 struct ssh *ssh = active_state; /* XXX */
194 const char *hostname, *ipaddr;
195
196 hostname = auth_get_canonical_hostname(ssh, options.use_dns);
197 ipaddr = ssh_remote_ipaddr(ssh);
198 return auth_rhosts2(pw, client_user, hostname, ipaddr);
199}
200
201static int
202auth_rhosts2_raw(struct passwd *pw, const char *client_user, const char *hostname,
203 const char *ipaddr) 191 const char *ipaddr)
204{ 192{
205 char buf[1024]; 193 char buf[1024];
@@ -334,10 +322,3 @@ auth_rhosts2_raw(struct passwd *pw, const char *client_user, const char *hostnam
334 restore_uid(); 322 restore_uid();
335 return 0; 323 return 0;
336} 324}
337
338int
339auth_rhosts2(struct passwd *pw, const char *client_user, const char *hostname,
340 const char *ipaddr)
341{
342 return auth_rhosts2_raw(pw, client_user, hostname, ipaddr);
343}
diff --git a/auth-rsa.c b/auth-rsa.c
deleted file mode 100644
index cbd971be1..000000000
--- a/auth-rsa.c
+++ /dev/null
@@ -1,349 +0,0 @@
1/* $OpenBSD: auth-rsa.c,v 1.90 2015/01/28 22:36:00 djm Exp $ */
2/*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5 * All rights reserved
6 * RSA-based authentication. This code determines whether to admit a login
7 * based on RSA authentication. This file also contains functions to check
8 * validity of the host key.
9 *
10 * As far as I am concerned, the code I have written for this software
11 * can be used freely for any purpose. Any derived versions of this
12 * software must be clearly marked as such, and if the derived work is
13 * incompatible with the protocol description in the RFC file, it must be
14 * called by a name other than "ssh" or "Secure Shell".
15 */
16
17#include "includes.h"
18
19#ifdef WITH_SSH1
20
21#include <sys/types.h>
22#include <sys/stat.h>
23
24#include <openssl/rsa.h>
25
26#include <pwd.h>
27#include <stdio.h>
28#include <stdarg.h>
29#include <string.h>
30
31#include "xmalloc.h"
32#include "rsa.h"
33#include "packet.h"
34#include "ssh1.h"
35#include "uidswap.h"
36#include "match.h"
37#include "buffer.h"
38#include "pathnames.h"
39#include "log.h"
40#include "misc.h"
41#include "servconf.h"
42#include "key.h"
43#include "auth-options.h"
44#include "hostfile.h"
45#include "auth.h"
46#ifdef GSSAPI
47#include "ssh-gss.h"
48#endif
49#include "monitor_wrap.h"
50#include "ssh.h"
51
52#include "digest.h"
53
54/* import */
55extern ServerOptions options;
56
57/*
58 * Session identifier that is used to bind key exchange and authentication
59 * responses to a particular session.
60 */
61extern u_char session_id[16];
62
63/*
64 * The .ssh/authorized_keys file contains public keys, one per line, in the
65 * following format:
66 * options bits e n comment
67 * where bits, e and n are decimal numbers,
68 * and comment is any string of characters up to newline. The maximum
69 * length of a line is SSH_MAX_PUBKEY_BYTES characters. See sshd(8) for a
70 * description of the options.
71 */
72
73BIGNUM *
74auth_rsa_generate_challenge(Key *key)
75{
76 BIGNUM *challenge;
77 BN_CTX *ctx;
78
79 if ((challenge = BN_new()) == NULL)
80 fatal("auth_rsa_generate_challenge: BN_new() failed");
81 /* Generate a random challenge. */
82 if (BN_rand(challenge, 256, 0, 0) == 0)
83 fatal("auth_rsa_generate_challenge: BN_rand failed");
84 if ((ctx = BN_CTX_new()) == NULL)
85 fatal("auth_rsa_generate_challenge: BN_CTX_new failed");
86 if (BN_mod(challenge, challenge, key->rsa->n, ctx) == 0)
87 fatal("auth_rsa_generate_challenge: BN_mod failed");
88 BN_CTX_free(ctx);
89
90 return challenge;
91}
92
93int
94auth_rsa_verify_response(Key *key, BIGNUM *challenge, u_char response[16])
95{
96 u_char buf[32], mdbuf[16];
97 struct ssh_digest_ctx *md;
98 int len;
99
100 /* don't allow short keys */
101 if (BN_num_bits(key->rsa->n) < SSH_RSA_MINIMUM_MODULUS_SIZE) {
102 error("%s: RSA modulus too small: %d < minimum %d bits",
103 __func__,
104 BN_num_bits(key->rsa->n), SSH_RSA_MINIMUM_MODULUS_SIZE);
105 return (0);
106 }
107
108 /* The response is MD5 of decrypted challenge plus session id. */
109 len = BN_num_bytes(challenge);
110 if (len <= 0 || len > 32)
111 fatal("%s: bad challenge length %d", __func__, len);
112 memset(buf, 0, 32);
113 BN_bn2bin(challenge, buf + 32 - len);
114 if ((md = ssh_digest_start(SSH_DIGEST_MD5)) == NULL ||
115 ssh_digest_update(md, buf, 32) < 0 ||
116 ssh_digest_update(md, session_id, 16) < 0 ||
117 ssh_digest_final(md, mdbuf, sizeof(mdbuf)) < 0)
118 fatal("%s: md5 failed", __func__);
119 ssh_digest_free(md);
120
121 /* Verify that the response is the original challenge. */
122 if (timingsafe_bcmp(response, mdbuf, 16) != 0) {
123 /* Wrong answer. */
124 return (0);
125 }
126 /* Correct answer. */
127 return (1);
128}
129
130/*
131 * Performs the RSA authentication challenge-response dialog with the client,
132 * and returns true (non-zero) if the client gave the correct answer to
133 * our challenge; returns zero if the client gives a wrong answer.
134 */
135
136int
137auth_rsa_challenge_dialog(Key *key)
138{
139 BIGNUM *challenge, *encrypted_challenge;
140 u_char response[16];
141 int i, success;
142
143 if ((encrypted_challenge = BN_new()) == NULL)
144 fatal("auth_rsa_challenge_dialog: BN_new() failed");
145
146 challenge = PRIVSEP(auth_rsa_generate_challenge(key));
147
148 /* Encrypt the challenge with the public key. */
149 if (rsa_public_encrypt(encrypted_challenge, challenge, key->rsa) != 0)
150 fatal("%s: rsa_public_encrypt failed", __func__);
151
152 /* Send the encrypted challenge to the client. */
153 packet_start(SSH_SMSG_AUTH_RSA_CHALLENGE);
154 packet_put_bignum(encrypted_challenge);
155 packet_send();
156 BN_clear_free(encrypted_challenge);
157 packet_write_wait();
158
159 /* Wait for a response. */
160 packet_read_expect(SSH_CMSG_AUTH_RSA_RESPONSE);
161 for (i = 0; i < 16; i++)
162 response[i] = (u_char)packet_get_char();
163 packet_check_eom();
164
165 success = PRIVSEP(auth_rsa_verify_response(key, challenge, response));
166 BN_clear_free(challenge);
167 return (success);
168}
169
170static int
171rsa_key_allowed_in_file(struct passwd *pw, char *file,
172 const BIGNUM *client_n, Key **rkey)
173{
174 char *fp, line[SSH_MAX_PUBKEY_BYTES];
175 int allowed = 0, bits;
176 FILE *f;
177 u_long linenum = 0;
178 Key *key;
179
180 debug("trying public RSA key file %s", file);
181 if ((f = auth_openkeyfile(file, pw, options.strict_modes)) == NULL)
182 return 0;
183
184 /*
185 * Go though the accepted keys, looking for the current key. If
186 * found, perform a challenge-response dialog to verify that the
187 * user really has the corresponding private key.
188 */
189 key = key_new(KEY_RSA1);
190 while (read_keyfile_line(f, file, line, sizeof(line), &linenum) != -1) {
191 char *cp;
192 char *key_options;
193 int keybits;
194
195 /* Skip leading whitespace, empty and comment lines. */
196 for (cp = line; *cp == ' ' || *cp == '\t'; cp++)
197 ;
198 if (!*cp || *cp == '\n' || *cp == '#')
199 continue;
200
201 /*
202 * Check if there are options for this key, and if so,
203 * save their starting address and skip the option part
204 * for now. If there are no options, set the starting
205 * address to NULL.
206 */
207 if (*cp < '0' || *cp > '9') {
208 int quoted = 0;
209 key_options = cp;
210 for (; *cp && (quoted || (*cp != ' ' && *cp != '\t')); cp++) {
211 if (*cp == '\\' && cp[1] == '"')
212 cp++; /* Skip both */
213 else if (*cp == '"')
214 quoted = !quoted;
215 }
216 } else
217 key_options = NULL;
218
219 /* Parse the key from the line. */
220 if (hostfile_read_key(&cp, &bits, key) == 0) {
221 debug("%.100s, line %lu: non ssh1 key syntax",
222 file, linenum);
223 continue;
224 }
225 /* cp now points to the comment part. */
226
227 /*
228 * Check if the we have found the desired key (identified
229 * by its modulus).
230 */
231 if (BN_cmp(key->rsa->n, client_n) != 0)
232 continue;
233
234 /* check the real bits */
235 keybits = BN_num_bits(key->rsa->n);
236 if (keybits < 0 || bits != keybits)
237 logit("Warning: %s, line %lu: keysize mismatch: "
238 "actual %d vs. announced %d.",
239 file, linenum, BN_num_bits(key->rsa->n), bits);
240
241 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash,
242 SSH_FP_DEFAULT)) == NULL)
243 continue;
244 debug("matching key found: file %s, line %lu %s %s",
245 file, linenum, key_type(key), fp);
246 free(fp);
247
248 /* Never accept a revoked key */
249 if (auth_key_is_revoked(key))
250 break;
251
252 /* We have found the desired key. */
253 /*
254 * If our options do not allow this key to be used,
255 * do not send challenge.
256 */
257 if (!auth_parse_options(pw, key_options, file, linenum))
258 continue;
259 if (key_is_cert_authority)
260 continue;
261 /* break out, this key is allowed */
262 allowed = 1;
263 break;
264 }
265
266 /* Close the file. */
267 fclose(f);
268
269 /* return key if allowed */
270 if (allowed && rkey != NULL)
271 *rkey = key;
272 else
273 key_free(key);
274
275 return allowed;
276}
277
278/*
279 * check if there's user key matching client_n,
280 * return key if login is allowed, NULL otherwise
281 */
282
283int
284auth_rsa_key_allowed(struct passwd *pw, BIGNUM *client_n, Key **rkey)
285{
286 char *file;
287 u_int i, allowed = 0;
288
289 temporarily_use_uid(pw);
290
291 for (i = 0; !allowed && i < options.num_authkeys_files; i++) {
292 if (strcasecmp(options.authorized_keys_files[i], "none") == 0)
293 continue;
294 file = expand_authorized_keys(
295 options.authorized_keys_files[i], pw);
296 allowed = rsa_key_allowed_in_file(pw, file, client_n, rkey);
297 free(file);
298 }
299
300 restore_uid();
301
302 return allowed;
303}
304
305/*
306 * Performs the RSA authentication dialog with the client. This returns
307 * 0 if the client could not be authenticated, and 1 if authentication was
308 * successful. This may exit if there is a serious protocol violation.
309 */
310int
311auth_rsa(Authctxt *authctxt, BIGNUM *client_n)
312{
313 Key *key;
314 struct passwd *pw = authctxt->pw;
315
316 /* no user given */
317 if (!authctxt->valid)
318 return 0;
319
320 if (!PRIVSEP(auth_rsa_key_allowed(pw, client_n, &key))) {
321 auth_clear_options();
322 return (0);
323 }
324
325 /* Perform the challenge-response dialog for this key. */
326 if (!auth_rsa_challenge_dialog(key)) {
327 /* Wrong response. */
328 verbose("Wrong response to RSA authentication challenge.");
329 packet_send_debug("Wrong response to RSA authentication challenge.");
330 /*
331 * Break out of the loop. Otherwise we might send
332 * another challenge and break the protocol.
333 */
334 key_free(key);
335 return (0);
336 }
337 /*
338 * Correct response. The client has been successfully
339 * authenticated. Note that we have not yet processed the
340 * options; this will be reset if the options cause the
341 * authentication to be rejected.
342 */
343 pubkey_auth_info(authctxt, key, NULL);
344
345 packet_send_debug("RSA authentication accepted.");
346 return (1);
347}
348
349#endif /* WITH_SSH1 */
diff --git a/auth.c b/auth.c
index 24527dd7c..b6a440213 100644
--- a/auth.c
+++ b/auth.c
@@ -1,4 +1,4 @@
1/* $OpenBSD: auth.c,v 1.115 2016/06/15 00:40:40 dtucker Exp $ */ 1/* $OpenBSD: auth.c,v 1.116 2016/08/13 17:47:41 markus Exp $ */
2/* 2/*
3 * Copyright (c) 2000 Markus Friedl. All rights reserved. 3 * Copyright (c) 2000 Markus Friedl. All rights reserved.
4 * 4 *
@@ -298,7 +298,7 @@ auth_log(Authctxt *authctxt, int authenticated, int partial,
298 else 298 else
299 authmsg = authenticated ? "Accepted" : "Failed"; 299 authmsg = authenticated ? "Accepted" : "Failed";
300 300
301 authlog("%s %s%s%s for %s%.100s from %.200s port %d %s%s%s", 301 authlog("%s %s%s%s for %s%.100s from %.200s port %d ssh2%s%s",
302 authmsg, 302 authmsg,
303 method, 303 method,
304 submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod, 304 submethod != NULL ? "/" : "", submethod == NULL ? "" : submethod,
@@ -306,7 +306,6 @@ auth_log(Authctxt *authctxt, int authenticated, int partial,
306 authctxt->user, 306 authctxt->user,
307 ssh_remote_ipaddr(ssh), 307 ssh_remote_ipaddr(ssh),
308 ssh_remote_port(ssh), 308 ssh_remote_port(ssh),
309 compat20 ? "ssh2" : "ssh1",
310 authctxt->info != NULL ? ": " : "", 309 authctxt->info != NULL ? ": " : "",
311 authctxt->info != NULL ? authctxt->info : ""); 310 authctxt->info != NULL ? authctxt->info : "");
312 free(authctxt->info); 311 free(authctxt->info);
@@ -339,12 +338,11 @@ auth_maxtries_exceeded(Authctxt *authctxt)
339 struct ssh *ssh = active_state; /* XXX */ 338 struct ssh *ssh = active_state; /* XXX */
340 339
341 error("maximum authentication attempts exceeded for " 340 error("maximum authentication attempts exceeded for "
342 "%s%.100s from %.200s port %d %s", 341 "%s%.100s from %.200s port %d ssh2",
343 authctxt->valid ? "" : "invalid user ", 342 authctxt->valid ? "" : "invalid user ",
344 authctxt->user, 343 authctxt->user,
345 ssh_remote_ipaddr(ssh), 344 ssh_remote_ipaddr(ssh),
346 ssh_remote_port(ssh), 345 ssh_remote_port(ssh));
347 compat20 ? "ssh2" : "ssh1");
348 packet_disconnect("Too many authentication failures"); 346 packet_disconnect("Too many authentication failures");
349 /* NOTREACHED */ 347 /* NOTREACHED */
350} 348}
diff --git a/auth.h b/auth.h
index 55170af50..338a62da7 100644
--- a/auth.h
+++ b/auth.h
@@ -1,4 +1,4 @@
1/* $OpenBSD: auth.h,v 1.88 2016/05/04 14:04:40 markus Exp $ */ 1/* $OpenBSD: auth.h,v 1.89 2016/08/13 17:47:41 markus Exp $ */
2 2
3/* 3/*
4 * Copyright (c) 2000 Markus Friedl. All rights reserved. 4 * Copyright (c) 2000 Markus Friedl. All rights reserved.
@@ -112,20 +112,11 @@ struct KbdintDevice
112 void (*free_ctx)(void *ctx); 112 void (*free_ctx)(void *ctx);
113}; 113};
114 114
115int auth_rhosts(struct passwd *, const char *);
116int 115int
117auth_rhosts2(struct passwd *, const char *, const char *, const char *); 116auth_rhosts2(struct passwd *, const char *, const char *, const char *);
118 117
119int auth_rhosts_rsa(Authctxt *, char *, Key *);
120int auth_password(Authctxt *, const char *); 118int auth_password(Authctxt *, const char *);
121int auth_rsa(Authctxt *, BIGNUM *); 119
122int auth_rsa_challenge_dialog(Key *);
123BIGNUM *auth_rsa_generate_challenge(Key *);
124int auth_rsa_verify_response(Key *, BIGNUM *, u_char[]);
125int auth_rsa_key_allowed(struct passwd *, BIGNUM *, Key **);
126
127int auth_rhosts_rsa_key_allowed(struct passwd *, const char *,
128 const char *, Key *);
129int hostbased_key_allowed(struct passwd *, const char *, char *, Key *); 120int hostbased_key_allowed(struct passwd *, const char *, char *, Key *);
130int user_key_allowed(struct passwd *, Key *, int); 121int user_key_allowed(struct passwd *, Key *, int);
131void pubkey_auth_info(Authctxt *, const Key *, const char *, ...) 122void pubkey_auth_info(Authctxt *, const Key *, const char *, ...)
@@ -156,7 +147,6 @@ void remove_kbdint_device(const char *);
156 147
157void disable_forwarding(void); 148void disable_forwarding(void);
158 149
159void do_authentication(Authctxt *);
160void do_authentication2(Authctxt *); 150void do_authentication2(Authctxt *);
161 151
162void auth_info(Authctxt *authctxt, const char *, ...) 152void auth_info(Authctxt *authctxt, const char *, ...)
@@ -187,10 +177,6 @@ int skey_respond(void *, u_int, char **);
187int allowed_user(struct passwd *); 177int allowed_user(struct passwd *);
188struct passwd * getpwnamallow(const char *user); 178struct passwd * getpwnamallow(const char *user);
189 179
190char *get_challenge(Authctxt *);
191int verify_response(Authctxt *, const char *);
192void abandon_challenge_response(Authctxt *);
193
194char *expand_authorized_keys(const char *, struct passwd *pw); 180char *expand_authorized_keys(const char *, struct passwd *pw);
195char *authorized_principals_file(struct passwd *); 181char *authorized_principals_file(struct passwd *);
196 182
@@ -210,7 +196,6 @@ Key *get_hostkey_public_by_index(int, struct ssh *);
210Key *get_hostkey_public_by_type(int, int, struct ssh *); 196Key *get_hostkey_public_by_type(int, int, struct ssh *);
211Key *get_hostkey_private_by_type(int, int, struct ssh *); 197Key *get_hostkey_private_by_type(int, int, struct ssh *);
212int get_hostkey_index(Key *, int, struct ssh *); 198int get_hostkey_index(Key *, int, struct ssh *);
213int ssh1_session_key(BIGNUM *);
214int sshd_hostkey_sign(Key *, Key *, u_char **, size_t *, 199int sshd_hostkey_sign(Key *, Key *, u_char **, size_t *,
215 const u_char *, size_t, const char *, u_int); 200 const u_char *, size_t, const char *, u_int);
216 201
diff --git a/auth1.c b/auth1.c
deleted file mode 100644
index 5073c49bb..000000000
--- a/auth1.c
+++ /dev/null
@@ -1,444 +0,0 @@
1/* $OpenBSD: auth1.c,v 1.82 2014/07/15 15:54:14 millert Exp $ */
2/*
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 * All rights reserved
5 *
6 * As far as I am concerned, the code I have written for this software
7 * can be used freely for any purpose. Any derived versions of this
8 * software must be clearly marked as such, and if the derived work is
9 * incompatible with the protocol description in the RFC file, it must be
10 * called by a name other than "ssh" or "Secure Shell".
11 */
12
13#include "includes.h"
14
15#ifdef WITH_SSH1
16
17#include <sys/types.h>
18
19#include <stdarg.h>
20#include <stdio.h>
21#include <string.h>
22#include <unistd.h>
23#include <pwd.h>
24
25#include "openbsd-compat/sys-queue.h"
26#include "xmalloc.h"
27#include "rsa.h"
28#include "ssh1.h"
29#include "packet.h"
30#include "buffer.h"
31#include "log.h"
32#include "misc.h"
33#include "servconf.h"
34#include "compat.h"
35#include "key.h"
36#include "hostfile.h"
37#include "auth.h"
38#include "channels.h"
39#include "session.h"
40#include "uidswap.h"
41#ifdef GSSAPI
42#include "ssh-gss.h"
43#endif
44#include "monitor_wrap.h"
45#include "buffer.h"
46
47/* import */
48extern ServerOptions options;
49extern Buffer loginmsg;
50
51static int auth1_process_password(Authctxt *);
52static int auth1_process_rsa(Authctxt *);
53static int auth1_process_rhosts_rsa(Authctxt *);
54static int auth1_process_tis_challenge(Authctxt *);
55static int auth1_process_tis_response(Authctxt *);
56
57static char *client_user = NULL; /* Used to fill in remote user for PAM */
58
59struct AuthMethod1 {
60 int type;
61 char *name;
62 int *enabled;
63 int (*method)(Authctxt *);
64};
65
66const struct AuthMethod1 auth1_methods[] = {
67 {
68 SSH_CMSG_AUTH_PASSWORD, "password",
69 &options.password_authentication, auth1_process_password
70 },
71 {
72 SSH_CMSG_AUTH_RSA, "rsa",
73 &options.rsa_authentication, auth1_process_rsa
74 },
75 {
76 SSH_CMSG_AUTH_RHOSTS_RSA, "rhosts-rsa",
77 &options.rhosts_rsa_authentication, auth1_process_rhosts_rsa
78 },
79 {
80 SSH_CMSG_AUTH_TIS, "challenge-response",
81 &options.challenge_response_authentication,
82 auth1_process_tis_challenge
83 },
84 {
85 SSH_CMSG_AUTH_TIS_RESPONSE, "challenge-response",
86 &options.challenge_response_authentication,
87 auth1_process_tis_response
88 },
89 { -1, NULL, NULL, NULL}
90};
91
92static const struct AuthMethod1
93*lookup_authmethod1(int type)
94{
95 int i;
96
97 for (i = 0; auth1_methods[i].name != NULL; i++)
98 if (auth1_methods[i].type == type)
99 return (&(auth1_methods[i]));
100
101 return (NULL);
102}
103
104static char *
105get_authname(int type)
106{
107 const struct AuthMethod1 *a;
108 static char buf[64];
109
110 if ((a = lookup_authmethod1(type)) != NULL)
111 return (a->name);
112 snprintf(buf, sizeof(buf), "bad-auth-msg-%d", type);
113 return (buf);
114}
115
116/*ARGSUSED*/
117static int
118auth1_process_password(Authctxt *authctxt)
119{
120 int authenticated = 0;
121 char *password;
122 u_int dlen;
123
124 /*
125 * Read user password. It is in plain text, but was
126 * transmitted over the encrypted channel so it is
127 * not visible to an outside observer.
128 */
129 password = packet_get_string(&dlen);
130 packet_check_eom();
131
132 /* Try authentication with the password. */
133 authenticated = PRIVSEP(auth_password(authctxt, password));
134
135 explicit_bzero(password, dlen);
136 free(password);
137
138 return (authenticated);
139}
140
141/*ARGSUSED*/
142static int
143auth1_process_rsa(Authctxt *authctxt)
144{
145 int authenticated = 0;
146 BIGNUM *n;
147
148 /* RSA authentication requested. */
149 if ((n = BN_new()) == NULL)
150 fatal("do_authloop: BN_new failed");
151 packet_get_bignum(n);
152 packet_check_eom();
153 authenticated = auth_rsa(authctxt, n);
154 BN_clear_free(n);
155
156 return (authenticated);
157}
158
159/*ARGSUSED*/
160static int
161auth1_process_rhosts_rsa(Authctxt *authctxt)
162{
163 int keybits, authenticated = 0;
164 u_int bits;
165 Key *client_host_key;
166 u_int ulen;
167
168 /*
169 * Get client user name. Note that we just have to
170 * trust the client; root on the client machine can
171 * claim to be any user.
172 */
173 client_user = packet_get_cstring(&ulen);
174
175 /* Get the client host key. */
176 client_host_key = key_new(KEY_RSA1);
177 bits = packet_get_int();
178 packet_get_bignum(client_host_key->rsa->e);
179 packet_get_bignum(client_host_key->rsa->n);
180
181 keybits = BN_num_bits(client_host_key->rsa->n);
182 if (keybits < 0 || bits != (u_int)keybits) {
183 verbose("Warning: keysize mismatch for client_host_key: "
184 "actual %d, announced %d",
185 BN_num_bits(client_host_key->rsa->n), bits);
186 }
187 packet_check_eom();
188
189 authenticated = auth_rhosts_rsa(authctxt, client_user,
190 client_host_key);
191 key_free(client_host_key);
192
193 auth_info(authctxt, "ruser %.100s", client_user);
194
195 return (authenticated);
196}
197
198/*ARGSUSED*/
199static int
200auth1_process_tis_challenge(Authctxt *authctxt)
201{
202 char *challenge;
203
204 if ((challenge = get_challenge(authctxt)) == NULL)
205 return (0);
206
207 debug("sending challenge '%s'", challenge);
208 packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE);
209 packet_put_cstring(challenge);
210 free(challenge);
211 packet_send();
212 packet_write_wait();
213
214 return (-1);
215}
216
217/*ARGSUSED*/
218static int
219auth1_process_tis_response(Authctxt *authctxt)
220{
221 int authenticated = 0;
222 char *response;
223 u_int dlen;
224
225 response = packet_get_string(&dlen);
226 packet_check_eom();
227 authenticated = verify_response(authctxt, response);
228 explicit_bzero(response, dlen);
229 free(response);
230
231 return (authenticated);
232}
233
234/*
235 * read packets, try to authenticate the user and
236 * return only if authentication is successful
237 */
238static void
239do_authloop(Authctxt *authctxt)
240{
241 int authenticated = 0;
242 int prev = 0, type = 0;
243 const struct AuthMethod1 *meth;
244
245 debug("Attempting authentication for %s%.100s.",
246 authctxt->valid ? "" : "invalid user ", authctxt->user);
247
248 /* If the user has no password, accept authentication immediately. */
249 if (options.permit_empty_passwd && options.password_authentication &&
250#ifdef KRB5
251 (!options.kerberos_authentication || options.kerberos_or_local_passwd) &&
252#endif
253 PRIVSEP(auth_password(authctxt, ""))) {
254#ifdef USE_PAM
255 if (options.use_pam && (PRIVSEP(do_pam_account())))
256#endif
257 {
258 auth_log(authctxt, 1, 0, "without authentication",
259 NULL);
260 return;
261 }
262 }
263
264 /* Indicate that authentication is needed. */
265 packet_start(SSH_SMSG_FAILURE);
266 packet_send();
267 packet_write_wait();
268
269 for (;;) {
270 /* default to fail */
271 authenticated = 0;
272
273
274 /* Get a packet from the client. */
275 prev = type;
276 type = packet_read();
277
278 /*
279 * If we started challenge-response authentication but the
280 * next packet is not a response to our challenge, release
281 * the resources allocated by get_challenge() (which would
282 * normally have been released by verify_response() had we
283 * received such a response)
284 */
285 if (prev == SSH_CMSG_AUTH_TIS &&
286 type != SSH_CMSG_AUTH_TIS_RESPONSE)
287 abandon_challenge_response(authctxt);
288
289 if (authctxt->failures >= options.max_authtries)
290 goto skip;
291 if ((meth = lookup_authmethod1(type)) == NULL) {
292 logit("Unknown message during authentication: "
293 "type %d", type);
294 goto skip;
295 }
296
297 if (!*(meth->enabled)) {
298 verbose("%s authentication disabled.", meth->name);
299 goto skip;
300 }
301
302 authenticated = meth->method(authctxt);
303 if (authenticated == -1)
304 continue; /* "postponed" */
305
306#ifdef BSD_AUTH
307 if (authctxt->as) {
308 auth_close(authctxt->as);
309 authctxt->as = NULL;
310 }
311#endif
312 if (!authctxt->valid && authenticated)
313 fatal("INTERNAL ERROR: authenticated invalid user %s",
314 authctxt->user);
315
316#ifdef _UNICOS
317 if (authenticated && cray_access_denied(authctxt->user)) {
318 authenticated = 0;
319 fatal("Access denied for user %s.",authctxt->user);
320 }
321#endif /* _UNICOS */
322
323#ifndef HAVE_CYGWIN
324 /* Special handling for root */
325 if (authenticated && authctxt->pw->pw_uid == 0 &&
326 !auth_root_allowed(meth->name)) {
327 authenticated = 0;
328# ifdef SSH_AUDIT_EVENTS
329 PRIVSEP(audit_event(SSH_LOGIN_ROOT_DENIED));
330# endif
331 }
332#endif
333
334#ifdef USE_PAM
335 if (options.use_pam && authenticated &&
336 !PRIVSEP(do_pam_account())) {
337 char *msg;
338 size_t len;
339
340 error("Access denied for user %s by PAM account "
341 "configuration", authctxt->user);
342 len = buffer_len(&loginmsg);
343 buffer_append(&loginmsg, "\0", 1);
344 msg = buffer_ptr(&loginmsg);
345 /* strip trailing newlines */
346 if (len > 0)
347 while (len > 0 && msg[--len] == '\n')
348 msg[len] = '\0';
349 else
350 msg = "Access denied.";
351 packet_disconnect("%s", msg);
352 }
353#endif
354
355 skip:
356 /* Log before sending the reply */
357 auth_log(authctxt, authenticated, 0, get_authname(type), NULL);
358
359 free(client_user);
360 client_user = NULL;
361
362 if (authenticated)
363 return;
364
365 if (++authctxt->failures >= options.max_authtries) {
366#ifdef SSH_AUDIT_EVENTS
367 PRIVSEP(audit_event(SSH_LOGIN_EXCEED_MAXTRIES));
368#endif
369 auth_maxtries_exceeded(authctxt);
370 }
371
372 packet_start(SSH_SMSG_FAILURE);
373 packet_send();
374 packet_write_wait();
375 }
376}
377
378/*
379 * Performs authentication of an incoming connection. Session key has already
380 * been exchanged and encryption is enabled.
381 */
382void
383do_authentication(Authctxt *authctxt)
384{
385 u_int ulen;
386 char *user, *style = NULL;
387
388 /* Get the name of the user that we wish to log in as. */
389 packet_read_expect(SSH_CMSG_USER);
390
391 /* Get the user name. */
392 user = packet_get_cstring(&ulen);
393 packet_check_eom();
394
395 if ((style = strchr(user, ':')) != NULL)
396 *style++ = '\0';
397
398 authctxt->user = user;
399 authctxt->style = style;
400
401 /* Verify that the user is a valid user. */
402 if ((authctxt->pw = PRIVSEP(getpwnamallow(user))) != NULL)
403 authctxt->valid = 1;
404 else {
405 debug("do_authentication: invalid user %s", user);
406 authctxt->pw = fakepw();
407 }
408
409 /* Configuration may have changed as a result of Match */
410 if (options.num_auth_methods != 0)
411 fatal("AuthenticationMethods is not supported with SSH "
412 "protocol 1");
413
414 setproctitle("%s%s", authctxt->valid ? user : "unknown",
415 use_privsep ? " [net]" : "");
416
417#ifdef USE_PAM
418 if (options.use_pam)
419 PRIVSEP(start_pam(authctxt));
420#endif
421
422 /*
423 * If we are not running as root, the user must have the same uid as
424 * the server.
425 */
426#ifndef HAVE_CYGWIN
427 if (!use_privsep && getuid() != 0 && authctxt->pw &&
428 authctxt->pw->pw_uid != getuid())
429 packet_disconnect("Cannot change user when server not running as root.");
430#endif
431
432 /*
433 * Loop until the user has been authenticated or the connection is
434 * closed, do_authloop() returns only if authentication is successful
435 */
436 do_authloop(authctxt);
437
438 /* The user has been authenticated and accepted. */
439 packet_start(SSH_SMSG_SUCCESS);
440 packet_send();
441 packet_write_wait();
442}
443
444#endif /* WITH_SSH1 */
diff --git a/monitor.c b/monitor.c
index cb57bd066..59b05a98f 100644
--- a/monitor.c
+++ b/monitor.c
@@ -1,4 +1,4 @@
1/* $OpenBSD: monitor.c,v 1.161 2016/07/22 03:39:13 djm Exp $ */ 1/* $OpenBSD: monitor.c,v 1.162 2016/08/13 17:47:41 markus Exp $ */
2/* 2/*
3 * Copyright 2002 Niels Provos <provos@citi.umich.edu> 3 * Copyright 2002 Niels Provos <provos@citi.umich.edu>
4 * Copyright 2002 Markus Friedl <markus@openbsd.org> 4 * Copyright 2002 Markus Friedl <markus@openbsd.org>
@@ -169,10 +169,6 @@ static int monitor_read_log(struct monitor *);
169 169
170static Authctxt *authctxt; 170static Authctxt *authctxt;
171 171
172#ifdef WITH_SSH1
173static BIGNUM *ssh1_challenge = NULL; /* used for ssh1 rsa auth */
174#endif
175
176/* local state for key verify */ 172/* local state for key verify */
177static u_char *key_blob = NULL; 173static u_char *key_blob = NULL;
178static u_int key_bloblen = 0; 174static u_int key_bloblen = 0;
@@ -254,52 +250,6 @@ struct mon_table mon_dispatch_postauth20[] = {
254 {0, 0, NULL} 250 {0, 0, NULL}
255}; 251};
256 252
257struct mon_table mon_dispatch_proto15[] = {
258#ifdef WITH_SSH1
259 {MONITOR_REQ_PWNAM, MON_ONCE, mm_answer_pwnamallow},
260 {MONITOR_REQ_SESSKEY, MON_ONCE, mm_answer_sesskey},
261 {MONITOR_REQ_SESSID, MON_ONCE, mm_answer_sessid},
262 {MONITOR_REQ_AUTHPASSWORD, MON_AUTH, mm_answer_authpassword},
263 {MONITOR_REQ_RSAKEYALLOWED, MON_ISAUTH|MON_ALOG, mm_answer_rsa_keyallowed},
264 {MONITOR_REQ_KEYALLOWED, MON_ISAUTH|MON_ALOG, mm_answer_keyallowed},
265 {MONITOR_REQ_RSACHALLENGE, MON_ONCE, mm_answer_rsa_challenge},
266 {MONITOR_REQ_RSARESPONSE, MON_ONCE|MON_AUTHDECIDE, mm_answer_rsa_response},
267#ifdef BSD_AUTH
268 {MONITOR_REQ_BSDAUTHQUERY, MON_ISAUTH, mm_answer_bsdauthquery},
269 {MONITOR_REQ_BSDAUTHRESPOND, MON_AUTH, mm_answer_bsdauthrespond},
270#endif
271#ifdef SKEY
272 {MONITOR_REQ_SKEYQUERY, MON_ISAUTH, mm_answer_skeyquery},
273 {MONITOR_REQ_SKEYRESPOND, MON_AUTH, mm_answer_skeyrespond},
274#endif
275#ifdef USE_PAM
276 {MONITOR_REQ_PAM_START, MON_ONCE, mm_answer_pam_start},
277 {MONITOR_REQ_PAM_ACCOUNT, 0, mm_answer_pam_account},
278 {MONITOR_REQ_PAM_INIT_CTX, MON_ISAUTH, mm_answer_pam_init_ctx},
279 {MONITOR_REQ_PAM_QUERY, MON_ISAUTH, mm_answer_pam_query},
280 {MONITOR_REQ_PAM_RESPOND, MON_ISAUTH, mm_answer_pam_respond},
281 {MONITOR_REQ_PAM_FREE_CTX, MON_ONCE|MON_AUTHDECIDE, mm_answer_pam_free_ctx},
282#endif
283#ifdef SSH_AUDIT_EVENTS
284 {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
285#endif
286#endif /* WITH_SSH1 */
287 {0, 0, NULL}
288};
289
290struct mon_table mon_dispatch_postauth15[] = {
291#ifdef WITH_SSH1
292 {MONITOR_REQ_PTY, MON_ONCE, mm_answer_pty},
293 {MONITOR_REQ_PTYCLEANUP, MON_ONCE, mm_answer_pty_cleanup},
294 {MONITOR_REQ_TERM, 0, mm_answer_term},
295#ifdef SSH_AUDIT_EVENTS
296 {MONITOR_REQ_AUDIT_EVENT, MON_PERMIT, mm_answer_audit_event},
297 {MONITOR_REQ_AUDIT_COMMAND, MON_PERMIT|MON_ONCE, mm_answer_audit_command},
298#endif
299#endif /* WITH_SSH1 */
300 {0, 0, NULL}
301};
302
303struct mon_table *mon_dispatch; 253struct mon_table *mon_dispatch;
304 254
305/* Specifies if a certain message is allowed at the moment */ 255/* Specifies if a certain message is allowed at the moment */
@@ -348,17 +298,10 @@ monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor)
348 298
349 authctxt->loginmsg = &loginmsg; 299 authctxt->loginmsg = &loginmsg;
350 300
351 if (compat20) { 301 mon_dispatch = mon_dispatch_proto20;
352 mon_dispatch = mon_dispatch_proto20; 302 /* Permit requests for moduli and signatures */
353 303 monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
354 /* Permit requests for moduli and signatures */ 304 monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
355 monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
356 monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
357 } else {
358 mon_dispatch = mon_dispatch_proto15;
359
360 monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 1);
361 }
362 305
363 /* The first few requests do not require asynchronous access */ 306 /* The first few requests do not require asynchronous access */
364 while (!authenticated) { 307 while (!authenticated) {
@@ -369,9 +312,6 @@ monitor_child_preauth(Authctxt *_authctxt, struct monitor *pmonitor)
369 312
370 /* Special handling for multiple required authentications */ 313 /* Special handling for multiple required authentications */
371 if (options.num_auth_methods != 0) { 314 if (options.num_auth_methods != 0) {
372 if (!compat20)
373 fatal("AuthenticationMethods is not supported"
374 "with SSH protocol 1");
375 if (authenticated && 315 if (authenticated &&
376 !auth2_update_methods_lists(authctxt, 316 !auth2_update_methods_lists(authctxt,
377 auth_method, auth_submethod)) { 317 auth_method, auth_submethod)) {
@@ -455,17 +395,13 @@ monitor_child_postauth(struct monitor *pmonitor)
455 signal(SIGXFSZ, SIG_IGN); 395 signal(SIGXFSZ, SIG_IGN);
456#endif 396#endif
457 397
458 if (compat20) { 398 mon_dispatch = mon_dispatch_postauth20;
459 mon_dispatch = mon_dispatch_postauth20; 399
400 /* Permit requests for moduli and signatures */
401 monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
402 monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
403 monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
460 404
461 /* Permit requests for moduli and signatures */
462 monitor_permit(mon_dispatch, MONITOR_REQ_MODULI, 1);
463 monitor_permit(mon_dispatch, MONITOR_REQ_SIGN, 1);
464 monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
465 } else {
466 mon_dispatch = mon_dispatch_postauth15;
467 monitor_permit(mon_dispatch, MONITOR_REQ_TERM, 1);
468 }
469 if (!no_pty_flag) { 405 if (!no_pty_flag) {
470 monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1); 406 monitor_permit(mon_dispatch, MONITOR_REQ_PTY, 1);
471 monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1); 407 monitor_permit(mon_dispatch, MONITOR_REQ_PTYCLEANUP, 1);
@@ -845,7 +781,7 @@ mm_answer_pwnamallow(int sock, Buffer *m)
845#undef M_CP_STRARRAYOPT 781#undef M_CP_STRARRAYOPT
846 782
847 /* Create valid auth method lists */ 783 /* Create valid auth method lists */
848 if (compat20 && auth2_setup_methods_lists(authctxt) != 0) { 784 if (auth2_setup_methods_lists(authctxt) != 0) {
849 /* 785 /*
850 * The monitor will continue long enough to let the child 786 * The monitor will continue long enough to let the child
851 * run to it's packet_disconnect(), but it must not allow any 787 * run to it's packet_disconnect(), but it must not allow any
@@ -857,14 +793,10 @@ mm_answer_pwnamallow(int sock, Buffer *m)
857 debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed); 793 debug3("%s: sending MONITOR_ANS_PWNAM: %d", __func__, allowed);
858 mm_request_send(sock, MONITOR_ANS_PWNAM, m); 794 mm_request_send(sock, MONITOR_ANS_PWNAM, m);
859 795
860 /* For SSHv1 allow authentication now */ 796 /* Allow service/style information on the auth context */
861 if (!compat20) 797 monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
862 monitor_permit_authentications(1); 798 monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
863 else { 799
864 /* Allow service/style information on the auth context */
865 monitor_permit(mon_dispatch, MONITOR_REQ_AUTHSERV, 1);
866 monitor_permit(mon_dispatch, MONITOR_REQ_AUTH2_READ_BANNER, 1);
867 }
868#ifdef USE_PAM 800#ifdef USE_PAM
869 if (options.use_pam) 801 if (options.use_pam)
870 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_START, 1); 802 monitor_permit(mon_dispatch, MONITOR_REQ_PAM_START, 1);
@@ -991,11 +923,8 @@ mm_answer_bsdauthrespond(int sock, Buffer *m)
991 debug3("%s: sending authenticated: %d", __func__, authok); 923 debug3("%s: sending authenticated: %d", __func__, authok);
992 mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m); 924 mm_request_send(sock, MONITOR_ANS_BSDAUTHRESPOND, m);
993 925
994 if (compat20) { 926 auth_method = "keyboard-interactive";
995 auth_method = "keyboard-interactive"; 927 auth_submethod = "bsdauth";
996 auth_submethod = "bsdauth";
997 } else
998 auth_method = "bsdauth";
999 928
1000 return (authok != 0); 929 return (authok != 0);
1001} 930}
@@ -1205,10 +1134,6 @@ mm_answer_keyallowed(int sock, Buffer *m)
1205 1134
1206 key = key_from_blob(blob, bloblen); 1135 key = key_from_blob(blob, bloblen);
1207 1136
1208 if ((compat20 && type == MM_RSAHOSTKEY) ||
1209 (!compat20 && type != MM_RSAHOSTKEY))
1210 fatal("%s: key type and protocol mismatch", __func__);
1211
1212 debug3("%s: key_from_blob: %p", __func__, key); 1137 debug3("%s: key_from_blob: %p", __func__, key);
1213 1138
1214 if (key != NULL && authctxt->valid) { 1139 if (key != NULL && authctxt->valid) {
@@ -1242,17 +1167,6 @@ mm_answer_keyallowed(int sock, Buffer *m)
1242 cuser, chost); 1167 cuser, chost);
1243 auth_method = "hostbased"; 1168 auth_method = "hostbased";
1244 break; 1169 break;
1245#ifdef WITH_SSH1
1246 case MM_RSAHOSTKEY:
1247 key->type = KEY_RSA1; /* XXX */
1248 allowed = options.rhosts_rsa_authentication &&
1249 auth_rhosts_rsa_key_allowed(authctxt->pw,
1250 cuser, chost, key);
1251 if (options.rhosts_rsa_authentication && allowed != 1)
1252 auth_clear_options();
1253 auth_method = "rsa";
1254 break;
1255#endif
1256 default: 1170 default:
1257 fatal("%s: unknown key type %d", __func__, type); 1171 fatal("%s: unknown key type %d", __func__, type);
1258 break; 1172 break;
@@ -1289,9 +1203,6 @@ mm_answer_keyallowed(int sock, Buffer *m)
1289 1203
1290 mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m); 1204 mm_request_send(sock, MONITOR_ANS_KEYALLOWED, m);
1291 1205
1292 if (type == MM_RSAHOSTKEY)
1293 monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
1294
1295 return (0); 1206 return (0);
1296} 1207}
1297 1208
@@ -1600,186 +1511,6 @@ mm_answer_pty_cleanup(int sock, Buffer *m)
1600 return (0); 1511 return (0);
1601} 1512}
1602 1513
1603#ifdef WITH_SSH1
1604int
1605mm_answer_sesskey(int sock, Buffer *m)
1606{
1607 BIGNUM *p;
1608 int rsafail;
1609
1610 /* Turn off permissions */
1611 monitor_permit(mon_dispatch, MONITOR_REQ_SESSKEY, 0);
1612
1613 if ((p = BN_new()) == NULL)
1614 fatal("%s: BN_new", __func__);
1615
1616 buffer_get_bignum2(m, p);
1617
1618 rsafail = ssh1_session_key(p);
1619
1620 buffer_clear(m);
1621 buffer_put_int(m, rsafail);
1622 buffer_put_bignum2(m, p);
1623
1624 BN_clear_free(p);
1625
1626 mm_request_send(sock, MONITOR_ANS_SESSKEY, m);
1627
1628 /* Turn on permissions for sessid passing */
1629 monitor_permit(mon_dispatch, MONITOR_REQ_SESSID, 1);
1630
1631 return (0);
1632}
1633
1634int
1635mm_answer_sessid(int sock, Buffer *m)
1636{
1637 int i;
1638
1639 debug3("%s entering", __func__);
1640
1641 if (buffer_len(m) != 16)
1642 fatal("%s: bad ssh1 session id", __func__);
1643 for (i = 0; i < 16; i++)
1644 session_id[i] = buffer_get_char(m);
1645
1646 /* Turn on permissions for getpwnam */
1647 monitor_permit(mon_dispatch, MONITOR_REQ_PWNAM, 1);
1648
1649 return (0);
1650}
1651
1652int
1653mm_answer_rsa_keyallowed(int sock, Buffer *m)
1654{
1655 BIGNUM *client_n;
1656 Key *key = NULL;
1657 u_char *blob = NULL;
1658 u_int blen = 0;
1659 int allowed = 0;
1660
1661 debug3("%s entering", __func__);
1662
1663 auth_method = "rsa";
1664 if (options.rsa_authentication && authctxt->valid) {
1665 if ((client_n = BN_new()) == NULL)
1666 fatal("%s: BN_new", __func__);
1667 buffer_get_bignum2(m, client_n);
1668 allowed = auth_rsa_key_allowed(authctxt->pw, client_n, &key);
1669 BN_clear_free(client_n);
1670 }
1671 buffer_clear(m);
1672 buffer_put_int(m, allowed);
1673 buffer_put_int(m, forced_command != NULL);
1674
1675 /* clear temporarily storage (used by generate challenge) */
1676 monitor_reset_key_state();
1677
1678 if (allowed && key != NULL) {
1679 key->type = KEY_RSA; /* cheat for key_to_blob */
1680 if (key_to_blob(key, &blob, &blen) == 0)
1681 fatal("%s: key_to_blob failed", __func__);
1682 buffer_put_string(m, blob, blen);
1683
1684 /* Save temporarily for comparison in verify */
1685 key_blob = blob;
1686 key_bloblen = blen;
1687 key_blobtype = MM_RSAUSERKEY;
1688 }
1689 if (key != NULL)
1690 key_free(key);
1691
1692 mm_request_send(sock, MONITOR_ANS_RSAKEYALLOWED, m);
1693
1694 monitor_permit(mon_dispatch, MONITOR_REQ_RSACHALLENGE, allowed);
1695 monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 0);
1696 return (0);
1697}
1698
1699int
1700mm_answer_rsa_challenge(int sock, Buffer *m)
1701{
1702 Key *key = NULL;
1703 u_char *blob;
1704 u_int blen;
1705
1706 debug3("%s entering", __func__);
1707
1708 if (!authctxt->valid)
1709 fatal("%s: authctxt not valid", __func__);
1710 blob = buffer_get_string(m, &blen);
1711 if (!monitor_allowed_key(blob, blen))
1712 fatal("%s: bad key, not previously allowed", __func__);
1713 if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
1714 fatal("%s: key type mismatch", __func__);
1715 if ((key = key_from_blob(blob, blen)) == NULL)
1716 fatal("%s: received bad key", __func__);
1717 if (key->type != KEY_RSA)
1718 fatal("%s: received bad key type %d", __func__, key->type);
1719 key->type = KEY_RSA1;
1720 if (ssh1_challenge)
1721 BN_clear_free(ssh1_challenge);
1722 ssh1_challenge = auth_rsa_generate_challenge(key);
1723
1724 buffer_clear(m);
1725 buffer_put_bignum2(m, ssh1_challenge);
1726
1727 debug3("%s sending reply", __func__);
1728 mm_request_send(sock, MONITOR_ANS_RSACHALLENGE, m);
1729
1730 monitor_permit(mon_dispatch, MONITOR_REQ_RSARESPONSE, 1);
1731
1732 free(blob);
1733 key_free(key);
1734 return (0);
1735}
1736
1737int
1738mm_answer_rsa_response(int sock, Buffer *m)
1739{
1740 Key *key = NULL;
1741 u_char *blob, *response;
1742 u_int blen, len;
1743 int success;
1744
1745 debug3("%s entering", __func__);
1746
1747 if (!authctxt->valid)
1748 fatal("%s: authctxt not valid", __func__);
1749 if (ssh1_challenge == NULL)
1750 fatal("%s: no ssh1_challenge", __func__);
1751
1752 blob = buffer_get_string(m, &blen);
1753 if (!monitor_allowed_key(blob, blen))
1754 fatal("%s: bad key, not previously allowed", __func__);
1755 if (key_blobtype != MM_RSAUSERKEY && key_blobtype != MM_RSAHOSTKEY)
1756 fatal("%s: key type mismatch: %d", __func__, key_blobtype);
1757 if ((key = key_from_blob(blob, blen)) == NULL)
1758 fatal("%s: received bad key", __func__);
1759 response = buffer_get_string(m, &len);
1760 if (len != 16)
1761 fatal("%s: received bad response to challenge", __func__);
1762 success = auth_rsa_verify_response(key, ssh1_challenge, response);
1763
1764 free(blob);
1765 key_free(key);
1766 free(response);
1767
1768 auth_method = key_blobtype == MM_RSAUSERKEY ? "rsa" : "rhosts-rsa";
1769
1770 /* reset state */
1771 BN_clear_free(ssh1_challenge);
1772 ssh1_challenge = NULL;
1773 monitor_reset_key_state();
1774
1775 buffer_clear(m);
1776 buffer_put_int(m, success);
1777 mm_request_send(sock, MONITOR_ANS_RSARESPONSE, m);
1778
1779 return (success);
1780}
1781#endif
1782
1783int 1514int
1784mm_answer_term(int sock, Buffer *req) 1515mm_answer_term(int sock, Buffer *req)
1785{ 1516{
diff --git a/monitor_wrap.c b/monitor_wrap.c
index 99dc13b61..64ff92885 100644
--- a/monitor_wrap.c
+++ b/monitor_wrap.c
@@ -1,4 +1,4 @@
1/* $OpenBSD: monitor_wrap.c,v 1.88 2016/03/07 19:02:43 djm Exp $ */ 1/* $OpenBSD: monitor_wrap.c,v 1.89 2016/08/13 17:47:41 markus Exp $ */
2/* 2/*
3 * Copyright 2002 Niels Provos <provos@citi.umich.edu> 3 * Copyright 2002 Niels Provos <provos@citi.umich.edu>
4 * Copyright 2002 Markus Friedl <markus@openbsd.org> 4 * Copyright 2002 Markus Friedl <markus@openbsd.org>
@@ -85,7 +85,6 @@
85#include "ssherr.h" 85#include "ssherr.h"
86 86
87/* Imports */ 87/* Imports */
88extern int compat20;
89extern z_stream incoming_stream; 88extern z_stream incoming_stream;
90extern z_stream outgoing_stream; 89extern z_stream outgoing_stream;
91extern struct monitor *pmonitor; 90extern struct monitor *pmonitor;
@@ -389,18 +388,6 @@ mm_hostbased_key_allowed(struct passwd *pw, const char *user, const char *host,
389} 388}
390 389
391int 390int
392mm_auth_rhosts_rsa_key_allowed(struct passwd *pw, const char *user,
393 const char *host, Key *key)
394{
395 int ret;
396
397 key->type = KEY_RSA; /* XXX hack for key_to_blob */
398 ret = mm_key_allowed(MM_RSAHOSTKEY, user, host, key, 0);
399 key->type = KEY_RSA1;
400 return (ret);
401}
402
403int
404mm_key_allowed(enum mm_keytype type, const char *user, const char *host, 391mm_key_allowed(enum mm_keytype type, const char *user, const char *host,
405 Key *key, int pubkey_auth_attempt) 392 Key *key, int pubkey_auth_attempt)
406{ 393{
@@ -710,28 +697,6 @@ mm_terminate(void)
710 buffer_free(&m); 697 buffer_free(&m);
711} 698}
712 699
713#ifdef WITH_SSH1
714int
715mm_ssh1_session_key(BIGNUM *num)
716{
717 int rsafail;
718 Buffer m;
719
720 buffer_init(&m);
721 buffer_put_bignum2(&m, num);
722 mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SESSKEY, &m);
723
724 mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_SESSKEY, &m);
725
726 rsafail = buffer_get_int(&m);
727 buffer_get_bignum2(&m, num);
728
729 buffer_free(&m);
730
731 return (rsafail);
732}
733#endif
734
735static void 700static void
736mm_chall_setup(char **name, char **infotxt, u_int *numprompts, 701mm_chall_setup(char **name, char **infotxt, u_int *numprompts,
737 char ***prompts, u_int **echo_on) 702 char ***prompts, u_int **echo_on)
@@ -862,120 +827,6 @@ mm_skey_respond(void *ctx, u_int numresponses, char **responses)
862} 827}
863#endif /* SKEY */ 828#endif /* SKEY */
864 829
865void
866mm_ssh1_session_id(u_char session_id[16])
867{
868 Buffer m;
869 int i;
870
871 debug3("%s entering", __func__);
872
873 buffer_init(&m);
874 for (i = 0; i < 16; i++)
875 buffer_put_char(&m, session_id[i]);
876
877 mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_SESSID, &m);
878 buffer_free(&m);
879}
880
881#ifdef WITH_SSH1
882int
883mm_auth_rsa_key_allowed(struct passwd *pw, BIGNUM *client_n, Key **rkey)
884{
885 Buffer m;
886 Key *key;
887 u_char *blob;
888 u_int blen;
889 int allowed = 0, have_forced = 0;
890
891 debug3("%s entering", __func__);
892
893 buffer_init(&m);
894 buffer_put_bignum2(&m, client_n);
895
896 mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_RSAKEYALLOWED, &m);
897 mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_RSAKEYALLOWED, &m);
898
899 allowed = buffer_get_int(&m);
900
901 /* fake forced command */
902 auth_clear_options();
903 have_forced = buffer_get_int(&m);
904 forced_command = have_forced ? xstrdup("true") : NULL;
905
906 if (allowed && rkey != NULL) {
907 blob = buffer_get_string(&m, &blen);
908 if ((key = key_from_blob(blob, blen)) == NULL)
909 fatal("%s: key_from_blob failed", __func__);
910 *rkey = key;
911 free(blob);
912 }
913 buffer_free(&m);
914
915 return (allowed);
916}
917
918BIGNUM *
919mm_auth_rsa_generate_challenge(Key *key)
920{
921 Buffer m;
922 BIGNUM *challenge;
923 u_char *blob;
924 u_int blen;
925
926 debug3("%s entering", __func__);
927
928 if ((challenge = BN_new()) == NULL)
929 fatal("%s: BN_new failed", __func__);
930
931 key->type = KEY_RSA; /* XXX cheat for key_to_blob */
932 if (key_to_blob(key, &blob, &blen) == 0)
933 fatal("%s: key_to_blob failed", __func__);
934 key->type = KEY_RSA1;
935
936 buffer_init(&m);
937 buffer_put_string(&m, blob, blen);
938 free(blob);
939
940 mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_RSACHALLENGE, &m);
941 mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_RSACHALLENGE, &m);
942
943 buffer_get_bignum2(&m, challenge);
944 buffer_free(&m);
945
946 return (challenge);
947}
948
949int
950mm_auth_rsa_verify_response(Key *key, BIGNUM *p, u_char response[16])
951{
952 Buffer m;
953 u_char *blob;
954 u_int blen;
955 int success = 0;
956
957 debug3("%s entering", __func__);
958
959 key->type = KEY_RSA; /* XXX cheat for key_to_blob */
960 if (key_to_blob(key, &blob, &blen) == 0)
961 fatal("%s: key_to_blob failed", __func__);
962 key->type = KEY_RSA1;
963
964 buffer_init(&m);
965 buffer_put_string(&m, blob, blen);
966 buffer_put_string(&m, response, 16);
967 free(blob);
968
969 mm_request_send(pmonitor->m_recvfd, MONITOR_REQ_RSARESPONSE, &m);
970 mm_request_receive_expect(pmonitor->m_recvfd, MONITOR_ANS_RSARESPONSE, &m);
971
972 success = buffer_get_int(&m);
973 buffer_free(&m);
974
975 return (success);
976}
977#endif
978
979#ifdef SSH_AUDIT_EVENTS 830#ifdef SSH_AUDIT_EVENTS
980void 831void
981mm_audit_event(ssh_audit_event_t event) 832mm_audit_event(ssh_audit_event_t event)
diff --git a/monitor_wrap.h b/monitor_wrap.h
index 9fd02b30c..1bc76afff 100644
--- a/monitor_wrap.h
+++ b/monitor_wrap.h
@@ -1,4 +1,4 @@
1/* $OpenBSD: monitor_wrap.h,v 1.30 2016/03/07 19:02:43 djm Exp $ */ 1/* $OpenBSD: monitor_wrap.h,v 1.31 2016/08/13 17:47:41 markus Exp $ */
2 2
3/* 3/*
4 * Copyright 2002 Niels Provos <provos@citi.umich.edu> 4 * Copyright 2002 Niels Provos <provos@citi.umich.edu>
@@ -31,7 +31,7 @@
31extern int use_privsep; 31extern int use_privsep;
32#define PRIVSEP(x) (use_privsep ? mm_##x : x) 32#define PRIVSEP(x) (use_privsep ? mm_##x : x)
33 33
34enum mm_keytype {MM_NOKEY, MM_HOSTKEY, MM_USERKEY, MM_RSAHOSTKEY, MM_RSAUSERKEY}; 34enum mm_keytype { MM_NOKEY, MM_HOSTKEY, MM_USERKEY };
35 35
36struct monitor; 36struct monitor;
37struct mm_master; 37struct mm_master;
@@ -49,12 +49,7 @@ int mm_key_allowed(enum mm_keytype, const char *, const char *, Key *, int);
49int mm_user_key_allowed(struct passwd *, Key *, int); 49int mm_user_key_allowed(struct passwd *, Key *, int);
50int mm_hostbased_key_allowed(struct passwd *, const char *, 50int mm_hostbased_key_allowed(struct passwd *, const char *,
51 const char *, Key *); 51 const char *, Key *);
52int mm_auth_rhosts_rsa_key_allowed(struct passwd *, const char *,
53 const char *, Key *);
54int mm_key_verify(Key *, u_char *, u_int, u_char *, u_int); 52int mm_key_verify(Key *, u_char *, u_int, u_char *, u_int);
55int mm_auth_rsa_key_allowed(struct passwd *, BIGNUM *, Key **);
56int mm_auth_rsa_verify_response(Key *, BIGNUM *, u_char *);
57BIGNUM *mm_auth_rsa_generate_challenge(Key *);
58 53
59#ifdef GSSAPI 54#ifdef GSSAPI
60OM_uint32 mm_ssh_gssapi_server_ctx(Gssctxt **, gss_OID); 55OM_uint32 mm_ssh_gssapi_server_ctx(Gssctxt **, gss_OID);
@@ -84,10 +79,6 @@ void mm_terminate(void);
84int mm_pty_allocate(int *, int *, char *, size_t); 79int mm_pty_allocate(int *, int *, char *, size_t);
85void mm_session_pty_cleanup2(struct Session *); 80void mm_session_pty_cleanup2(struct Session *);
86 81
87/* SSHv1 interfaces */
88void mm_ssh1_session_id(u_char *);
89int mm_ssh1_session_key(BIGNUM *);
90
91/* Key export functions */ 82/* Key export functions */
92struct newkeys *mm_newkeys_from_blob(u_char *, int); 83struct newkeys *mm_newkeys_from_blob(u_char *, int);
93int mm_newkeys_to_blob(int, u_char **, u_int *); 84int mm_newkeys_to_blob(int, u_char **, u_int *);
diff --git a/serverloop.c b/serverloop.c
index 3563e5d42..1e211701e 100644
--- a/serverloop.c
+++ b/serverloop.c
@@ -1,4 +1,4 @@
1/* $OpenBSD: serverloop.c,v 1.184 2016/03/07 19:02:43 djm Exp $ */ 1/* $OpenBSD: serverloop.c,v 1.185 2016/08/13 17:47:41 markus Exp $ */
2/* 2/*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi> 3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -67,7 +67,6 @@
67#include "sshpty.h" 67#include "sshpty.h"
68#include "channels.h" 68#include "channels.h"
69#include "compat.h" 69#include "compat.h"
70#include "ssh1.h"
71#include "ssh2.h" 70#include "ssh2.h"
72#include "key.h" 71#include "key.h"
73#include "cipher.h" 72#include "cipher.h"
@@ -86,25 +85,6 @@ extern ServerOptions options;
86extern Authctxt *the_authctxt; 85extern Authctxt *the_authctxt;
87extern int use_privsep; 86extern int use_privsep;
88 87
89static Buffer stdin_buffer; /* Buffer for stdin data. */
90static Buffer stdout_buffer; /* Buffer for stdout data. */
91static Buffer stderr_buffer; /* Buffer for stderr data. */
92static int fdin; /* Descriptor for stdin (for writing) */
93static int fdout; /* Descriptor for stdout (for reading);
94 May be same number as fdin. */
95static int fderr; /* Descriptor for stderr. May be -1. */
96static long stdin_bytes = 0; /* Number of bytes written to stdin. */
97static long stdout_bytes = 0; /* Number of stdout bytes sent to client. */
98static long stderr_bytes = 0; /* Number of stderr bytes sent to client. */
99static long fdout_bytes = 0; /* Number of stdout bytes read from program. */
100static int stdin_eof = 0; /* EOF message received from client. */
101static int fdout_eof = 0; /* EOF encountered reading from fdout. */
102static int fderr_eof = 0; /* EOF encountered readung from fderr. */
103static int fdin_is_tty = 0; /* fdin points to a tty. */
104static int connection_in; /* Connection to client (input). */
105static int connection_out; /* Connection to client (output). */
106static int connection_closed = 0; /* Connection to client closed. */
107static u_int buffer_high; /* "Soft" max buffer size. */
108static int no_more_sessions = 0; /* Disallow further sessions. */ 88static int no_more_sessions = 0; /* Disallow further sessions. */
109 89
110/* 90/*
@@ -185,64 +165,6 @@ sigterm_handler(int sig)
185 received_sigterm = sig; 165 received_sigterm = sig;
186} 166}
187 167
188/*
189 * Make packets from buffered stderr data, and buffer it for sending
190 * to the client.
191 */
192static void
193make_packets_from_stderr_data(void)
194{
195 u_int len;
196
197 /* Send buffered stderr data to the client. */
198 while (buffer_len(&stderr_buffer) > 0 &&
199 packet_not_very_much_data_to_write()) {
200 len = buffer_len(&stderr_buffer);
201 if (packet_is_interactive()) {
202 if (len > 512)
203 len = 512;
204 } else {
205 /* Keep the packets at reasonable size. */
206 if (len > packet_get_maxsize())
207 len = packet_get_maxsize();
208 }
209 packet_start(SSH_SMSG_STDERR_DATA);
210 packet_put_string(buffer_ptr(&stderr_buffer), len);
211 packet_send();
212 buffer_consume(&stderr_buffer, len);
213 stderr_bytes += len;
214 }
215}
216
217/*
218 * Make packets from buffered stdout data, and buffer it for sending to the
219 * client.
220 */
221static void
222make_packets_from_stdout_data(void)
223{
224 u_int len;
225
226 /* Send buffered stdout data to the client. */
227 while (buffer_len(&stdout_buffer) > 0 &&
228 packet_not_very_much_data_to_write()) {
229 len = buffer_len(&stdout_buffer);
230 if (packet_is_interactive()) {
231 if (len > 512)
232 len = 512;
233 } else {
234 /* Keep the packets at reasonable size. */
235 if (len > packet_get_maxsize())
236 len = packet_get_maxsize();
237 }
238 packet_start(SSH_SMSG_STDOUT_DATA);
239 packet_put_string(buffer_ptr(&stdout_buffer), len);
240 packet_send();
241 buffer_consume(&stdout_buffer, len);
242 stdout_bytes += len;
243 }
244}
245
246static void 168static void
247client_alive_check(void) 169client_alive_check(void)
248{ 170{
@@ -275,14 +197,14 @@ client_alive_check(void)
275 * for the duration of the wait (0 = infinite). 197 * for the duration of the wait (0 = infinite).
276 */ 198 */
277static void 199static void
278wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp, 200wait_until_can_do_something(int connection_in, int connection_out,
201 fd_set **readsetp, fd_set **writesetp, int *maxfdp,
279 u_int *nallocp, u_int64_t max_time_ms) 202 u_int *nallocp, u_int64_t max_time_ms)
280{ 203{
281 struct timeval tv, *tvp; 204 struct timeval tv, *tvp;
282 int ret; 205 int ret;
283 time_t minwait_secs = 0; 206 time_t minwait_secs = 0;
284 int client_alive_scheduled = 0; 207 int client_alive_scheduled = 0;
285 int program_alive_scheduled = 0;
286 208
287 /* Allocate and update select() masks for channel descriptors. */ 209 /* Allocate and update select() masks for channel descriptors. */
288 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp, 210 channel_prepare_select(readsetp, writesetp, maxfdp, nallocp,
@@ -300,7 +222,7 @@ wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
300 * this could be randomized somewhat to make traffic 222 * this could be randomized somewhat to make traffic
301 * analysis more difficult, but we're not doing it yet. 223 * analysis more difficult, but we're not doing it yet.
302 */ 224 */
303 if (compat20 && options.client_alive_interval) { 225 if (options.client_alive_interval) {
304 uint64_t keepalive_ms = 226 uint64_t keepalive_ms =
305 (uint64_t)options.client_alive_interval * 1000; 227 (uint64_t)options.client_alive_interval * 1000;
306 228
@@ -309,38 +231,11 @@ wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
309 max_time_ms = keepalive_ms; 231 max_time_ms = keepalive_ms;
310 } 232 }
311 233
312 if (compat20) {
313#if 0 234#if 0
314 /* wrong: bad condition XXX */ 235 /* wrong: bad condition XXX */
315 if (channel_not_very_much_buffered_data()) 236 if (channel_not_very_much_buffered_data())
316#endif 237#endif
317 FD_SET(connection_in, *readsetp); 238 FD_SET(connection_in, *readsetp);
318 } else {
319 /*
320 * Read packets from the client unless we have too much
321 * buffered stdin or channel data.
322 */
323 if (buffer_len(&stdin_buffer) < buffer_high &&
324 channel_not_very_much_buffered_data())
325 FD_SET(connection_in, *readsetp);
326 /*
327 * If there is not too much data already buffered going to
328 * the client, try to get some more data from the program.
329 */
330 if (packet_not_very_much_data_to_write()) {
331 program_alive_scheduled = child_terminated;
332 if (!fdout_eof)
333 FD_SET(fdout, *readsetp);
334 if (!fderr_eof)
335 FD_SET(fderr, *readsetp);
336 }
337 /*
338 * If we have buffered data, try to write some of that data
339 * to the program.
340 */
341 if (fdin != -1 && buffer_len(&stdin_buffer) > 0)
342 FD_SET(fdin, *writesetp);
343 }
344 notify_prepare(*readsetp); 239 notify_prepare(*readsetp);
345 240
346 /* 241 /*
@@ -374,16 +269,8 @@ wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
374 memset(*writesetp, 0, *nallocp); 269 memset(*writesetp, 0, *nallocp);
375 if (errno != EINTR) 270 if (errno != EINTR)
376 error("select: %.100s", strerror(errno)); 271 error("select: %.100s", strerror(errno));
377 } else { 272 } else if (ret == 0 && client_alive_scheduled)
378 if (ret == 0 && client_alive_scheduled) 273 client_alive_check();
379 client_alive_check();
380 if (!compat20 && program_alive_scheduled && fdin_is_tty) {
381 if (!fdout_eof)
382 FD_SET(fdout, *readsetp);
383 if (!fderr_eof)
384 FD_SET(fderr, *readsetp);
385 }
386 }
387 274
388 notify_done(*readsetp); 275 notify_done(*readsetp);
389} 276}
@@ -392,8 +279,8 @@ wait_until_can_do_something(fd_set **readsetp, fd_set **writesetp, int *maxfdp,
392 * Processes input from the client and the program. Input data is stored 279 * Processes input from the client and the program. Input data is stored
393 * in buffers and processed later. 280 * in buffers and processed later.
394 */ 281 */
395static void 282static int
396process_input(fd_set *readset) 283process_input(fd_set *readset, int connection_in)
397{ 284{
398 struct ssh *ssh = active_state; /* XXX */ 285 struct ssh *ssh = active_state; /* XXX */
399 int len; 286 int len;
@@ -405,10 +292,7 @@ process_input(fd_set *readset)
405 if (len == 0) { 292 if (len == 0) {
406 verbose("Connection closed by %.100s port %d", 293 verbose("Connection closed by %.100s port %d",
407 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh)); 294 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
408 connection_closed = 1; 295 return -1;
409 if (compat20)
410 return;
411 cleanup_exit(255);
412 } else if (len < 0) { 296 } else if (len < 0) {
413 if (errno != EINTR && errno != EAGAIN && 297 if (errno != EINTR && errno != EAGAIN &&
414 errno != EWOULDBLOCK) { 298 errno != EWOULDBLOCK) {
@@ -423,381 +307,26 @@ process_input(fd_set *readset)
423 packet_process_incoming(buf, len); 307 packet_process_incoming(buf, len);
424 } 308 }
425 } 309 }
426 if (compat20) 310 return 0;
427 return;
428
429 /* Read and buffer any available stdout data from the program. */
430 if (!fdout_eof && FD_ISSET(fdout, readset)) {
431 errno = 0;
432 len = read(fdout, buf, sizeof(buf));
433 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
434 errno == EWOULDBLOCK) && !child_terminated))) {
435 /* do nothing */
436#ifndef PTY_ZEROREAD
437 } else if (len <= 0) {
438#else
439 } else if ((!isatty(fdout) && len <= 0) ||
440 (isatty(fdout) && (len < 0 || (len == 0 && errno != 0)))) {
441#endif
442 fdout_eof = 1;
443 } else {
444 buffer_append(&stdout_buffer, buf, len);
445 fdout_bytes += len;
446 }
447 }
448 /* Read and buffer any available stderr data from the program. */
449 if (!fderr_eof && FD_ISSET(fderr, readset)) {
450 errno = 0;
451 len = read(fderr, buf, sizeof(buf));
452 if (len < 0 && (errno == EINTR || ((errno == EAGAIN ||
453 errno == EWOULDBLOCK) && !child_terminated))) {
454 /* do nothing */
455#ifndef PTY_ZEROREAD
456 } else if (len <= 0) {
457#else
458 } else if ((!isatty(fderr) && len <= 0) ||
459 (isatty(fderr) && (len < 0 || (len == 0 && errno != 0)))) {
460#endif
461 fderr_eof = 1;
462 } else {
463 buffer_append(&stderr_buffer, buf, len);
464 }
465 }
466} 311}
467 312
468/* 313/*
469 * Sends data from internal buffers to client program stdin. 314 * Sends data from internal buffers to client program stdin.
470 */ 315 */
471static void 316static void
472process_output(fd_set *writeset) 317process_output(fd_set *writeset, int connection_out)
473{ 318{
474 struct termios tio;
475 u_char *data;
476 u_int dlen;
477 int len;
478
479 /* Write buffered data to program stdin. */
480 if (!compat20 && fdin != -1 && FD_ISSET(fdin, writeset)) {
481 data = buffer_ptr(&stdin_buffer);
482 dlen = buffer_len(&stdin_buffer);
483 len = write(fdin, data, dlen);
484 if (len < 0 &&
485 (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) {
486 /* do nothing */
487 } else if (len <= 0) {
488 if (fdin != fdout)
489 close(fdin);
490 else
491 shutdown(fdin, SHUT_WR); /* We will no longer send. */
492 fdin = -1;
493 } else {
494 /* Successful write. */
495 if (fdin_is_tty && dlen >= 1 && data[0] != '\r' &&
496 tcgetattr(fdin, &tio) == 0 &&
497 !(tio.c_lflag & ECHO) && (tio.c_lflag & ICANON)) {
498 /*
499 * Simulate echo to reduce the impact of
500 * traffic analysis
501 */
502 packet_send_ignore(len);
503 packet_send();
504 }
505 /* Consume the data from the buffer. */
506 buffer_consume(&stdin_buffer, len);
507 /* Update the count of bytes written to the program. */
508 stdin_bytes += len;
509 }
510 }
511 /* Send any buffered packet data to the client. */ 319 /* Send any buffered packet data to the client. */
512 if (FD_ISSET(connection_out, writeset)) 320 if (FD_ISSET(connection_out, writeset))
513 packet_write_poll(); 321 packet_write_poll();
514} 322}
515 323
516/*
517 * Wait until all buffered output has been sent to the client.
518 * This is used when the program terminates.
519 */
520static void
521drain_output(void)
522{
523 /* Send any buffered stdout data to the client. */
524 if (buffer_len(&stdout_buffer) > 0) {
525 packet_start(SSH_SMSG_STDOUT_DATA);
526 packet_put_string(buffer_ptr(&stdout_buffer),
527 buffer_len(&stdout_buffer));
528 packet_send();
529 /* Update the count of sent bytes. */
530 stdout_bytes += buffer_len(&stdout_buffer);
531 }
532 /* Send any buffered stderr data to the client. */
533 if (buffer_len(&stderr_buffer) > 0) {
534 packet_start(SSH_SMSG_STDERR_DATA);
535 packet_put_string(buffer_ptr(&stderr_buffer),
536 buffer_len(&stderr_buffer));
537 packet_send();
538 /* Update the count of sent bytes. */
539 stderr_bytes += buffer_len(&stderr_buffer);
540 }
541 /* Wait until all buffered data has been written to the client. */
542 packet_write_wait();
543}
544
545static void 324static void
546process_buffered_input_packets(void) 325process_buffered_input_packets(void)
547{ 326{
548 dispatch_run(DISPATCH_NONBLOCK, NULL, active_state); 327 dispatch_run(DISPATCH_NONBLOCK, NULL, active_state);
549} 328}
550 329
551/*
552 * Performs the interactive session. This handles data transmission between
553 * the client and the program. Note that the notion of stdin, stdout, and
554 * stderr in this function is sort of reversed: this function writes to
555 * stdin (of the child program), and reads from stdout and stderr (of the
556 * child program).
557 */
558void
559server_loop(pid_t pid, int fdin_arg, int fdout_arg, int fderr_arg)
560{
561 fd_set *readset = NULL, *writeset = NULL;
562 int max_fd = 0;
563 u_int nalloc = 0;
564 int wait_status; /* Status returned by wait(). */
565 pid_t wait_pid; /* pid returned by wait(). */
566 int waiting_termination = 0; /* Have displayed waiting close message. */
567 u_int64_t max_time_milliseconds;
568 u_int previous_stdout_buffer_bytes;
569 u_int stdout_buffer_bytes;
570 int type;
571
572 debug("Entering interactive session.");
573
574 /* Initialize the SIGCHLD kludge. */
575 child_terminated = 0;
576 mysignal(SIGCHLD, sigchld_handler);
577
578 if (!use_privsep) {
579 signal(SIGTERM, sigterm_handler);
580 signal(SIGINT, sigterm_handler);
581 signal(SIGQUIT, sigterm_handler);
582 }
583
584 /* Initialize our global variables. */
585 fdin = fdin_arg;
586 fdout = fdout_arg;
587 fderr = fderr_arg;
588
589 /* nonblocking IO */
590 set_nonblock(fdin);
591 set_nonblock(fdout);
592 /* we don't have stderr for interactive terminal sessions, see below */
593 if (fderr != -1)
594 set_nonblock(fderr);
595
596 if (!(datafellows & SSH_BUG_IGNOREMSG) && isatty(fdin))
597 fdin_is_tty = 1;
598
599 connection_in = packet_get_connection_in();
600 connection_out = packet_get_connection_out();
601
602 notify_setup();
603
604 previous_stdout_buffer_bytes = 0;
605
606 /* Set approximate I/O buffer size. */
607 if (packet_is_interactive())
608 buffer_high = 4096;
609 else
610 buffer_high = 64 * 1024;
611
612#if 0
613 /* Initialize max_fd to the maximum of the known file descriptors. */
614 max_fd = MAX(connection_in, connection_out);
615 max_fd = MAX(max_fd, fdin);
616 max_fd = MAX(max_fd, fdout);
617 if (fderr != -1)
618 max_fd = MAX(max_fd, fderr);
619#endif
620
621 /* Initialize Initialize buffers. */
622 buffer_init(&stdin_buffer);
623 buffer_init(&stdout_buffer);
624 buffer_init(&stderr_buffer);
625
626 /*
627 * If we have no separate fderr (which is the case when we have a pty
628 * - there we cannot make difference between data sent to stdout and
629 * stderr), indicate that we have seen an EOF from stderr. This way
630 * we don't need to check the descriptor everywhere.
631 */
632 if (fderr == -1)
633 fderr_eof = 1;
634
635 server_init_dispatch();
636
637 /* Main loop of the server for the interactive session mode. */
638 for (;;) {
639
640 /* Process buffered packets from the client. */
641 process_buffered_input_packets();
642
643 /*
644 * If we have received eof, and there is no more pending
645 * input data, cause a real eof by closing fdin.
646 */
647 if (stdin_eof && fdin != -1 && buffer_len(&stdin_buffer) == 0) {
648 if (fdin != fdout)
649 close(fdin);
650 else
651 shutdown(fdin, SHUT_WR); /* We will no longer send. */
652 fdin = -1;
653 }
654 /* Make packets from buffered stderr data to send to the client. */
655 make_packets_from_stderr_data();
656
657 /*
658 * Make packets from buffered stdout data to send to the
659 * client. If there is very little to send, this arranges to
660 * not send them now, but to wait a short while to see if we
661 * are getting more data. This is necessary, as some systems
662 * wake up readers from a pty after each separate character.
663 */
664 max_time_milliseconds = 0;
665 stdout_buffer_bytes = buffer_len(&stdout_buffer);
666 if (stdout_buffer_bytes != 0 && stdout_buffer_bytes < 256 &&
667 stdout_buffer_bytes != previous_stdout_buffer_bytes) {
668 /* try again after a while */
669 max_time_milliseconds = 10;
670 } else {
671 /* Send it now. */
672 make_packets_from_stdout_data();
673 }
674 previous_stdout_buffer_bytes = buffer_len(&stdout_buffer);
675
676 /* Send channel data to the client. */
677 if (packet_not_very_much_data_to_write())
678 channel_output_poll();
679
680 /*
681 * Bail out of the loop if the program has closed its output
682 * descriptors, and we have no more data to send to the
683 * client, and there is no pending buffered data.
684 */
685 if (fdout_eof && fderr_eof && !packet_have_data_to_write() &&
686 buffer_len(&stdout_buffer) == 0 && buffer_len(&stderr_buffer) == 0) {
687 if (!channel_still_open())
688 break;
689 if (!waiting_termination) {
690 const char *s = "Waiting for forwarded connections to terminate...\r\n";
691 char *cp;
692 waiting_termination = 1;
693 buffer_append(&stderr_buffer, s, strlen(s));
694
695 /* Display list of open channels. */
696 cp = channel_open_message();
697 buffer_append(&stderr_buffer, cp, strlen(cp));
698 free(cp);
699 }
700 }
701 max_fd = MAX(connection_in, connection_out);
702 max_fd = MAX(max_fd, fdin);
703 max_fd = MAX(max_fd, fdout);
704 max_fd = MAX(max_fd, fderr);
705 max_fd = MAX(max_fd, notify_pipe[0]);
706
707 /* Sleep in select() until we can do something. */
708 wait_until_can_do_something(&readset, &writeset, &max_fd,
709 &nalloc, max_time_milliseconds);
710
711 if (received_sigterm) {
712 logit("Exiting on signal %d", (int)received_sigterm);
713 /* Clean up sessions, utmp, etc. */
714 cleanup_exit(255);
715 }
716
717 /* Process any channel events. */
718 channel_after_select(readset, writeset);
719
720 /* Process input from the client and from program stdout/stderr. */
721 process_input(readset);
722
723 /* Process output to the client and to program stdin. */
724 process_output(writeset);
725 }
726 free(readset);
727 free(writeset);
728
729 /* Cleanup and termination code. */
730
731 /* Wait until all output has been sent to the client. */
732 drain_output();
733
734 debug("End of interactive session; stdin %ld, stdout (read %ld, sent %ld), stderr %ld bytes.",
735 stdin_bytes, fdout_bytes, stdout_bytes, stderr_bytes);
736
737 /* Free and clear the buffers. */
738 buffer_free(&stdin_buffer);
739 buffer_free(&stdout_buffer);
740 buffer_free(&stderr_buffer);
741
742 /* Close the file descriptors. */
743 if (fdout != -1)
744 close(fdout);
745 fdout = -1;
746 fdout_eof = 1;
747 if (fderr != -1)
748 close(fderr);
749 fderr = -1;
750 fderr_eof = 1;
751 if (fdin != -1)
752 close(fdin);
753 fdin = -1;
754
755 channel_free_all();
756
757 /* We no longer want our SIGCHLD handler to be called. */
758 mysignal(SIGCHLD, SIG_DFL);
759
760 while ((wait_pid = waitpid(-1, &wait_status, 0)) < 0)
761 if (errno != EINTR)
762 packet_disconnect("wait: %.100s", strerror(errno));
763 if (wait_pid != pid)
764 error("Strange, wait returned pid %ld, expected %ld",
765 (long)wait_pid, (long)pid);
766
767 /* Check if it exited normally. */
768 if (WIFEXITED(wait_status)) {
769 /* Yes, normal exit. Get exit status and send it to the client. */
770 debug("Command exited with status %d.", WEXITSTATUS(wait_status));
771 packet_start(SSH_SMSG_EXITSTATUS);
772 packet_put_int(WEXITSTATUS(wait_status));
773 packet_send();
774 packet_write_wait();
775
776 /*
777 * Wait for exit confirmation. Note that there might be
778 * other packets coming before it; however, the program has
779 * already died so we just ignore them. The client is
780 * supposed to respond with the confirmation when it receives
781 * the exit status.
782 */
783 do {
784 type = packet_read();
785 }
786 while (type != SSH_CMSG_EXIT_CONFIRMATION);
787
788 debug("Received exit confirmation.");
789 return;
790 }
791 /* Check if the program terminated due to a signal. */
792 if (WIFSIGNALED(wait_status))
793 packet_disconnect("Command terminated on signal %d.",
794 WTERMSIG(wait_status));
795
796 /* Some weird exit cause. Just exit. */
797 packet_disconnect("wait returned status %04x.", wait_status);
798 /* NOTREACHED */
799}
800
801static void 330static void
802collect_children(void) 331collect_children(void)
803{ 332{
@@ -825,7 +354,7 @@ server_loop2(Authctxt *authctxt)
825{ 354{
826 fd_set *readset = NULL, *writeset = NULL; 355 fd_set *readset = NULL, *writeset = NULL;
827 int max_fd; 356 int max_fd;
828 u_int nalloc = 0; 357 u_int nalloc = 0, connection_in, connection_out;
829 u_int64_t rekey_timeout_ms = 0; 358 u_int64_t rekey_timeout_ms = 0;
830 359
831 debug("Entering interactive session for SSH2."); 360 debug("Entering interactive session for SSH2.");
@@ -854,14 +383,14 @@ server_loop2(Authctxt *authctxt)
854 if (!ssh_packet_is_rekeying(active_state) && 383 if (!ssh_packet_is_rekeying(active_state) &&
855 packet_not_very_much_data_to_write()) 384 packet_not_very_much_data_to_write())
856 channel_output_poll(); 385 channel_output_poll();
857 if (options.rekey_interval > 0 && compat20 && 386 if (options.rekey_interval > 0 &&
858 !ssh_packet_is_rekeying(active_state)) 387 !ssh_packet_is_rekeying(active_state))
859 rekey_timeout_ms = packet_get_rekey_timeout() * 1000; 388 rekey_timeout_ms = packet_get_rekey_timeout() * 1000;
860 else 389 else
861 rekey_timeout_ms = 0; 390 rekey_timeout_ms = 0;
862 391
863 wait_until_can_do_something(&readset, &writeset, &max_fd, 392 wait_until_can_do_something(connection_in, connection_out,
864 &nalloc, rekey_timeout_ms); 393 &readset, &writeset, &max_fd, &nalloc, rekey_timeout_ms);
865 394
866 if (received_sigterm) { 395 if (received_sigterm) {
867 logit("Exiting on signal %d", (int)received_sigterm); 396 logit("Exiting on signal %d", (int)received_sigterm);
@@ -872,10 +401,9 @@ server_loop2(Authctxt *authctxt)
872 collect_children(); 401 collect_children();
873 if (!ssh_packet_is_rekeying(active_state)) 402 if (!ssh_packet_is_rekeying(active_state))
874 channel_after_select(readset, writeset); 403 channel_after_select(readset, writeset);
875 process_input(readset); 404 if (process_input(readset, connection_in) < 0)
876 if (connection_closed)
877 break; 405 break;
878 process_output(writeset); 406 process_output(writeset, connection_out);
879 } 407 }
880 collect_children(); 408 collect_children();
881 409
@@ -902,53 +430,6 @@ server_input_keep_alive(int type, u_int32_t seq, void *ctxt)
902 return 0; 430 return 0;
903} 431}
904 432
905static int
906server_input_stdin_data(int type, u_int32_t seq, void *ctxt)
907{
908 char *data;
909 u_int data_len;
910
911 /* Stdin data from the client. Append it to the buffer. */
912 /* Ignore any data if the client has closed stdin. */
913 if (fdin == -1)
914 return 0;
915 data = packet_get_string(&data_len);
916 packet_check_eom();
917 buffer_append(&stdin_buffer, data, data_len);
918 explicit_bzero(data, data_len);
919 free(data);
920 return 0;
921}
922
923static int
924server_input_eof(int type, u_int32_t seq, void *ctxt)
925{
926 /*
927 * Eof from the client. The stdin descriptor to the
928 * program will be closed when all buffered data has
929 * drained.
930 */
931 debug("EOF received for stdin.");
932 packet_check_eom();
933 stdin_eof = 1;
934 return 0;
935}
936
937static int
938server_input_window_size(int type, u_int32_t seq, void *ctxt)
939{
940 u_int row = packet_get_int();
941 u_int col = packet_get_int();
942 u_int xpixel = packet_get_int();
943 u_int ypixel = packet_get_int();
944
945 debug("Window change received.");
946 packet_check_eom();
947 if (fdin != -1)
948 pty_change_window_size(fdin, row, col, xpixel, ypixel);
949 return 0;
950}
951
952static Channel * 433static Channel *
953server_request_direct_tcpip(void) 434server_request_direct_tcpip(void)
954{ 435{
@@ -1353,9 +834,9 @@ server_input_channel_req(int type, u_int32_t seq, void *ctxt)
1353} 834}
1354 835
1355static void 836static void
1356server_init_dispatch_20(void) 837server_init_dispatch(void)
1357{ 838{
1358 debug("server_init_dispatch_20"); 839 debug("server_init_dispatch");
1359 dispatch_init(&dispatch_protocol_error); 840 dispatch_init(&dispatch_protocol_error);
1360 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose); 841 dispatch_set(SSH2_MSG_CHANNEL_CLOSE, &channel_input_oclose);
1361 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data); 842 dispatch_set(SSH2_MSG_CHANNEL_DATA, &channel_input_data);
@@ -1375,36 +856,3 @@ server_init_dispatch_20(void)
1375 /* rekeying */ 856 /* rekeying */
1376 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit); 857 dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
1377} 858}
1378static void
1379server_init_dispatch_13(void)
1380{
1381 debug("server_init_dispatch_13");
1382 dispatch_init(NULL);
1383 dispatch_set(SSH_CMSG_EOF, &server_input_eof);
1384 dispatch_set(SSH_CMSG_STDIN_DATA, &server_input_stdin_data);
1385 dispatch_set(SSH_CMSG_WINDOW_SIZE, &server_input_window_size);
1386 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_close);
1387 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_close_confirmation);
1388 dispatch_set(SSH_MSG_CHANNEL_DATA, &channel_input_data);
1389 dispatch_set(SSH_MSG_CHANNEL_OPEN_CONFIRMATION, &channel_input_open_confirmation);
1390 dispatch_set(SSH_MSG_CHANNEL_OPEN_FAILURE, &channel_input_open_failure);
1391 dispatch_set(SSH_MSG_PORT_OPEN, &channel_input_port_open);
1392}
1393static void
1394server_init_dispatch_15(void)
1395{
1396 server_init_dispatch_13();
1397 debug("server_init_dispatch_15");
1398 dispatch_set(SSH_MSG_CHANNEL_CLOSE, &channel_input_ieof);
1399 dispatch_set(SSH_MSG_CHANNEL_CLOSE_CONFIRMATION, &channel_input_oclose);
1400}
1401static void
1402server_init_dispatch(void)
1403{
1404 if (compat20)
1405 server_init_dispatch_20();
1406 else if (compat13)
1407 server_init_dispatch_13();
1408 else
1409 server_init_dispatch_15();
1410}
diff --git a/serverloop.h b/serverloop.h
index 7311558f9..d5fbda16f 100644
--- a/serverloop.h
+++ b/serverloop.h
@@ -1,4 +1,4 @@
1/* $OpenBSD: serverloop.h,v 1.6 2006/03/25 22:22:43 djm Exp $ */ 1/* $OpenBSD: serverloop.h,v 1.7 2016/08/13 17:47:41 markus Exp $ */
2 2
3/* 3/*
4 * Author: Tatu Ylonen <ylo@cs.hut.fi> 4 * Author: Tatu Ylonen <ylo@cs.hut.fi>
@@ -21,7 +21,6 @@
21#ifndef SERVERLOOP_H 21#ifndef SERVERLOOP_H
22#define SERVERLOOP_H 22#define SERVERLOOP_H
23 23
24void server_loop(pid_t, int, int, int);
25void server_loop2(Authctxt *); 24void server_loop2(Authctxt *);
26 25
27#endif 26#endif
diff --git a/session.c b/session.c
index 2235f26ac..9bad653fc 100644
--- a/session.c
+++ b/session.c
@@ -1,4 +1,4 @@
1/* $OpenBSD: session.c,v 1.282 2016/03/10 11:47:57 djm Exp $ */ 1/* $OpenBSD: session.c,v 1.283 2016/08/13 17:47:41 markus Exp $ */
2/* 2/*
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 * All rights reserved 4 * All rights reserved
@@ -66,7 +66,6 @@
66#include "openbsd-compat/sys-queue.h" 66#include "openbsd-compat/sys-queue.h"
67#include "xmalloc.h" 67#include "xmalloc.h"
68#include "ssh.h" 68#include "ssh.h"
69#include "ssh1.h"
70#include "ssh2.h" 69#include "ssh2.h"
71#include "sshpty.h" 70#include "sshpty.h"
72#include "packet.h" 71#include "packet.h"
@@ -128,7 +127,6 @@ void do_child(Session *, const char *);
128void do_motd(void); 127void do_motd(void);
129int check_quietlogin(Session *, const char *); 128int check_quietlogin(Session *, const char *);
130 129
131static void do_authenticated1(Authctxt *);
132static void do_authenticated2(Authctxt *); 130static void do_authenticated2(Authctxt *);
133 131
134static int session_pty_req(Session *); 132static int session_pty_req(Session *);
@@ -267,11 +265,7 @@ do_authenticated(Authctxt *authctxt)
267 265
268 auth_debug_send(); 266 auth_debug_send();
269 267
270 if (compat20) 268 do_authenticated2(authctxt);
271 do_authenticated2(authctxt);
272 else
273 do_authenticated1(authctxt);
274
275 do_cleanup(authctxt); 269 do_cleanup(authctxt);
276} 270}
277 271
@@ -290,164 +284,6 @@ xauth_valid_string(const char *s)
290 return 1; 284 return 1;
291} 285}
292 286
293/*
294 * Prepares for an interactive session. This is called after the user has
295 * been successfully authenticated. During this message exchange, pseudo
296 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings
297 * are requested, etc.
298 */
299static void
300do_authenticated1(Authctxt *authctxt)
301{
302 Session *s;
303 char *command;
304 int success, type, screen_flag;
305 int enable_compression_after_reply = 0;
306 u_int proto_len, data_len, dlen, compression_level = 0;
307
308 s = session_new();
309 if (s == NULL) {
310 error("no more sessions");
311 return;
312 }
313 s->authctxt = authctxt;
314 s->pw = authctxt->pw;
315
316 /*
317 * We stay in this loop until the client requests to execute a shell
318 * or a command.
319 */
320 for (;;) {
321 success = 0;
322
323 /* Get a packet from the client. */
324 type = packet_read();
325
326 /* Process the packet. */
327 switch (type) {
328 case SSH_CMSG_REQUEST_COMPRESSION:
329 compression_level = packet_get_int();
330 packet_check_eom();
331 if (compression_level < 1 || compression_level > 9) {
332 packet_send_debug("Received invalid compression level %d.",
333 compression_level);
334 break;
335 }
336 if (options.compression == COMP_NONE) {
337 debug2("compression disabled");
338 break;
339 }
340 /* Enable compression after we have responded with SUCCESS. */
341 enable_compression_after_reply = 1;
342 success = 1;
343 break;
344
345 case SSH_CMSG_REQUEST_PTY:
346 success = session_pty_req(s);
347 break;
348
349 case SSH_CMSG_X11_REQUEST_FORWARDING:
350 s->auth_proto = packet_get_string(&proto_len);
351 s->auth_data = packet_get_string(&data_len);
352
353 screen_flag = packet_get_protocol_flags() &
354 SSH_PROTOFLAG_SCREEN_NUMBER;
355 debug2("SSH_PROTOFLAG_SCREEN_NUMBER: %d", screen_flag);
356
357 if (packet_remaining() == 4) {
358 if (!screen_flag)
359 debug2("Buggy client: "
360 "X11 screen flag missing");
361 s->screen = packet_get_int();
362 } else {
363 s->screen = 0;
364 }
365 packet_check_eom();
366 if (xauth_valid_string(s->auth_proto) &&
367 xauth_valid_string(s->auth_data))
368 success = session_setup_x11fwd(s);
369 else {
370 success = 0;
371 error("Invalid X11 forwarding data");
372 }
373 if (!success) {
374 free(s->auth_proto);
375 free(s->auth_data);
376 s->auth_proto = NULL;
377 s->auth_data = NULL;
378 }
379 break;
380
381 case SSH_CMSG_AGENT_REQUEST_FORWARDING:
382 if (!options.allow_agent_forwarding ||
383 no_agent_forwarding_flag || compat13) {
384 debug("Authentication agent forwarding not permitted for this authentication.");
385 break;
386 }
387 debug("Received authentication agent forwarding request.");
388 success = auth_input_request_forwarding(s->pw);
389 break;
390
391 case SSH_CMSG_PORT_FORWARD_REQUEST:
392 if (no_port_forwarding_flag) {
393 debug("Port forwarding not permitted for this authentication.");
394 break;
395 }
396 if (!(options.allow_tcp_forwarding & FORWARD_REMOTE)) {
397 debug("Port forwarding not permitted.");
398 break;
399 }
400 debug("Received TCP/IP port forwarding request.");
401 if (channel_input_port_forward_request(s->pw->pw_uid == 0,
402 &options.fwd_opts) < 0) {
403 debug("Port forwarding failed.");
404 break;
405 }
406 success = 1;
407 break;
408
409 case SSH_CMSG_MAX_PACKET_SIZE:
410 if (packet_set_maxsize(packet_get_int()) > 0)
411 success = 1;
412 break;
413
414 case SSH_CMSG_EXEC_SHELL:
415 case SSH_CMSG_EXEC_CMD:
416 if (type == SSH_CMSG_EXEC_CMD) {
417 command = packet_get_string(&dlen);
418 debug("Exec command '%.500s'", command);
419 if (do_exec(s, command) != 0)
420 packet_disconnect(
421 "command execution failed");
422 free(command);
423 } else {
424 if (do_exec(s, NULL) != 0)
425 packet_disconnect(
426 "shell execution failed");
427 }
428 packet_check_eom();
429 session_close(s);
430 return;
431
432 default:
433 /*
434 * Any unknown messages in this phase are ignored,
435 * and a failure message is returned.
436 */
437 logit("Unknown packet type received after authentication: %d", type);
438 }
439 packet_start(success ? SSH_SMSG_SUCCESS : SSH_SMSG_FAILURE);
440 packet_send();
441 packet_write_wait();
442
443 /* Enable compression now that we have replied if appropriate. */
444 if (enable_compression_after_reply) {
445 enable_compression_after_reply = 0;
446 packet_start_compression(compression_level);
447 }
448 }
449}
450
451#define USE_PIPES 1 287#define USE_PIPES 1
452/* 288/*
453 * This is called to fork and execute a command when we have no tty. This 289 * This is called to fork and execute a command when we have no tty. This
@@ -615,14 +451,8 @@ do_exec_no_pty(Session *s, const char *command)
615 close(pout[1]); 451 close(pout[1]);
616 close(perr[1]); 452 close(perr[1]);
617 453
618 if (compat20) { 454 session_set_fds(s, pin[1], pout[0], perr[0],
619 session_set_fds(s, pin[1], pout[0], perr[0], 455 s->is_subsystem, 0);
620 s->is_subsystem, 0);
621 } else {
622 /* Enter the interactive session. */
623 server_loop(pid, pin[1], pout[0], perr[0]);
624 /* server_loop has closed pin[1], pout[0], and perr[0]. */
625 }
626#else 456#else
627 /* We are the parent. Close the child sides of the socket pairs. */ 457 /* We are the parent. Close the child sides of the socket pairs. */
628 close(inout[0]); 458 close(inout[0]);
@@ -632,13 +462,8 @@ do_exec_no_pty(Session *s, const char *command)
632 * Enter the interactive session. Note: server_loop must be able to 462 * Enter the interactive session. Note: server_loop must be able to
633 * handle the case that fdin and fdout are the same. 463 * handle the case that fdin and fdout are the same.
634 */ 464 */
635 if (compat20) { 465 session_set_fds(s, inout[1], inout[1], err[1],
636 session_set_fds(s, inout[1], inout[1], err[1], 466 s->is_subsystem, 0);
637 s->is_subsystem, 0);
638 } else {
639 server_loop(pid, inout[1], inout[1], err[1]);
640 /* server_loop has closed inout[1] and err[1]. */
641 }
642#endif 467#endif
643 return 0; 468 return 0;
644} 469}
@@ -756,12 +581,7 @@ do_exec_pty(Session *s, const char *command)
756 s->ptymaster = ptymaster; 581 s->ptymaster = ptymaster;
757 packet_set_interactive(1, 582 packet_set_interactive(1,
758 options.ip_qos_interactive, options.ip_qos_bulk); 583 options.ip_qos_interactive, options.ip_qos_bulk);
759 if (compat20) { 584 session_set_fds(s, ptyfd, fdout, -1, 1, 1);
760 session_set_fds(s, ptyfd, fdout, -1, 1, 1);
761 } else {
762 server_loop(pid, ptyfd, fdout, -1);
763 /* server_loop _has_ closed ptyfd and fdout. */
764 }
765 return 0; 585 return 0;
766} 586}
767 587
@@ -2106,14 +1926,8 @@ session_pty_req(Session *s)
2106 } 1926 }
2107 1927
2108 s->term = packet_get_string(&len); 1928 s->term = packet_get_string(&len);
2109 1929 s->col = packet_get_int();
2110 if (compat20) { 1930 s->row = packet_get_int();
2111 s->col = packet_get_int();
2112 s->row = packet_get_int();
2113 } else {
2114 s->row = packet_get_int();
2115 s->col = packet_get_int();
2116 }
2117 s->xpixel = packet_get_int(); 1931 s->xpixel = packet_get_int();
2118 s->ypixel = packet_get_int(); 1932 s->ypixel = packet_get_int();
2119 1933
@@ -2135,9 +1949,7 @@ session_pty_req(Session *s)
2135 } 1949 }
2136 debug("session_pty_req: session %d alloc %s", s->self, s->tty); 1950 debug("session_pty_req: session %d alloc %s", s->self, s->tty);
2137 1951
2138 /* for SSH1 the tty modes length is not given */ 1952 n_bytes = packet_remaining();
2139 if (!compat20)
2140 n_bytes = packet_remaining();
2141 tty_parse_modes(s->ttyfd, &n_bytes); 1953 tty_parse_modes(s->ttyfd, &n_bytes);
2142 1954
2143 if (!use_privsep) 1955 if (!use_privsep)
@@ -2353,8 +2165,6 @@ void
2353session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr, 2165session_set_fds(Session *s, int fdin, int fdout, int fderr, int ignore_fderr,
2354 int is_tty) 2166 int is_tty)
2355{ 2167{
2356 if (!compat20)
2357 fatal("session_set_fds: called for proto != 2.0");
2358 /* 2168 /*
2359 * now that have a child and a pipe to the child, 2169 * now that have a child and a pipe to the child,
2360 * we can activate our channel and register the fd's 2170 * we can activate our channel and register the fd's
@@ -2794,7 +2604,7 @@ do_cleanup(Authctxt *authctxt)
2794#endif 2604#endif
2795 2605
2796#ifdef GSSAPI 2606#ifdef GSSAPI
2797 if (compat20 && options.gss_cleanup_creds) 2607 if (options.gss_cleanup_creds)
2798 ssh_gssapi_cleanup_creds(); 2608 ssh_gssapi_cleanup_creds();
2799#endif 2609#endif
2800 2610
diff --git a/session.h b/session.h
index f18eaf329..98e1dafee 100644
--- a/session.h
+++ b/session.h
@@ -1,4 +1,4 @@
1/* $OpenBSD: session.h,v 1.32 2016/03/07 19:02:43 djm Exp $ */ 1/* $OpenBSD: session.h,v 1.33 2016/08/13 17:47:41 markus Exp $ */
2 2
3/* 3/*
4 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved. 4 * Copyright (c) 2000, 2001 Markus Friedl. All rights reserved.
@@ -51,7 +51,6 @@ struct Session {
51 char *auth_data; 51 char *auth_data;
52 int single_connection; 52 int single_connection;
53 53
54 /* proto 2 */
55 int chanid; 54 int chanid;
56 int *x11_chanids; 55 int *x11_chanids;
57 int is_subsystem; 56 int is_subsystem;
diff --git a/sshd.c b/sshd.c
index 9fc829a91..b50ea1d99 100644
--- a/sshd.c
+++ b/sshd.c
@@ -1,4 +1,4 @@
1/* $OpenBSD: sshd.c,v 1.471 2016/08/03 04:23:55 dtucker Exp $ */ 1/* $OpenBSD: sshd.c,v 1.472 2016/08/13 17:47:41 markus Exp $ */
2/* 2/*
3 * Author: Tatu Ylonen <ylo@cs.hut.fi> 3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
@@ -87,7 +87,6 @@
87 87
88#include "xmalloc.h" 88#include "xmalloc.h"
89#include "ssh.h" 89#include "ssh.h"
90#include "ssh1.h"
91#include "ssh2.h" 90#include "ssh2.h"
92#include "rsa.h" 91#include "rsa.h"
93#include "sshpty.h" 92#include "sshpty.h"
@@ -201,22 +200,12 @@ int have_agent = 0;
201 * not very useful. Currently, memory locking is not implemented. 200 * not very useful. Currently, memory locking is not implemented.
202 */ 201 */
203struct { 202struct {
204 Key *server_key; /* ephemeral server key */
205 Key *ssh1_host_key; /* ssh1 host key */
206 Key **host_keys; /* all private host keys */ 203 Key **host_keys; /* all private host keys */
207 Key **host_pubkeys; /* all public host keys */ 204 Key **host_pubkeys; /* all public host keys */
208 Key **host_certificates; /* all public host certificates */ 205 Key **host_certificates; /* all public host certificates */
209 int have_ssh1_key;
210 int have_ssh2_key; 206 int have_ssh2_key;
211 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
212} sensitive_data; 207} sensitive_data;
213 208
214/*
215 * Flag indicating whether the RSA server key needs to be regenerated.
216 * Is set in the SIGALRM handler and cleared when the key is regenerated.
217 */
218static volatile sig_atomic_t key_do_regen = 0;
219
220/* This is set to true when a signal is received. */ 209/* This is set to true when a signal is received. */
221static volatile sig_atomic_t received_sighup = 0; 210static volatile sig_atomic_t received_sighup = 0;
222static volatile sig_atomic_t received_sigterm = 0; 211static volatile sig_atomic_t received_sigterm = 0;
@@ -255,10 +244,6 @@ struct passwd *privsep_pw = NULL;
255/* Prototypes for various functions defined later in this file. */ 244/* Prototypes for various functions defined later in this file. */
256void destroy_sensitive_data(void); 245void destroy_sensitive_data(void);
257void demote_sensitive_data(void); 246void demote_sensitive_data(void);
258
259#ifdef WITH_SSH1
260static void do_ssh1_kex(void);
261#endif
262static void do_ssh2_kex(void); 247static void do_ssh2_kex(void);
263 248
264/* 249/*
@@ -375,43 +360,10 @@ grace_alarm_handler(int sig)
375 ssh_remote_ipaddr(active_state), ssh_remote_port(active_state)); 360 ssh_remote_ipaddr(active_state), ssh_remote_port(active_state));
376} 361}
377 362
378/*
379 * Signal handler for the key regeneration alarm. Note that this
380 * alarm only occurs in the daemon waiting for connections, and it does not
381 * do anything with the private key or random state before forking.
382 * Thus there should be no concurrency control/asynchronous execution
383 * problems.
384 */
385static void
386generate_ephemeral_server_key(void)
387{
388 verbose("Generating %s%d bit RSA key.",
389 sensitive_data.server_key ? "new " : "", options.server_key_bits);
390 if (sensitive_data.server_key != NULL)
391 key_free(sensitive_data.server_key);
392 sensitive_data.server_key = key_generate(KEY_RSA1,
393 options.server_key_bits);
394 verbose("RSA key generation complete.");
395
396 arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
397}
398
399/*ARGSUSED*/
400static void
401key_regeneration_alarm(int sig)
402{
403 int save_errno = errno;
404
405 signal(SIGALRM, SIG_DFL);
406 errno = save_errno;
407 key_do_regen = 1;
408}
409
410static void 363static void
411sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out) 364sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out)
412{ 365{
413 u_int i; 366 u_int i;
414 int mismatch;
415 int remote_major, remote_minor; 367 int remote_major, remote_minor;
416 int major, minor; 368 int major, minor;
417 char *s, *newline = "\n"; 369 char *s, *newline = "\n";
@@ -511,42 +463,13 @@ sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out)
511 "refusing connection", remote_version); 463 "refusing connection", remote_version);
512 } 464 }
513 465
514 mismatch = 0;
515 switch (remote_major) {
516 case 1:
517 if (remote_minor == 99) {
518 if (options.protocol & SSH_PROTO_2)
519 enable_compat20();
520 else
521 mismatch = 1;
522 break;
523 }
524 if (!(options.protocol & SSH_PROTO_1)) {
525 mismatch = 1;
526 break;
527 }
528 if (remote_minor < 3) {
529 packet_disconnect("Your ssh version is too old and "
530 "is no longer supported. Please install a newer version.");
531 } else if (remote_minor == 3) {
532 /* note that this disables agent-forwarding */
533 enable_compat13();
534 }
535 break;
536 case 2:
537 if (options.protocol & SSH_PROTO_2) {
538 enable_compat20();
539 break;
540 }
541 /* FALLTHROUGH */
542 default:
543 mismatch = 1;
544 break;
545 }
546 chop(server_version_string); 466 chop(server_version_string);
547 debug("Local version string %.200s", server_version_string); 467 debug("Local version string %.200s", server_version_string);
548 468
549 if (mismatch) { 469 if (remote_major == 2 ||
470 (remote_major == 1 && remote_minor == 99)) {
471 enable_compat20();
472 } else {
550 s = "Protocol major versions differ.\n"; 473 s = "Protocol major versions differ.\n";
551 (void) atomicio(vwrite, sock_out, s, strlen(s)); 474 (void) atomicio(vwrite, sock_out, s, strlen(s));
552 close(sock_in); 475 close(sock_in);
@@ -565,10 +488,6 @@ destroy_sensitive_data(void)
565{ 488{
566 int i; 489 int i;
567 490
568 if (sensitive_data.server_key) {
569 key_free(sensitive_data.server_key);
570 sensitive_data.server_key = NULL;
571 }
572 for (i = 0; i < options.num_host_key_files; i++) { 491 for (i = 0; i < options.num_host_key_files; i++) {
573 if (sensitive_data.host_keys[i]) { 492 if (sensitive_data.host_keys[i]) {
574 key_free(sensitive_data.host_keys[i]); 493 key_free(sensitive_data.host_keys[i]);
@@ -579,8 +498,6 @@ destroy_sensitive_data(void)
579 sensitive_data.host_certificates[i] = NULL; 498 sensitive_data.host_certificates[i] = NULL;
580 } 499 }
581 } 500 }
582 sensitive_data.ssh1_host_key = NULL;
583 explicit_bzero(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
584} 501}
585 502
586/* Demote private to public keys for network child */ 503/* Demote private to public keys for network child */
@@ -590,24 +507,14 @@ demote_sensitive_data(void)
590 Key *tmp; 507 Key *tmp;
591 int i; 508 int i;
592 509
593 if (sensitive_data.server_key) {
594 tmp = key_demote(sensitive_data.server_key);
595 key_free(sensitive_data.server_key);
596 sensitive_data.server_key = tmp;
597 }
598
599 for (i = 0; i < options.num_host_key_files; i++) { 510 for (i = 0; i < options.num_host_key_files; i++) {
600 if (sensitive_data.host_keys[i]) { 511 if (sensitive_data.host_keys[i]) {
601 tmp = key_demote(sensitive_data.host_keys[i]); 512 tmp = key_demote(sensitive_data.host_keys[i]);
602 key_free(sensitive_data.host_keys[i]); 513 key_free(sensitive_data.host_keys[i]);
603 sensitive_data.host_keys[i] = tmp; 514 sensitive_data.host_keys[i] = tmp;
604 if (tmp->type == KEY_RSA1)
605 sensitive_data.ssh1_host_key = tmp;
606 } 515 }
607 /* Certs do not need demotion */ 516 /* Certs do not need demotion */
608 } 517 }
609
610 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
611} 518}
612 519
613static void 520static void
@@ -803,7 +710,7 @@ list_hostkey_types(void)
803 key = sensitive_data.host_keys[i]; 710 key = sensitive_data.host_keys[i];
804 if (key == NULL) 711 if (key == NULL)
805 key = sensitive_data.host_pubkeys[i]; 712 key = sensitive_data.host_pubkeys[i];
806 if (key == NULL || key->type == KEY_RSA1) 713 if (key == NULL)
807 continue; 714 continue;
808 /* Check that the key is accepted in HostkeyAlgorithms */ 715 /* Check that the key is accepted in HostkeyAlgorithms */
809 if (match_pattern_list(sshkey_ssh_name(key), 716 if (match_pattern_list(sshkey_ssh_name(key),
@@ -952,7 +859,7 @@ notify_hostkeys(struct ssh *ssh)
952 for (i = nkeys = 0; i < options.num_host_key_files; i++) { 859 for (i = nkeys = 0; i < options.num_host_key_files; i++) {
953 key = get_hostkey_public_by_index(i, ssh); 860 key = get_hostkey_public_by_index(i, ssh);
954 if (key == NULL || key->type == KEY_UNSPEC || 861 if (key == NULL || key->type == KEY_UNSPEC ||
955 key->type == KEY_RSA1 || sshkey_is_cert(key)) 862 sshkey_is_cert(key))
956 continue; 863 continue;
957 fp = sshkey_fingerprint(key, options.fingerprint_hash, 864 fp = sshkey_fingerprint(key, options.fingerprint_hash,
958 SSH_FP_DEFAULT); 865 SSH_FP_DEFAULT);
@@ -1038,13 +945,6 @@ send_rexec_state(int fd, struct sshbuf *conf)
1038 /* 945 /*
1039 * Protocol from reexec master to child: 946 * Protocol from reexec master to child:
1040 * string configuration 947 * string configuration
1041 * u_int ephemeral_key_follows
1042 * bignum e (only if ephemeral_key_follows == 1)
1043 * bignum n "
1044 * bignum d "
1045 * bignum iqmp "
1046 * bignum p "
1047 * bignum q "
1048 * string rngseed (only if OpenSSL is not self-seeded) 948 * string rngseed (only if OpenSSL is not self-seeded)
1049 */ 949 */
1050 if ((m = sshbuf_new()) == NULL) 950 if ((m = sshbuf_new()) == NULL)
@@ -1052,28 +952,6 @@ send_rexec_state(int fd, struct sshbuf *conf)
1052 if ((r = sshbuf_put_stringb(m, conf)) != 0) 952 if ((r = sshbuf_put_stringb(m, conf)) != 0)
1053 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 953 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1054 954
1055#ifdef WITH_SSH1
1056 if (sensitive_data.server_key != NULL &&
1057 sensitive_data.server_key->type == KEY_RSA1) {
1058 if ((r = sshbuf_put_u32(m, 1)) != 0 ||
1059 (r = sshbuf_put_bignum1(m,
1060 sensitive_data.server_key->rsa->e)) != 0 ||
1061 (r = sshbuf_put_bignum1(m,
1062 sensitive_data.server_key->rsa->n)) != 0 ||
1063 (r = sshbuf_put_bignum1(m,
1064 sensitive_data.server_key->rsa->d)) != 0 ||
1065 (r = sshbuf_put_bignum1(m,
1066 sensitive_data.server_key->rsa->iqmp)) != 0 ||
1067 (r = sshbuf_put_bignum1(m,
1068 sensitive_data.server_key->rsa->p)) != 0 ||
1069 (r = sshbuf_put_bignum1(m,
1070 sensitive_data.server_key->rsa->q)) != 0)
1071 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1072 } else
1073#endif
1074 if ((r = sshbuf_put_u32(m, 0)) != 0)
1075 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1076
1077#if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY) 955#if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1078 rexec_send_rng_seed(m); 956 rexec_send_rng_seed(m);
1079#endif 957#endif
@@ -1107,24 +985,6 @@ recv_rexec_state(int fd, Buffer *conf)
1107 buffer_append(conf, cp, len); 985 buffer_append(conf, cp, len);
1108 free(cp); 986 free(cp);
1109 987
1110 if (buffer_get_int(&m)) {
1111#ifdef WITH_SSH1
1112 if (sensitive_data.server_key != NULL)
1113 key_free(sensitive_data.server_key);
1114 sensitive_data.server_key = key_new_private(KEY_RSA1);
1115 buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
1116 buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
1117 buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
1118 buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
1119 buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
1120 buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
1121 if (rsa_generate_additional_parameters(
1122 sensitive_data.server_key->rsa) != 0)
1123 fatal("%s: rsa_generate_additional_parameters "
1124 "error", __func__);
1125#endif
1126 }
1127
1128#if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY) 988#if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1129 rexec_recv_rng_seed(&m); 989 rexec_recv_rng_seed(&m);
1130#endif 990#endif
@@ -1248,7 +1108,7 @@ server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1248{ 1108{
1249 fd_set *fdset; 1109 fd_set *fdset;
1250 int i, j, ret, maxfd; 1110 int i, j, ret, maxfd;
1251 int key_used = 0, startups = 0; 1111 int startups = 0;
1252 int startup_p[2] = { -1 , -1 }; 1112 int startup_p[2] = { -1 , -1 };
1253 struct sockaddr_storage from; 1113 struct sockaddr_storage from;
1254 socklen_t fromlen; 1114 socklen_t fromlen;
@@ -1295,11 +1155,6 @@ server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1295 unlink(options.pid_file); 1155 unlink(options.pid_file);
1296 exit(received_sigterm == SIGTERM ? 0 : 255); 1156 exit(received_sigterm == SIGTERM ? 0 : 255);
1297 } 1157 }
1298 if (key_used && key_do_regen) {
1299 generate_ephemeral_server_key();
1300 key_used = 0;
1301 key_do_regen = 0;
1302 }
1303 if (ret < 0) 1158 if (ret < 0)
1304 continue; 1159 continue;
1305 1160
@@ -1434,19 +1289,6 @@ server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1434 close(config_s[0]); 1289 close(config_s[0]);
1435 close(config_s[1]); 1290 close(config_s[1]);
1436 } 1291 }
1437
1438 /*
1439 * Mark that the key has been used (it
1440 * was "given" to the child).
1441 */
1442 if ((options.protocol & SSH_PROTO_1) &&
1443 key_used == 0) {
1444 /* Schedule server key regeneration alarm. */
1445 signal(SIGALRM, key_regeneration_alarm);
1446 alarm(options.key_regeneration_time);
1447 key_used = 1;
1448 }
1449
1450 close(*newsock); 1292 close(*newsock);
1451 1293
1452 /* 1294 /*
@@ -1619,8 +1461,7 @@ main(int ac, char **av)
1619 options.log_level = SYSLOG_LEVEL_QUIET; 1461 options.log_level = SYSLOG_LEVEL_QUIET;
1620 break; 1462 break;
1621 case 'b': 1463 case 'b':
1622 options.server_key_bits = (int)strtonum(optarg, 256, 1464 /* ignored */
1623 32768, NULL);
1624 break; 1465 break;
1625 case 'p': 1466 case 'p':
1626 options.ports_from_cmdline = 1; 1467 options.ports_from_cmdline = 1;
@@ -1726,9 +1567,6 @@ main(int ac, char **av)
1726 drop_cray_privs(); 1567 drop_cray_privs();
1727#endif 1568#endif
1728 1569
1729 sensitive_data.server_key = NULL;
1730 sensitive_data.ssh1_host_key = NULL;
1731 sensitive_data.have_ssh1_key = 0;
1732 sensitive_data.have_ssh2_key = 0; 1570 sensitive_data.have_ssh2_key = 0;
1733 1571
1734 /* 1572 /*
@@ -1852,8 +1690,7 @@ main(int ac, char **av)
1852 sensitive_data.host_keys[i] = key; 1690 sensitive_data.host_keys[i] = key;
1853 sensitive_data.host_pubkeys[i] = pubkey; 1691 sensitive_data.host_pubkeys[i] = pubkey;
1854 1692
1855 if (key == NULL && pubkey != NULL && pubkey->type != KEY_RSA1 && 1693 if (key == NULL && pubkey != NULL && have_agent) {
1856 have_agent) {
1857 debug("will rely on agent for hostkey %s", 1694 debug("will rely on agent for hostkey %s",
1858 options.host_key_files[i]); 1695 options.host_key_files[i]);
1859 keytype = pubkey->type; 1696 keytype = pubkey->type;
@@ -1868,10 +1705,6 @@ main(int ac, char **av)
1868 } 1705 }
1869 1706
1870 switch (keytype) { 1707 switch (keytype) {
1871 case KEY_RSA1:
1872 sensitive_data.ssh1_host_key = key;
1873 sensitive_data.have_ssh1_key = 1;
1874 break;
1875 case KEY_RSA: 1708 case KEY_RSA:
1876 case KEY_DSA: 1709 case KEY_DSA:
1877 case KEY_ECDSA: 1710 case KEY_ECDSA:
@@ -1884,19 +1717,10 @@ main(int ac, char **av)
1884 SSH_FP_DEFAULT)) == NULL) 1717 SSH_FP_DEFAULT)) == NULL)
1885 fatal("sshkey_fingerprint failed"); 1718 fatal("sshkey_fingerprint failed");
1886 debug("%s host key #%d: %s %s", 1719 debug("%s host key #%d: %s %s",
1887 key ? "private" : "agent", i, keytype == KEY_RSA1 ? 1720 key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1888 sshkey_type(pubkey) : sshkey_ssh_name(pubkey), fp);
1889 free(fp); 1721 free(fp);
1890 } 1722 }
1891 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) { 1723 if (!sensitive_data.have_ssh2_key) {
1892 logit("Disabling protocol version 1. Could not load host key");
1893 options.protocol &= ~SSH_PROTO_1;
1894 }
1895 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1896 logit("Disabling protocol version 2. Could not load host key");
1897 options.protocol &= ~SSH_PROTO_2;
1898 }
1899 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1900 logit("sshd: no hostkeys available -- exiting."); 1724 logit("sshd: no hostkeys available -- exiting.");
1901 exit(1); 1725 exit(1);
1902 } 1726 }
@@ -1944,33 +1768,6 @@ main(int ac, char **av)
1944 key_type(key)); 1768 key_type(key));
1945 } 1769 }
1946 1770
1947#ifdef WITH_SSH1
1948 /* Check certain values for sanity. */
1949 if (options.protocol & SSH_PROTO_1) {
1950 if (options.server_key_bits < SSH_RSA_MINIMUM_MODULUS_SIZE ||
1951 options.server_key_bits > OPENSSL_RSA_MAX_MODULUS_BITS) {
1952 fprintf(stderr, "Bad server key size.\n");
1953 exit(1);
1954 }
1955 /*
1956 * Check that server and host key lengths differ sufficiently. This
1957 * is necessary to make double encryption work with rsaref. Oh, I
1958 * hate software patents. I dont know if this can go? Niels
1959 */
1960 if (options.server_key_bits >
1961 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1962 SSH_KEY_BITS_RESERVED && options.server_key_bits <
1963 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1964 SSH_KEY_BITS_RESERVED) {
1965 options.server_key_bits =
1966 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1967 SSH_KEY_BITS_RESERVED;
1968 debug("Forcing server key to %d bits to make it differ from host key.",
1969 options.server_key_bits);
1970 }
1971 }
1972#endif
1973
1974 if (use_privsep) { 1771 if (use_privsep) {
1975 struct stat st; 1772 struct stat st;
1976 1773
@@ -2068,9 +1865,6 @@ main(int ac, char **av)
2068 platform_pre_listen(); 1865 platform_pre_listen();
2069 server_listen(); 1866 server_listen();
2070 1867
2071 if (options.protocol & SSH_PROTO_1)
2072 generate_ephemeral_server_key();
2073
2074 signal(SIGHUP, sighup_handler); 1868 signal(SIGHUP, sighup_handler);
2075 signal(SIGCHLD, main_sigchld_handler); 1869 signal(SIGCHLD, main_sigchld_handler);
2076 signal(SIGTERM, sigterm_handler); 1870 signal(SIGTERM, sigterm_handler);
@@ -2220,11 +2014,6 @@ main(int ac, char **av)
2220 alarm(options.login_grace_time); 2014 alarm(options.login_grace_time);
2221 2015
2222 sshd_exchange_identification(ssh, sock_in, sock_out); 2016 sshd_exchange_identification(ssh, sock_in, sock_out);
2223
2224 /* In inetd mode, generate ephemeral key only for proto 1 connections */
2225 if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
2226 generate_ephemeral_server_key();
2227
2228 packet_set_nonblocking(); 2017 packet_set_nonblocking();
2229 2018
2230 /* allocate authentication context */ 2019 /* allocate authentication context */
@@ -2242,7 +2031,7 @@ main(int ac, char **av)
2242 if (use_privsep) { 2031 if (use_privsep) {
2243 if (privsep_preauth(authctxt) == 1) 2032 if (privsep_preauth(authctxt) == 1)
2244 goto authenticated; 2033 goto authenticated;
2245 } else if (compat20 && have_agent) { 2034 } else if (have_agent) {
2246 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) { 2035 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2247 error("Unable to get agent socket: %s", ssh_err(r)); 2036 error("Unable to get agent socket: %s", ssh_err(r));
2248 have_agent = 0; 2037 have_agent = 0;
@@ -2251,17 +2040,9 @@ main(int ac, char **av)
2251 2040
2252 /* perform the key exchange */ 2041 /* perform the key exchange */
2253 /* authenticate user and start session */ 2042 /* authenticate user and start session */
2254 if (compat20) { 2043 do_ssh2_kex();
2255 do_ssh2_kex(); 2044 do_authentication2(authctxt);
2256 do_authentication2(authctxt); 2045
2257 } else {
2258#ifdef WITH_SSH1
2259 do_ssh1_kex();
2260 do_authentication(authctxt);
2261#else
2262 fatal("ssh1 not supported");
2263#endif
2264 }
2265 /* 2046 /*
2266 * If we use privilege separation, the unprivileged child transfers 2047 * If we use privilege separation, the unprivileged child transfers
2267 * the current keystate and exits 2048 * the current keystate and exits
@@ -2309,16 +2090,13 @@ main(int ac, char **av)
2309 if (use_privsep) { 2090 if (use_privsep) {
2310 privsep_postauth(authctxt); 2091 privsep_postauth(authctxt);
2311 /* the monitor process [priv] will not return */ 2092 /* the monitor process [priv] will not return */
2312 if (!compat20)
2313 destroy_sensitive_data();
2314 } 2093 }
2315 2094
2316 packet_set_timeout(options.client_alive_interval, 2095 packet_set_timeout(options.client_alive_interval,
2317 options.client_alive_count_max); 2096 options.client_alive_count_max);
2318 2097
2319 /* Try to send all our hostkeys to the client */ 2098 /* Try to send all our hostkeys to the client */
2320 if (compat20) 2099 notify_hostkeys(active_state);
2321 notify_hostkeys(active_state);
2322 2100
2323 /* Start session. */ 2101 /* Start session. */
2324 do_authenticated(authctxt); 2102 do_authenticated(authctxt);
@@ -2347,229 +2125,6 @@ main(int ac, char **av)
2347 exit(0); 2125 exit(0);
2348} 2126}
2349 2127
2350#ifdef WITH_SSH1
2351/*
2352 * Decrypt session_key_int using our private server key and private host key
2353 * (key with larger modulus first).
2354 */
2355int
2356ssh1_session_key(BIGNUM *session_key_int)
2357{
2358 struct ssh *ssh = active_state; /* XXX */
2359 int rsafail = 0;
2360
2361 if (BN_cmp(sensitive_data.server_key->rsa->n,
2362 sensitive_data.ssh1_host_key->rsa->n) > 0) {
2363 /* Server key has bigger modulus. */
2364 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
2365 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
2366 SSH_KEY_BITS_RESERVED) {
2367 fatal("do_connection: %s port %d: "
2368 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2369 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
2370 BN_num_bits(sensitive_data.server_key->rsa->n),
2371 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2372 SSH_KEY_BITS_RESERVED);
2373 }
2374 if (rsa_private_decrypt(session_key_int, session_key_int,
2375 sensitive_data.server_key->rsa) != 0)
2376 rsafail++;
2377 if (rsa_private_decrypt(session_key_int, session_key_int,
2378 sensitive_data.ssh1_host_key->rsa) != 0)
2379 rsafail++;
2380 } else {
2381 /* Host key has bigger modulus (or they are equal). */
2382 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
2383 BN_num_bits(sensitive_data.server_key->rsa->n) +
2384 SSH_KEY_BITS_RESERVED) {
2385 fatal("do_connection: %s port %d: "
2386 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2387 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
2388 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
2389 BN_num_bits(sensitive_data.server_key->rsa->n),
2390 SSH_KEY_BITS_RESERVED);
2391 }
2392 if (rsa_private_decrypt(session_key_int, session_key_int,
2393 sensitive_data.ssh1_host_key->rsa) != 0)
2394 rsafail++;
2395 if (rsa_private_decrypt(session_key_int, session_key_int,
2396 sensitive_data.server_key->rsa) != 0)
2397 rsafail++;
2398 }
2399 return (rsafail);
2400}
2401
2402/*
2403 * SSH1 key exchange
2404 */
2405static void
2406do_ssh1_kex(void)
2407{
2408 struct ssh *ssh = active_state; /* XXX */
2409 int i, len;
2410 int rsafail = 0;
2411 BIGNUM *session_key_int, *fake_key_int, *real_key_int;
2412 u_char session_key[SSH_SESSION_KEY_LENGTH];
2413 u_char fake_key_bytes[4096 / 8];
2414 size_t fake_key_len;
2415 u_char cookie[8];
2416 u_int cipher_type, auth_mask, protocol_flags;
2417
2418 /*
2419 * Generate check bytes that the client must send back in the user
2420 * packet in order for it to be accepted; this is used to defy ip
2421 * spoofing attacks. Note that this only works against somebody
2422 * doing IP spoofing from a remote machine; any machine on the local
2423 * network can still see outgoing packets and catch the random
2424 * cookie. This only affects rhosts authentication, and this is one
2425 * of the reasons why it is inherently insecure.
2426 */
2427 arc4random_buf(cookie, sizeof(cookie));
2428
2429 /*
2430 * Send our public key. We include in the packet 64 bits of random
2431 * data that must be matched in the reply in order to prevent IP
2432 * spoofing.
2433 */
2434 packet_start(SSH_SMSG_PUBLIC_KEY);
2435 for (i = 0; i < 8; i++)
2436 packet_put_char(cookie[i]);
2437
2438 /* Store our public server RSA key. */
2439 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2440 packet_put_bignum(sensitive_data.server_key->rsa->e);
2441 packet_put_bignum(sensitive_data.server_key->rsa->n);
2442
2443 /* Store our public host RSA key. */
2444 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2445 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2446 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
2447
2448 /* Put protocol flags. */
2449 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2450
2451 /* Declare which ciphers we support. */
2452 packet_put_int(cipher_mask_ssh1(0));
2453
2454 /* Declare supported authentication types. */
2455 auth_mask = 0;
2456 if (options.rhosts_rsa_authentication)
2457 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2458 if (options.rsa_authentication)
2459 auth_mask |= 1 << SSH_AUTH_RSA;
2460 if (options.challenge_response_authentication == 1)
2461 auth_mask |= 1 << SSH_AUTH_TIS;
2462 if (options.password_authentication)
2463 auth_mask |= 1 << SSH_AUTH_PASSWORD;
2464 packet_put_int(auth_mask);
2465
2466 /* Send the packet and wait for it to be sent. */
2467 packet_send();
2468 packet_write_wait();
2469
2470 debug("Sent %d bit server key and %d bit host key.",
2471 BN_num_bits(sensitive_data.server_key->rsa->n),
2472 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2473
2474 /* Read clients reply (cipher type and session key). */
2475 packet_read_expect(SSH_CMSG_SESSION_KEY);
2476
2477 /* Get cipher type and check whether we accept this. */
2478 cipher_type = packet_get_char();
2479
2480 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
2481 packet_disconnect("Warning: client selects unsupported cipher.");
2482
2483 /* Get check bytes from the packet. These must match those we
2484 sent earlier with the public key packet. */
2485 for (i = 0; i < 8; i++)
2486 if (cookie[i] != packet_get_char())
2487 packet_disconnect("IP Spoofing check bytes do not match.");
2488
2489 debug("Encryption type: %.200s", cipher_name(cipher_type));
2490
2491 /* Get the encrypted integer. */
2492 if ((real_key_int = BN_new()) == NULL)
2493 fatal("do_ssh1_kex: BN_new failed");
2494 packet_get_bignum(real_key_int);
2495
2496 protocol_flags = packet_get_int();
2497 packet_set_protocol_flags(protocol_flags);
2498 packet_check_eom();
2499
2500 /* Setup a fake key in case RSA decryption fails */
2501 if ((fake_key_int = BN_new()) == NULL)
2502 fatal("do_ssh1_kex: BN_new failed");
2503 fake_key_len = BN_num_bytes(real_key_int);
2504 if (fake_key_len > sizeof(fake_key_bytes))
2505 fake_key_len = sizeof(fake_key_bytes);
2506 arc4random_buf(fake_key_bytes, fake_key_len);
2507 if (BN_bin2bn(fake_key_bytes, fake_key_len, fake_key_int) == NULL)
2508 fatal("do_ssh1_kex: BN_bin2bn failed");
2509
2510 /* Decrypt real_key_int using host/server keys */
2511 rsafail = PRIVSEP(ssh1_session_key(real_key_int));
2512 /* If decryption failed, use the fake key. Else, the real key. */
2513 if (rsafail)
2514 session_key_int = fake_key_int;
2515 else
2516 session_key_int = real_key_int;
2517
2518 /*
2519 * Extract session key from the decrypted integer. The key is in the
2520 * least significant 256 bits of the integer; the first byte of the
2521 * key is in the highest bits.
2522 */
2523 (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
2524 len = BN_num_bytes(session_key_int);
2525 if (len < 0 || (u_int)len > sizeof(session_key)) {
2526 error("%s: bad session key len from %s port %d: "
2527 "session_key_int %d > sizeof(session_key) %lu", __func__,
2528 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
2529 len, (u_long)sizeof(session_key));
2530 rsafail++;
2531 } else {
2532 explicit_bzero(session_key, sizeof(session_key));
2533 BN_bn2bin(session_key_int,
2534 session_key + sizeof(session_key) - len);
2535
2536 derive_ssh1_session_id(
2537 sensitive_data.ssh1_host_key->rsa->n,
2538 sensitive_data.server_key->rsa->n,
2539 cookie, session_id);
2540 /*
2541 * Xor the first 16 bytes of the session key with the
2542 * session id.
2543 */
2544 for (i = 0; i < 16; i++)
2545 session_key[i] ^= session_id[i];
2546 }
2547
2548 /* Destroy the private and public keys. No longer. */
2549 destroy_sensitive_data();
2550
2551 if (use_privsep)
2552 mm_ssh1_session_id(session_id);
2553
2554 /* Destroy the decrypted integer. It is no longer needed. */
2555 BN_clear_free(real_key_int);
2556 BN_clear_free(fake_key_int);
2557
2558 /* Set the session key. From this on all communications will be encrypted. */
2559 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2560
2561 /* Destroy our copy of the session key. It is no longer needed. */
2562 explicit_bzero(session_key, sizeof(session_key));
2563
2564 debug("Received session key; encryption turned on.");
2565
2566 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2567 packet_start(SSH_SMSG_SUCCESS);
2568 packet_send();
2569 packet_write_wait();
2570}
2571#endif
2572
2573int 2128int
2574sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen, 2129sshd_hostkey_sign(Key *privkey, Key *pubkey, u_char **signature, size_t *slen,
2575 const u_char *data, size_t dlen, const char *alg, u_int flag) 2130 const u_char *data, size_t dlen, const char *alg, u_int flag)