Fix an embarrassing mistake in config box handling which was causing
[u/mdw/putty] / ssh.c
CommitLineData
eaf1e20a 1/*
2 * SSH backend.
3 */
4
374330e2 5#include <stdio.h>
6#include <stdlib.h>
fb09bf1c 7#include <stdarg.h>
8#include <assert.h>
3c112d53 9#include <limits.h>
d051d1b4 10#include <signal.h>
374330e2 11
12#include "putty.h"
dacbd0e8 13#include "tree234.h"
fb09bf1c 14#include "ssh.h"
bf84a03a 15#ifndef NO_GSSAPI
b3d375b2 16#include "sshgssc.h"
42af6a67 17#include "sshgss.h"
bf84a03a 18#endif
374330e2 19
20#ifndef FALSE
21#define FALSE 0
22#endif
23#ifndef TRUE
24#define TRUE 1
25#endif
26
32874aea 27#define SSH1_MSG_DISCONNECT 1 /* 0x1 */
28#define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
29#define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
30#define SSH1_CMSG_USER 4 /* 0x4 */
31#define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
32#define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
33#define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
34#define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
35#define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
36#define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
37#define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
38#define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
39#define SSH1_SMSG_SUCCESS 14 /* 0xe */
40#define SSH1_SMSG_FAILURE 15 /* 0xf */
41#define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
42#define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
43#define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
44#define SSH1_CMSG_EOF 19 /* 0x13 */
45#define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
46#define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
47#define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
48#define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
49#define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
50#define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
51#define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
52#define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
53#define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
54#define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
55#define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
56#define SSH1_MSG_IGNORE 32 /* 0x20 */
57#define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
58#define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
59#define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
60#define SSH1_MSG_DEBUG 36 /* 0x24 */
61#define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
62#define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
63#define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
64#define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
65#define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
66#define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
67#define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
68
8f9e3231 69#define SSH1_AUTH_RHOSTS 1 /* 0x1 */
70#define SSH1_AUTH_RSA 2 /* 0x2 */
71#define SSH1_AUTH_PASSWORD 3 /* 0x3 */
72#define SSH1_AUTH_RHOSTS_RSA 4 /* 0x4 */
32874aea 73#define SSH1_AUTH_TIS 5 /* 0x5 */
74#define SSH1_AUTH_CCARD 16 /* 0x10 */
75
76#define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
b96dc54c 77/* Mask for protoflags we will echo back to server if seen */
32874aea 78#define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
79
80#define SSH2_MSG_DISCONNECT 1 /* 0x1 */
81#define SSH2_MSG_IGNORE 2 /* 0x2 */
82#define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
83#define SSH2_MSG_DEBUG 4 /* 0x4 */
84#define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
85#define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
86#define SSH2_MSG_KEXINIT 20 /* 0x14 */
87#define SSH2_MSG_NEWKEYS 21 /* 0x15 */
88#define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
89#define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
90#define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
91#define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
92#define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
93#define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
fae1a71b 94#define SSH2_MSG_KEXRSA_PUBKEY 30 /* 0x1e */
95#define SSH2_MSG_KEXRSA_SECRET 31 /* 0x1f */
96#define SSH2_MSG_KEXRSA_DONE 32 /* 0x20 */
32874aea 97#define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
98#define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
99#define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
100#define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
101#define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
102#define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
761187b6 103#define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
104#define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
32874aea 105#define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
106#define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
107#define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
108#define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
109#define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
110#define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
111#define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
112#define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
113#define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
114#define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
115#define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
116#define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
117#define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
118#define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
42af6a67 119#define SSH2_MSG_USERAUTH_GSSAPI_RESPONSE 60
120#define SSH2_MSG_USERAUTH_GSSAPI_TOKEN 61
121#define SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE 63
122#define SSH2_MSG_USERAUTH_GSSAPI_ERROR 64
123#define SSH2_MSG_USERAUTH_GSSAPI_ERRTOK 65
124#define SSH2_MSG_USERAUTH_GSSAPI_MIC 66
32874aea 125
00db133f 126/*
127 * Packet type contexts, so that ssh2_pkt_type can correctly decode
128 * the ambiguous type numbers back into the correct type strings.
129 */
acab36bc 130typedef enum {
131 SSH2_PKTCTX_NOKEX,
132 SSH2_PKTCTX_DHGROUP,
133 SSH2_PKTCTX_DHGEX,
134 SSH2_PKTCTX_RSAKEX
135} Pkt_KCtx;
136typedef enum {
137 SSH2_PKTCTX_NOAUTH,
138 SSH2_PKTCTX_PUBLICKEY,
139 SSH2_PKTCTX_PASSWORD,
42af6a67 140 SSH2_PKTCTX_GSSAPI,
acab36bc 141 SSH2_PKTCTX_KBDINTER
142} Pkt_ACtx;
00db133f 143
32874aea 144#define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
145#define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
146#define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
147#define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
148#define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
149#define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
150#define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
151#define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
152#define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
153#define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
154#define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
155#define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
156#define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
157#define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
158#define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
38c4a8da 159
160static const char *const ssh2_disconnect_reasons[] = {
161 NULL,
afb4d0dc 162 "host not allowed to connect",
163 "protocol error",
164 "key exchange failed",
165 "host authentication failed",
1da38d29 166 "MAC error",
afb4d0dc 167 "compression error",
168 "service not available",
169 "protocol version not supported",
170 "host key not verifiable",
171 "connection lost",
172 "by application",
173 "too many connections",
174 "auth cancelled by user",
175 "no more auth methods available",
176 "illegal user name",
38c4a8da 177};
9005f3ba 178
32874aea 179#define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
180#define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
181#define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
182#define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
d211621f 183
32874aea 184#define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
fb09bf1c 185
7d503c31 186/*
187 * Various remote-bug flags.
188 */
189#define BUG_CHOKES_ON_SSH1_IGNORE 1
190#define BUG_SSH2_HMAC 2
bd358db1 191#define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
0df73905 192#define BUG_CHOKES_ON_RSA 8
1dd353b5 193#define BUG_SSH2_RSA_PADDING 16
088bde77 194#define BUG_SSH2_DERIVEKEY 32
f382c87d 195#define BUG_SSH2_REKEY 64
dda87a28 196#define BUG_SSH2_PK_SESSIONID 128
c9739dba 197#define BUG_SSH2_MAXPKT 256
cf6ddb95 198#define BUG_CHOKES_ON_SSH2_IGNORE 512
bd358db1 199
c6ccd5c2 200/*
201 * Codes for terminal modes.
202 * Most of these are the same in SSH-1 and SSH-2.
7646c432 203 * This list is derived from RFC 4254 and
c6ccd5c2 204 * SSH-1 RFC-1.2.31.
205 */
206static const struct {
207 const char* const mode;
208 int opcode;
209 enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
210} ssh_ttymodes[] = {
211 /* "V" prefix discarded for special characters relative to SSH specs */
212 { "INTR", 1, TTY_OP_CHAR },
213 { "QUIT", 2, TTY_OP_CHAR },
214 { "ERASE", 3, TTY_OP_CHAR },
215 { "KILL", 4, TTY_OP_CHAR },
216 { "EOF", 5, TTY_OP_CHAR },
217 { "EOL", 6, TTY_OP_CHAR },
218 { "EOL2", 7, TTY_OP_CHAR },
219 { "START", 8, TTY_OP_CHAR },
220 { "STOP", 9, TTY_OP_CHAR },
221 { "SUSP", 10, TTY_OP_CHAR },
222 { "DSUSP", 11, TTY_OP_CHAR },
223 { "REPRINT", 12, TTY_OP_CHAR },
224 { "WERASE", 13, TTY_OP_CHAR },
225 { "LNEXT", 14, TTY_OP_CHAR },
226 { "FLUSH", 15, TTY_OP_CHAR },
227 { "SWTCH", 16, TTY_OP_CHAR },
228 { "STATUS", 17, TTY_OP_CHAR },
229 { "DISCARD", 18, TTY_OP_CHAR },
230 { "IGNPAR", 30, TTY_OP_BOOL },
231 { "PARMRK", 31, TTY_OP_BOOL },
232 { "INPCK", 32, TTY_OP_BOOL },
233 { "ISTRIP", 33, TTY_OP_BOOL },
234 { "INLCR", 34, TTY_OP_BOOL },
235 { "IGNCR", 35, TTY_OP_BOOL },
236 { "ICRNL", 36, TTY_OP_BOOL },
237 { "IUCLC", 37, TTY_OP_BOOL },
238 { "IXON", 38, TTY_OP_BOOL },
239 { "IXANY", 39, TTY_OP_BOOL },
240 { "IXOFF", 40, TTY_OP_BOOL },
241 { "IMAXBEL", 41, TTY_OP_BOOL },
242 { "ISIG", 50, TTY_OP_BOOL },
243 { "ICANON", 51, TTY_OP_BOOL },
244 { "XCASE", 52, TTY_OP_BOOL },
245 { "ECHO", 53, TTY_OP_BOOL },
246 { "ECHOE", 54, TTY_OP_BOOL },
247 { "ECHOK", 55, TTY_OP_BOOL },
248 { "ECHONL", 56, TTY_OP_BOOL },
249 { "NOFLSH", 57, TTY_OP_BOOL },
250 { "TOSTOP", 58, TTY_OP_BOOL },
251 { "IEXTEN", 59, TTY_OP_BOOL },
252 { "ECHOCTL", 60, TTY_OP_BOOL },
253 { "ECHOKE", 61, TTY_OP_BOOL },
254 { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
255 { "OPOST", 70, TTY_OP_BOOL },
256 { "OLCUC", 71, TTY_OP_BOOL },
257 { "ONLCR", 72, TTY_OP_BOOL },
258 { "OCRNL", 73, TTY_OP_BOOL },
259 { "ONOCR", 74, TTY_OP_BOOL },
260 { "ONLRET", 75, TTY_OP_BOOL },
261 { "CS7", 90, TTY_OP_BOOL },
262 { "CS8", 91, TTY_OP_BOOL },
263 { "PARENB", 92, TTY_OP_BOOL },
264 { "PARODD", 93, TTY_OP_BOOL }
265};
266
267/* Miscellaneous other tty-related constants. */
268#define SSH_TTY_OP_END 0
269/* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
270#define SSH1_TTY_OP_ISPEED 192
271#define SSH1_TTY_OP_OSPEED 193
272#define SSH2_TTY_OP_ISPEED 128
273#define SSH2_TTY_OP_OSPEED 129
274
275/* Helper functions for parsing tty-related config. */
276static unsigned int ssh_tty_parse_specchar(char *s)
277{
278 unsigned int ret;
279 if (*s) {
280 char *next = NULL;
281 ret = ctrlparse(s, &next);
282 if (!next) ret = s[0];
283 } else {
284 ret = 255; /* special value meaning "don't set" */
285 }
286 return ret;
287}
288static unsigned int ssh_tty_parse_boolean(char *s)
289{
290 if (stricmp(s, "yes") == 0 ||
291 stricmp(s, "on") == 0 ||
292 stricmp(s, "true") == 0 ||
293 stricmp(s, "+") == 0)
294 return 1; /* true */
295 else if (stricmp(s, "no") == 0 ||
296 stricmp(s, "off") == 0 ||
297 stricmp(s, "false") == 0 ||
298 stricmp(s, "-") == 0)
299 return 0; /* false */
300 else
301 return (atoi(s) != 0);
302}
303
00db133f 304#define translate(x) if (type == x) return #x
acab36bc 305#define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
306#define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
ae9ae89f 307static char *ssh1_pkt_type(int type)
00db133f 308{
309 translate(SSH1_MSG_DISCONNECT);
310 translate(SSH1_SMSG_PUBLIC_KEY);
311 translate(SSH1_CMSG_SESSION_KEY);
312 translate(SSH1_CMSG_USER);
313 translate(SSH1_CMSG_AUTH_RSA);
314 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
315 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
316 translate(SSH1_CMSG_AUTH_PASSWORD);
317 translate(SSH1_CMSG_REQUEST_PTY);
318 translate(SSH1_CMSG_WINDOW_SIZE);
319 translate(SSH1_CMSG_EXEC_SHELL);
320 translate(SSH1_CMSG_EXEC_CMD);
321 translate(SSH1_SMSG_SUCCESS);
322 translate(SSH1_SMSG_FAILURE);
323 translate(SSH1_CMSG_STDIN_DATA);
324 translate(SSH1_SMSG_STDOUT_DATA);
325 translate(SSH1_SMSG_STDERR_DATA);
326 translate(SSH1_CMSG_EOF);
327 translate(SSH1_SMSG_EXIT_STATUS);
328 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
329 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
330 translate(SSH1_MSG_CHANNEL_DATA);
331 translate(SSH1_MSG_CHANNEL_CLOSE);
332 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
333 translate(SSH1_SMSG_X11_OPEN);
334 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
335 translate(SSH1_MSG_PORT_OPEN);
336 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
337 translate(SSH1_SMSG_AGENT_OPEN);
338 translate(SSH1_MSG_IGNORE);
339 translate(SSH1_CMSG_EXIT_CONFIRMATION);
340 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
341 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
342 translate(SSH1_MSG_DEBUG);
343 translate(SSH1_CMSG_REQUEST_COMPRESSION);
344 translate(SSH1_CMSG_AUTH_TIS);
345 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
346 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
347 translate(SSH1_CMSG_AUTH_CCARD);
348 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
349 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
350 return "unknown";
351}
acab36bc 352static char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx, int type)
00db133f 353{
42af6a67 354 translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
355 translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
356 translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
357 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
358 translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
359 translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
00db133f 360 translate(SSH2_MSG_DISCONNECT);
361 translate(SSH2_MSG_IGNORE);
362 translate(SSH2_MSG_UNIMPLEMENTED);
363 translate(SSH2_MSG_DEBUG);
364 translate(SSH2_MSG_SERVICE_REQUEST);
365 translate(SSH2_MSG_SERVICE_ACCEPT);
366 translate(SSH2_MSG_KEXINIT);
367 translate(SSH2_MSG_NEWKEYS);
acab36bc 368 translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
369 translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
370 translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
371 translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
372 translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
373 translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
374 translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
375 translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
376 translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
00db133f 377 translate(SSH2_MSG_USERAUTH_REQUEST);
378 translate(SSH2_MSG_USERAUTH_FAILURE);
379 translate(SSH2_MSG_USERAUTH_SUCCESS);
380 translate(SSH2_MSG_USERAUTH_BANNER);
acab36bc 381 translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
382 translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
383 translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
384 translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
00db133f 385 translate(SSH2_MSG_GLOBAL_REQUEST);
386 translate(SSH2_MSG_REQUEST_SUCCESS);
387 translate(SSH2_MSG_REQUEST_FAILURE);
388 translate(SSH2_MSG_CHANNEL_OPEN);
389 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
390 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
391 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
392 translate(SSH2_MSG_CHANNEL_DATA);
393 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
394 translate(SSH2_MSG_CHANNEL_EOF);
395 translate(SSH2_MSG_CHANNEL_CLOSE);
396 translate(SSH2_MSG_CHANNEL_REQUEST);
397 translate(SSH2_MSG_CHANNEL_SUCCESS);
398 translate(SSH2_MSG_CHANNEL_FAILURE);
399 return "unknown";
400}
401#undef translate
402#undef translatec
7d503c31 403
9a10ecf4 404/* Enumeration values for fields in SSH-1 packets */
405enum {
406 PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
407 /* These values are for communicating relevant semantics of
408 * fields to the packet logging code. */
409 PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
410};
972a41c8 411
acddebd9 412/*
413 * Coroutine mechanics for the sillier bits of the code. If these
414 * macros look impenetrable to you, you might find it helpful to
415 * read
416 *
417 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
418 *
419 * which explains the theory behind these macros.
b624d1e6 420 *
421 * In particular, if you are getting `case expression not constant'
422 * errors when building with MS Visual Studio, this is because MS's
423 * Edit and Continue debugging feature causes their compiler to
424 * violate ANSI C. To disable Edit and Continue debugging:
425 *
426 * - right-click ssh.c in the FileView
427 * - click Settings
428 * - select the C/C++ tab and the General category
429 * - under `Debug info:', select anything _other_ than `Program
430 * Database for Edit and Continue'.
acddebd9 431 */
51470298 432#define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
433#define crState(t) \
434 struct t *s; \
3d88e64d 435 if (!ssh->t) ssh->t = snew(struct t); \
51470298 436 s = ssh->t;
437#define crFinish(z) } *crLine = 0; return (z); }
438#define crFinishV } *crLine = 0; return; }
374330e2 439#define crReturn(z) \
440 do {\
51470298 441 *crLine =__LINE__; return (z); case __LINE__:;\
374330e2 442 } while (0)
443#define crReturnV \
444 do {\
51470298 445 *crLine=__LINE__; return; case __LINE__:;\
374330e2 446 } while (0)
51470298 447#define crStop(z) do{ *crLine = 0; return (z); }while(0)
448#define crStopV do{ *crLine = 0; return; }while(0)
fb09bf1c 449#define crWaitUntil(c) do { crReturn(0); } while (!(c))
7cca0d81 450#define crWaitUntilV(c) do { crReturnV; } while (!(c))
374330e2 451
51470298 452typedef struct ssh_tag *Ssh;
ff3187f6 453struct Packet;
454
dacd8872 455static struct Packet *ssh1_pkt_init(int pkt_type);
ff3187f6 456static struct Packet *ssh2_pkt_init(int pkt_type);
dacd8872 457static void ssh_pkt_ensure(struct Packet *, int length);
458static void ssh_pkt_adddata(struct Packet *, void *data, int len);
459static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
ff3187f6 460static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
dacd8872 461static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
462static void ssh_pkt_addstring_start(struct Packet *);
463static void ssh_pkt_addstring_str(struct Packet *, char *data);
464static void ssh_pkt_addstring_data(struct Packet *, char *data, int len);
465static void ssh_pkt_addstring(struct Packet *, char *data);
d8baa528 466static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
dacd8872 467static void ssh1_pkt_addmp(struct Packet *, Bignum b);
ff3187f6 468static void ssh2_pkt_addmp(struct Packet *, Bignum b);
469static int ssh2_pkt_construct(Ssh, struct Packet *);
470static void ssh2_pkt_send(Ssh, struct Packet *);
590f6a5f 471static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
ff3187f6 472static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
473 struct Packet *pktin);
474static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
475 struct Packet *pktin);
997097db 476static void ssh2_channel_check_close(struct ssh_channel *c);
bc06669b 477static void ssh_channel_destroy(struct ssh_channel *c);
3d63ca2e 478
5471d09a 479/*
480 * Buffer management constants. There are several of these for
481 * various different purposes:
482 *
483 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
484 * on a local data stream before we throttle the whole SSH
2e85c969 485 * connection (in SSH-1 only). Throttling the whole connection is
5471d09a 486 * pretty drastic so we set this high in the hope it won't
487 * happen very often.
488 *
489 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
490 * on the SSH connection itself before we defensively throttle
491 * _all_ local data streams. This is pretty drastic too (though
2e85c969 492 * thankfully unlikely in SSH-2 since the window mechanism should
5471d09a 493 * ensure that the server never has any need to throttle its end
494 * of the connection), so we set this high as well.
495 *
2e85c969 496 * - OUR_V2_WINSIZE is the maximum window size we present on SSH-2
5471d09a 497 * channels.
9b53e9b8 498 *
499 * - OUR_V2_BIGWIN is the window size we advertise for the only
3361b80a 500 * channel in a simple connection. It must be <= INT_MAX.
9916cc1e 501 *
502 * - OUR_V2_MAXPKT is the official "maximum packet size" we send
503 * to the remote side. This actually has nothing to do with the
504 * size of the _packet_, but is instead a limit on the amount
505 * of data we're willing to receive in a single SSH2 channel
506 * data message.
507 *
508 * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
509 * _packet_ we're prepared to cope with. It must be a multiple
510 * of the cipher block size, and must be at least 35000.
5471d09a 511 */
512
513#define SSH1_BUFFER_LIMIT 32768
514#define SSH_MAX_BACKLOG 32768
515#define OUR_V2_WINSIZE 16384
3361b80a 516#define OUR_V2_BIGWIN 0x7fffffff
954d5c5a 517#define OUR_V2_MAXPKT 0x4000UL
9916cc1e 518#define OUR_V2_PACKETLIMIT 0x9000UL
d74d141c 519
85cc02bb 520const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
e5574168 521
8b2715b2 522const static struct ssh_mac *macs[] = {
6668a75e 523 &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
32874aea 524};
8b2715b2 525const static struct ssh_mac *buggymacs[] = {
6668a75e 526 &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
32874aea 527};
e5574168 528
5366aed8 529static void *ssh_comp_none_init(void)
530{
531 return NULL;
532}
533static void ssh_comp_none_cleanup(void *handle)
32874aea 534{
535}
5366aed8 536static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
32874aea 537 unsigned char **outblock, int *outlen)
538{
539 return 0;
540}
5366aed8 541static int ssh_comp_none_disable(void *handle)
32874aea 542{
4ba9b64b 543 return 0;
544}
57476f6b 545const static struct ssh_compress ssh_comp_none = {
ab18ccff 546 "none", NULL,
5366aed8 547 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
548 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
549 ssh_comp_none_disable, NULL
e5574168 550};
4ba9b64b 551extern const struct ssh_compress ssh_zlib;
552const static struct ssh_compress *compressions[] = {
32874aea 553 &ssh_zlib, &ssh_comp_none
554};
374330e2 555
32874aea 556enum { /* channel types */
783415f8 557 CHAN_MAINSESSION,
558 CHAN_X11,
559 CHAN_AGENT,
bc240b21 560 CHAN_SOCKDATA,
c6b41791 561 CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
562 /*
563 * CHAN_ZOMBIE is used to indicate a channel for which we've
564 * already destroyed the local data source: for instance, if a
565 * forwarded port experiences a socket error on the local side, we
566 * immediately destroy its local socket and turn the SSH channel
567 * into CHAN_ZOMBIE.
568 */
569 CHAN_ZOMBIE
783415f8 570};
571
dacbd0e8 572/*
0e443c99 573 * little structure to keep track of outstanding WINDOW_ADJUSTs
574 */
575struct winadj {
576 struct winadj *next;
577 unsigned size;
578};
579
580/*
dacbd0e8 581 * 2-3-4 tree storing channels.
582 */
583struct ssh_channel {
51470298 584 Ssh ssh; /* pointer back to main context */
d211621f 585 unsigned remoteid, localid;
dacbd0e8 586 int type;
64d6ff88 587 /* True if we opened this channel but server hasn't confirmed. */
588 int halfopen;
0357890f 589 /*
2e85c969 590 * In SSH-1, this value contains four bits:
0357890f 591 *
592 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
593 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
594 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
595 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
596 *
597 * A channel is completely finished with when all four bits are set.
bc06669b 598 *
599 * In SSH-2, the four bits mean:
600 *
601 * 1 We have sent SSH2_MSG_CHANNEL_EOF.
602 * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
603 * 4 We have received SSH2_MSG_CHANNEL_EOF.
604 * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
605 *
606 * A channel is completely finished with when we have both sent
607 * and received CLOSE.
608 *
609 * The symbolic constants below use the SSH-2 terminology, which
610 * is a bit confusing in SSH-1, but we have to use _something_.
0357890f 611 */
bc06669b 612#define CLOSES_SENT_EOF 1
613#define CLOSES_SENT_CLOSE 2
614#define CLOSES_RCVD_EOF 4
615#define CLOSES_RCVD_CLOSE 8
dacbd0e8 616 int closes;
78280721 617
618 /*
bc06669b 619 * This flag indicates that an EOF is pending on the outgoing side
620 * of the channel: that is, wherever we're getting the data for
621 * this channel has sent us some data followed by EOF. We can't
622 * actually send the EOF until we've finished sending the data, so
623 * we set this flag instead to remind us to do so once our buffer
624 * is clear.
78280721 625 */
bc06669b 626 int pending_eof;
78280721 627
ff68564b 628 /*
629 * True if this channel is causing the underlying connection to be
630 * throttled.
631 */
632 int throttling_conn;
5471d09a 633 union {
5471d09a 634 struct ssh2_data_channel {
635 bufchain outbuffer;
636 unsigned remwindow, remmaxpkt;
467e064d 637 /* locwindow is signed so we can cope with excess data. */
9b53e9b8 638 int locwindow, locmaxwin;
0e443c99 639 /*
640 * remlocwin is the amount of local window that we think
641 * the remote end had available to it after it sent the
642 * last data packet or window adjust ack.
643 */
644 int remlocwin;
645 /*
646 * These store the list of window adjusts that haven't
647 * been acked.
648 */
649 struct winadj *winadj_head, *winadj_tail;
650 enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
5471d09a 651 } v2;
652 } v;
dacbd0e8 653 union {
32874aea 654 struct ssh_agent_channel {
655 unsigned char *message;
656 unsigned char msglen[4];
a03c9f9c 657 unsigned lensofar, totallen;
32874aea 658 } a;
659 struct ssh_x11_channel {
660 Socket s;
661 } x11;
d74d141c 662 struct ssh_pfd_channel {
663 Socket s;
664 } pfd;
dacbd0e8 665 } u;
666};
57476f6b 667
d74d141c 668/*
2e85c969 669 * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
670 * use this structure in different ways, reflecting SSH-2's
bc240b21 671 * altogether saner approach to port forwarding.
672 *
2e85c969 673 * In SSH-1, you arrange a remote forwarding by sending the server
bc240b21 674 * the remote port number, and the local destination host:port.
675 * When a connection comes in, the server sends you back that
676 * host:port pair, and you connect to it. This is a ready-made
677 * security hole if you're not on the ball: a malicious server
678 * could send you back _any_ host:port pair, so if you trustingly
679 * connect to the address it gives you then you've just opened the
680 * entire inside of your corporate network just by connecting
681 * through it to a dodgy SSH server. Hence, we must store a list of
682 * host:port pairs we _are_ trying to forward to, and reject a
683 * connection request from the server if it's not in the list.
684 *
2e85c969 685 * In SSH-2, each side of the connection minds its own business and
bc240b21 686 * doesn't send unnecessary information to the other. You arrange a
687 * remote forwarding by sending the server just the remote port
688 * number. When a connection comes in, the server tells you which
689 * of its ports was connected to; and _you_ have to remember what
690 * local host:port pair went with that port number.
691 *
2e85c969 692 * Hence, in SSH-1 this structure is indexed by destination
693 * host:port pair, whereas in SSH-2 it is indexed by source port.
d74d141c 694 */
fda2feb1 695struct ssh_portfwd; /* forward declaration */
696
d74d141c 697struct ssh_rportfwd {
bc240b21 698 unsigned sport, dport;
699 char dhost[256];
06fadff5 700 char *sportdesc;
fda2feb1 701 struct ssh_portfwd *pfrec;
d74d141c 702};
fda2feb1 703#define free_rportfwd(pf) ( \
704 ((pf) ? (sfree((pf)->sportdesc)) : (void)0 ), sfree(pf) )
705
706/*
707 * Separately to the rportfwd tree (which is for looking up port
708 * open requests from the server), a tree of _these_ structures is
709 * used to keep track of all the currently open port forwardings,
710 * so that we can reconfigure in mid-session if the user requests
711 * it.
712 */
713struct ssh_portfwd {
84328ddb 714 enum { DESTROY, KEEP, CREATE } status;
fda2feb1 715 int type;
716 unsigned sport, dport;
717 char *saddr, *daddr;
3fe92132 718 char *sserv, *dserv;
fda2feb1 719 struct ssh_rportfwd *remote;
05581745 720 int addressfamily;
fda2feb1 721 void *local;
722};
723#define free_portfwd(pf) ( \
3fe92132 724 ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
725 sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
d74d141c 726
57476f6b 727struct Packet {
dacd8872 728 long length; /* length of `data' actually used */
729 long forcepad; /* SSH-2: force padding to at least this length */
730 int type; /* only used for incoming packets */
731 unsigned long sequence; /* SSH-2 incoming sequence number */
732 unsigned char *data; /* allocated storage */
733 unsigned char *body; /* offset of payload within `data' */
734 long savedpos; /* temporary index into `data' (for strings) */
735 long maxlen; /* amount of storage allocated for `data' */
736 long encrypted_len; /* for SSH-2 total-size counting */
ff3187f6 737
738 /*
739 * State associated with packet logging
740 */
741 int logmode;
742 int nblanks;
743 struct logblank_t *blanks;
57476f6b 744};
745
1c1a7262 746static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
ff3187f6 747 struct Packet *pktin);
1c1a7262 748static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
ff3187f6 749 struct Packet *pktin);
b09eaa88 750static void ssh1_protocol_setup(Ssh ssh);
751static void ssh2_protocol_setup(Ssh ssh);
51470298 752static void ssh_size(void *handle, int width, int height);
753static void ssh_special(void *handle, Telnet_Special);
5471d09a 754static int ssh2_try_send(struct ssh_channel *c);
51470298 755static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
756static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
9fca3f8c 757static void ssh2_set_window(struct ssh_channel *c, int newwin);
51470298 758static int ssh_sendbuffer(void *handle);
ac934965 759static int ssh_do_close(Ssh ssh, int notify_exit);
ff3187f6 760static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
761static int ssh2_pkt_getbool(struct Packet *pkt);
762static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
9442dd57 763static void ssh2_timer(void *ctx, long now);
1c1a7262 764static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
9442dd57 765 struct Packet *pktin);
57476f6b 766
51470298 767struct rdpkt1_state_tag {
57476f6b 768 long len, pad, biglen, to_read;
769 unsigned long realcrc, gotcrc;
770 unsigned char *p;
771 int i;
772 int chunk;
ff3187f6 773 struct Packet *pktin;
51470298 774};
57476f6b 775
51470298 776struct rdpkt2_state_tag {
960e736a 777 long len, pad, payload, packetlen, maclen;
778 int i;
779 int cipherblk;
780 unsigned long incoming_sequence;
ff3187f6 781 struct Packet *pktin;
51470298 782};
783
b09eaa88 784typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
06fadff5 785typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
786
787struct queued_handler;
788struct queued_handler {
789 int msg1, msg2;
790 chandler_fn_t handler;
791 void *ctx;
792 struct queued_handler *next;
793};
b09eaa88 794
51470298 795struct ssh_tag {
796 const struct plug_function_table *fn;
797 /* the above field _must_ be first in the structure */
798
4320baf7 799 char *v_c, *v_s;
b672f405 800 void *exhash;
51470298 801
802 Socket s;
803
b9d7bcad 804 void *ldisc;
a8327734 805 void *logctx;
b9d7bcad 806
51470298 807 unsigned char session_key[32];
808 int v1_compressing;
809 int v1_remote_protoflags;
810 int v1_local_protoflags;
811 int agentfwd_enabled;
812 int X11_fwd_enabled;
813 int remote_bugs;
814 const struct ssh_cipher *cipher;
371e569c 815 void *v1_cipher_ctx;
0183b242 816 void *crcda_ctx;
51470298 817 const struct ssh2_cipher *cscipher, *sccipher;
371e569c 818 void *cs_cipher_ctx, *sc_cipher_ctx;
51470298 819 const struct ssh_mac *csmac, *scmac;
e0e1a00d 820 void *cs_mac_ctx, *sc_mac_ctx;
51470298 821 const struct ssh_compress *cscomp, *sccomp;
5366aed8 822 void *cs_comp_ctx, *sc_comp_ctx;
51470298 823 const struct ssh_kex *kex;
824 const struct ssh_signkey *hostkey;
754c0df9 825 unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
b672f405 826 int v2_session_id_len;
27cd7fc2 827 void *kex_ctx;
51470298 828
829 char *savedhost;
830 int savedport;
831 int send_ok;
832 int echoing, editing;
833
834 void *frontend;
835
db219738 836 int ospeed, ispeed; /* temporaries */
51470298 837 int term_width, term_height;
838
839 tree234 *channels; /* indexed by local id */
840 struct ssh_channel *mainchan; /* primary session channel */
feb02b4e 841 int ncmode; /* is primary channel direct-tcpip? */
51470298 842 int exitcode;
ac934965 843 int close_expected;
9e296bfa 844 int clean_exit;
51470298 845
fda2feb1 846 tree234 *rportfwds, *portfwds;
51470298 847
848 enum {
849 SSH_STATE_PREPACKET,
850 SSH_STATE_BEFORE_SIZE,
851 SSH_STATE_INTERMED,
852 SSH_STATE_SESSION,
853 SSH_STATE_CLOSED
854 } state;
855
856 int size_needed, eof_needed;
bc06669b 857 int sent_console_eof;
4a202fc6 858 int got_pty; /* affects EOF behaviour on main channel */
51470298 859
590f6a5f 860 struct Packet **queue;
861 int queuelen, queuesize;
862 int queueing;
51470298 863 unsigned char *deferred_send_data;
864 int deferred_len, deferred_size;
865
866 /*
867 * Gross hack: pscp will try to start SFTP but fall back to
868 * scp1 if that fails. This variable is the means by which
869 * scp.c can reach into the SSH code and find out which one it
870 * got.
871 */
872 int fallback_cmd;
873
6bbce591 874 bufchain banner; /* accumulates banners during do_ssh2_authconn */
51470298 875
acab36bc 876 Pkt_KCtx pkt_kctx;
877 Pkt_ACtx pkt_actx;
51470298 878
8def70c3 879 struct X11Display *x11disp;
302121de 880
51470298 881 int version;
ff68564b 882 int conn_throttle_count;
51470298 883 int overall_bufsize;
884 int throttled_all;
885 int v1_stdout_throttling;
a8756193 886 unsigned long v2_outgoing_sequence;
51470298 887
888 int ssh1_rdpkt_crstate;
889 int ssh2_rdpkt_crstate;
890 int do_ssh_init_crstate;
891 int ssh_gotdata_crstate;
51470298 892 int do_ssh1_login_crstate;
b09eaa88 893 int do_ssh1_connection_crstate;
51470298 894 int do_ssh2_transport_crstate;
895 int do_ssh2_authconn_crstate;
896
897 void *do_ssh_init_state;
898 void *do_ssh1_login_state;
899 void *do_ssh2_transport_state;
900 void *do_ssh2_authconn_state;
901
902 struct rdpkt1_state_tag rdpkt1_state;
903 struct rdpkt2_state_tag rdpkt2_state;
904
2e85c969 905 /* SSH-1 and SSH-2 use this for different things, but both use it */
b09eaa88 906 int protocol_initial_phase_done;
907
1c1a7262 908 void (*protocol) (Ssh ssh, void *vin, int inlen,
ff3187f6 909 struct Packet *pkt);
910 struct Packet *(*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
86916870 911
912 /*
4a693cfc 913 * We maintain our own copy of a Conf structure here. That way,
914 * when we're passed a new one for reconfiguration, we can check
915 * the differences and potentially reconfigure port forwardings
916 * etc in mid-session.
86916870 917 */
4a693cfc 918 Conf *conf;
919
920 /*
921 * Values cached out of conf so as to avoid the tree234 lookup
922 * cost every time they're used.
923 */
924 int logomitdata;
925
926 /*
927 * Dynamically allocated username string created during SSH
928 * login. Stored in here rather than in the coroutine state so
929 * that it'll be reliably freed if we shut down the SSH session
930 * at some unexpected moment.
931 */
932 char *username;
839f10db 933
934 /*
3d9449a1 935 * Used to transfer data back from async callbacks.
839f10db 936 */
937 void *agent_response;
938 int agent_response_len;
3d9449a1 939 int user_response;
940
941 /*
942 * The SSH connection can be set as `frozen', meaning we are
943 * not currently accepting incoming data from the network. This
944 * is slightly more serious than setting the _socket_ as
945 * frozen, because we may already have had data passed to us
946 * from the network which we need to delay processing until
947 * after the freeze is lifted, so we also need a bufchain to
948 * store that data.
949 */
950 int frozen;
951 bufchain queued_incoming_data;
b09eaa88 952
953 /*
954 * Dispatch table for packet types that we may have to deal
955 * with at any time.
956 */
957 handler_fn_t packet_dispatch[256];
39934deb 958
959 /*
06fadff5 960 * Queues of one-off handler functions for success/failure
961 * indications from a request.
962 */
963 struct queued_handler *qhead, *qtail;
964
965 /*
39934deb 966 * This module deals with sending keepalives.
967 */
968 Pinger pinger;
9442dd57 969
970 /*
971 * Track incoming and outgoing data sizes and time, for
972 * size-based rekeys.
973 */
974 unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
d57f70af 975 unsigned long max_data_size;
9442dd57 976 int kex_in_progress;
e6c1536e 977 long next_rekey, last_rekey;
e13bba36 978 char *deferred_rekey_reason; /* points to STATIC string; don't free */
42af6a67 979
980 /*
981 * Fully qualified host name, which we need if doing GSSAPI.
982 */
983 char *fullhostname;
1e00c92b 984
985#ifndef NO_GSSAPI
986 /*
987 * GSSAPI libraries for this session.
988 */
989 struct ssh_gss_liblist *gsslibs;
990#endif
51470298 991};
960e736a 992
382908ad 993#define logevent(s) logevent(ssh->frontend, s)
a8327734 994
995/* logevent, only printf-formatted. */
cbe2d68f 996static void logeventf(Ssh ssh, const char *fmt, ...)
a8327734 997{
998 va_list ap;
57356d63 999 char *buf;
a8327734 1000
1001 va_start(ap, fmt);
57356d63 1002 buf = dupvprintf(fmt, ap);
a8327734 1003 va_end(ap);
57356d63 1004 logevent(buf);
57356d63 1005 sfree(buf);
a8327734 1006}
1007
6b5cf8b4 1008#define bombout(msg) \
1009 do { \
1010 char *text = dupprintf msg; \
ac934965 1011 ssh_do_close(ssh, FALSE); \
6b5cf8b4 1012 logevent(text); \
1013 connection_fatal(ssh->frontend, "%s", text); \
1014 sfree(text); \
1015 } while (0)
a8327734 1016
9a10ecf4 1017/* Functions to leave bits out of the SSH packet log file. */
1018
ff3187f6 1019static void dont_log_password(Ssh ssh, struct Packet *pkt, int blanktype)
9a10ecf4 1020{
4a693cfc 1021 if (conf_get_int(ssh->conf, CONF_logomitpass))
ff3187f6 1022 pkt->logmode = blanktype;
9a10ecf4 1023}
1024
ff3187f6 1025static void dont_log_data(Ssh ssh, struct Packet *pkt, int blanktype)
9a10ecf4 1026{
4a693cfc 1027 if (ssh->logomitdata)
ff3187f6 1028 pkt->logmode = blanktype;
9a10ecf4 1029}
1030
ff3187f6 1031static void end_log_omission(Ssh ssh, struct Packet *pkt)
9a10ecf4 1032{
ff3187f6 1033 pkt->logmode = PKTLOG_EMIT;
9a10ecf4 1034}
1035
4a693cfc 1036/* Helper function for common bits of parsing ttymodes. */
1037static void parse_ttymodes(Ssh ssh,
c6ccd5c2 1038 void (*do_mode)(void *data, char *mode, char *val),
1039 void *data)
1040{
4a693cfc 1041 char *key, *val;
1042
1043 for (val = conf_get_str_strs(ssh->conf, CONF_ttymodes, NULL, &key);
1044 val != NULL;
1045 val = conf_get_str_strs(ssh->conf, CONF_ttymodes, key, &key)) {
1046 /*
1047 * val[0] is either 'V', indicating that an explicit value
1048 * follows it, or 'A' indicating that we should pass the
1049 * value through from the local environment via get_ttymode.
1050 */
1051 if (val[0] == 'A')
1052 val = get_ttymode(ssh->frontend, key);
c6ccd5c2 1053 else
4a693cfc 1054 val++; /* skip the 'V' */
c6ccd5c2 1055 if (val)
4a693cfc 1056 do_mode(data, key, val);
c6ccd5c2 1057 }
1058}
1059
32874aea 1060static int ssh_channelcmp(void *av, void *bv)
1061{
1062 struct ssh_channel *a = (struct ssh_channel *) av;
1063 struct ssh_channel *b = (struct ssh_channel *) bv;
1064 if (a->localid < b->localid)
1065 return -1;
1066 if (a->localid > b->localid)
1067 return +1;
dacbd0e8 1068 return 0;
1069}
32874aea 1070static int ssh_channelfind(void *av, void *bv)
1071{
1072 unsigned *a = (unsigned *) av;
1073 struct ssh_channel *b = (struct ssh_channel *) bv;
1074 if (*a < b->localid)
1075 return -1;
1076 if (*a > b->localid)
1077 return +1;
dacbd0e8 1078 return 0;
1079}
1080
bc240b21 1081static int ssh_rportcmp_ssh1(void *av, void *bv)
d74d141c 1082{
1083 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1084 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
1085 int i;
bc240b21 1086 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
d74d141c 1087 return i < 0 ? -1 : +1;
bc240b21 1088 if (a->dport > b->dport)
1089 return +1;
1090 if (a->dport < b->dport)
1091 return -1;
1092 return 0;
1093}
1094
1095static int ssh_rportcmp_ssh2(void *av, void *bv)
1096{
1097 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
1098 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
cdcbdf3b 1099
bc240b21 1100 if (a->sport > b->sport)
d74d141c 1101 return +1;
bc240b21 1102 if (a->sport < b->sport)
1103 return -1;
d74d141c 1104 return 0;
1105}
1106
fda2feb1 1107/*
1108 * Special form of strcmp which can cope with NULL inputs. NULL is
1109 * defined to sort before even the empty string.
1110 */
1111static int nullstrcmp(const char *a, const char *b)
1112{
1113 if (a == NULL && b == NULL)
1114 return 0;
1115 if (a == NULL)
1116 return -1;
1117 if (b == NULL)
1118 return +1;
1119 return strcmp(a, b);
1120}
1121
1122static int ssh_portcmp(void *av, void *bv)
1123{
1124 struct ssh_portfwd *a = (struct ssh_portfwd *) av;
1125 struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
1126 int i;
1127 if (a->type > b->type)
1128 return +1;
1129 if (a->type < b->type)
1130 return -1;
84328ddb 1131 if (a->addressfamily > b->addressfamily)
1132 return +1;
1133 if (a->addressfamily < b->addressfamily)
1134 return -1;
fda2feb1 1135 if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
1136 return i < 0 ? -1 : +1;
1137 if (a->sport > b->sport)
1138 return +1;
1139 if (a->sport < b->sport)
1140 return -1;
1141 if (a->type != 'D') {
1142 if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
1143 return i < 0 ? -1 : +1;
1144 if (a->dport > b->dport)
1145 return +1;
1146 if (a->dport < b->dport)
1147 return -1;
1148 }
1149 return 0;
1150}
1151
51470298 1152static int alloc_channel_id(Ssh ssh)
32874aea 1153{
260f3dec 1154 const unsigned CHANNEL_NUMBER_OFFSET = 256;
1155 unsigned low, high, mid;
d2371c81 1156 int tsize;
1157 struct ssh_channel *c;
1158
1159 /*
1160 * First-fit allocation of channel numbers: always pick the
1161 * lowest unused one. To do this, binary-search using the
1162 * counted B-tree to find the largest channel ID which is in a
1163 * contiguous sequence from the beginning. (Precisely
1164 * everything in that sequence must have ID equal to its tree
1165 * index plus CHANNEL_NUMBER_OFFSET.)
1166 */
51470298 1167 tsize = count234(ssh->channels);
d2371c81 1168
32874aea 1169 low = -1;
1170 high = tsize;
d2371c81 1171 while (high - low > 1) {
1172 mid = (high + low) / 2;
51470298 1173 c = index234(ssh->channels, mid);
d2371c81 1174 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
1175 low = mid; /* this one is fine */
1176 else
1177 high = mid; /* this one is past it */
1178 }
1179 /*
1180 * Now low points to either -1, or the tree index of the
1181 * largest ID in the initial sequence.
1182 */
1183 {
1184 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
51470298 1185 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
d2371c81 1186 }
1187 return low + 1 + CHANNEL_NUMBER_OFFSET;
1188}
1189
edd0cb8a 1190static void c_write_stderr(int trusted, const char *buf, int len)
1191{
1192 int i;
1193 for (i = 0; i < len; i++)
667deca9 1194 if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
edd0cb8a 1195 fputc(buf[i], stderr);
1196}
1197
9fab77dc 1198static void c_write(Ssh ssh, const char *buf, int len)
32874aea 1199{
edd0cb8a 1200 if (flags & FLAG_STDERR)
1201 c_write_stderr(1, buf, len);
1202 else
1203 from_backend(ssh->frontend, 1, buf, len);
3bdaf79d 1204}
1205
9fab77dc 1206static void c_write_untrusted(Ssh ssh, const char *buf, int len)
32874aea 1207{
edd0cb8a 1208 if (flags & FLAG_STDERR)
1209 c_write_stderr(0, buf, len);
1210 else
1211 from_backend_untrusted(ssh->frontend, buf, len);
a209e957 1212}
1213
9fab77dc 1214static void c_write_str(Ssh ssh, const char *buf)
32874aea 1215{
51470298 1216 c_write(ssh, buf, strlen(buf));
1408a877 1217}
1218
ff3187f6 1219static void ssh_free_packet(struct Packet *pkt)
1220{
1221 sfree(pkt->data);
1222 sfree(pkt);
1223}
1224static struct Packet *ssh_new_packet(void)
1225{
1226 struct Packet *pkt = snew(struct Packet);
1227
dacd8872 1228 pkt->body = pkt->data = NULL;
ff3187f6 1229 pkt->maxlen = 0;
1230 pkt->logmode = PKTLOG_EMIT;
1231 pkt->nblanks = 0;
1232 pkt->blanks = NULL;
1233
1234 return pkt;
1235}
1236
fb09bf1c 1237/*
1238 * Collect incoming data in the incoming packet buffer.
e5574168 1239 * Decipher and verify the packet when it is completely read.
1240 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
fb09bf1c 1241 * Update the *data and *datalen variables.
ff3187f6 1242 * Return a Packet structure when a packet is completed.
fb09bf1c 1243 */
ff3187f6 1244static struct Packet *ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
fb09bf1c 1245{
51470298 1246 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
374330e2 1247
51470298 1248 crBegin(ssh->ssh1_rdpkt_crstate);
374330e2 1249
ff3187f6 1250 st->pktin = ssh_new_packet();
1251
1252 st->pktin->type = 0;
1253 st->pktin->length = 0;
374330e2 1254
57476f6b 1255 for (st->i = st->len = 0; st->i < 4; st->i++) {
fb09bf1c 1256 while ((*datalen) == 0)
ff3187f6 1257 crReturn(NULL);
57476f6b 1258 st->len = (st->len << 8) + **data;
fb09bf1c 1259 (*data)++, (*datalen)--;
1260 }
374330e2 1261
57476f6b 1262 st->pad = 8 - (st->len % 8);
1263 st->biglen = st->len + st->pad;
ff3187f6 1264 st->pktin->length = st->len - 5;
fb09bf1c 1265
ae0500e5 1266 if (st->biglen < 0) {
1267 bombout(("Extremely large packet length from server suggests"
1268 " data stream corruption"));
ff3187f6 1269 ssh_free_packet(st->pktin);
1270 crStop(NULL);
ae0500e5 1271 }
1272
ff3187f6 1273 st->pktin->maxlen = st->biglen;
1274 st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
374330e2 1275
57476f6b 1276 st->to_read = st->biglen;
ff3187f6 1277 st->p = st->pktin->data;
57476f6b 1278 while (st->to_read > 0) {
32874aea 1279 st->chunk = st->to_read;
fb09bf1c 1280 while ((*datalen) == 0)
ff3187f6 1281 crReturn(NULL);
57476f6b 1282 if (st->chunk > (*datalen))
1283 st->chunk = (*datalen);
1284 memcpy(st->p, *data, st->chunk);
1285 *data += st->chunk;
1286 *datalen -= st->chunk;
1287 st->p += st->chunk;
1288 st->to_read -= st->chunk;
fb09bf1c 1289 }
374330e2 1290
ff3187f6 1291 if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
0183b242 1292 st->biglen, NULL)) {
6b5cf8b4 1293 bombout(("Network attack (CRC compensation) detected!"));
ff3187f6 1294 ssh_free_packet(st->pktin);
1295 crStop(NULL);
9a3a93a5 1296 }
1297
51470298 1298 if (ssh->cipher)
ff3187f6 1299 ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
374330e2 1300
ff3187f6 1301 st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
1302 st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
57476f6b 1303 if (st->gotcrc != st->realcrc) {
6b5cf8b4 1304 bombout(("Incorrect CRC received on packet"));
ff3187f6 1305 ssh_free_packet(st->pktin);
1306 crStop(NULL);
fb09bf1c 1307 }
572f871e 1308
ff3187f6 1309 st->pktin->body = st->pktin->data + st->pad + 1;
1310 st->pktin->savedpos = 0;
4ba9b64b 1311
51470298 1312 if (ssh->v1_compressing) {
4ba9b64b 1313 unsigned char *decompblk;
1314 int decomplen;
36b8d9bb 1315 if (!zlib_decompress_block(ssh->sc_comp_ctx,
ff3187f6 1316 st->pktin->body - 1, st->pktin->length + 1,
36b8d9bb 1317 &decompblk, &decomplen)) {
1318 bombout(("Zlib decompression encountered invalid data"));
ff3187f6 1319 ssh_free_packet(st->pktin);
1320 crStop(NULL);
36b8d9bb 1321 }
4ba9b64b 1322
ff3187f6 1323 if (st->pktin->maxlen < st->pad + decomplen) {
1324 st->pktin->maxlen = st->pad + decomplen;
1325 st->pktin->data = sresize(st->pktin->data,
1326 st->pktin->maxlen + APIEXTRA,
3d88e64d 1327 unsigned char);
ff3187f6 1328 st->pktin->body = st->pktin->data + st->pad + 1;
4ba9b64b 1329 }
1330
ff3187f6 1331 memcpy(st->pktin->body - 1, decompblk, decomplen);
dcbde236 1332 sfree(decompblk);
ff3187f6 1333 st->pktin->length = decomplen - 1;
4ba9b64b 1334 }
1335
ff3187f6 1336 st->pktin->type = st->pktin->body[-1];
00db133f 1337
9a10ecf4 1338 /*
1339 * Log incoming packet, possibly omitting sensitive fields.
1340 */
1341 if (ssh->logctx) {
1342 int nblanks = 0;
1343 struct logblank_t blank;
4a693cfc 1344 if (ssh->logomitdata) {
9a10ecf4 1345 int do_blank = FALSE, blank_prefix = 0;
1346 /* "Session data" packets - omit the data field */
ff3187f6 1347 if ((st->pktin->type == SSH1_SMSG_STDOUT_DATA) ||
1348 (st->pktin->type == SSH1_SMSG_STDERR_DATA)) {
9a10ecf4 1349 do_blank = TRUE; blank_prefix = 4;
a2724fba 1350 } else if (st->pktin->type == SSH1_MSG_CHANNEL_DATA) {
1351 do_blank = TRUE; blank_prefix = 8;
9a10ecf4 1352 }
1353 if (do_blank) {
1354 blank.offset = blank_prefix;
ff3187f6 1355 blank.len = st->pktin->length;
9a10ecf4 1356 blank.type = PKTLOG_OMIT;
1357 nblanks = 1;
1358 }
1359 }
a8327734 1360 log_packet(ssh->logctx,
ff3187f6 1361 PKT_INCOMING, st->pktin->type,
1362 ssh1_pkt_type(st->pktin->type),
1363 st->pktin->body, st->pktin->length,
0d13bfcd 1364 nblanks, &blank, NULL);
9a10ecf4 1365 }
00db133f 1366
ff3187f6 1367 crFinish(st->pktin);
fb09bf1c 1368}
1369
ff3187f6 1370static struct Packet *ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
e5574168 1371{
51470298 1372 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
e5574168 1373
51470298 1374 crBegin(ssh->ssh2_rdpkt_crstate);
e5574168 1375
ff3187f6 1376 st->pktin = ssh_new_packet();
1377
1378 st->pktin->type = 0;
1379 st->pktin->length = 0;
51470298 1380 if (ssh->sccipher)
1381 st->cipherblk = ssh->sccipher->blksize;
e5574168 1382 else
32874aea 1383 st->cipherblk = 8;
960e736a 1384 if (st->cipherblk < 8)
32874aea 1385 st->cipherblk = 8;
9916cc1e 1386 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
960e736a 1387
9916cc1e 1388 if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
1389 ssh->scmac) {
1390 /*
1391 * When dealing with a CBC-mode cipher, we want to avoid the
1392 * possibility of an attacker's tweaking the ciphertext stream
1393 * so as to cause us to feed the same block to the block
1394 * cipher more than once and thus leak information
1395 * (VU#958563). The way we do this is not to take any
1396 * decisions on the basis of anything we've decrypted until
1397 * we've verified it with a MAC. That includes the packet
1398 * length, so we just read data and check the MAC repeatedly,
1399 * and when the MAC passes, see if the length we've got is
1400 * plausible.
1401 */
1402
1403 /* May as well allocate the whole lot now. */
1404 st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
1405 unsigned char);
1406
1407 /* Read an amount corresponding to the MAC. */
1408 for (st->i = 0; st->i < st->maclen; st->i++) {
1409 while ((*datalen) == 0)
1410 crReturn(NULL);
1411 st->pktin->data[st->i] = *(*data)++;
1412 (*datalen)--;
1413 }
e5574168 1414
9916cc1e 1415 st->packetlen = 0;
1416 {
1417 unsigned char seq[4];
1418 ssh->scmac->start(ssh->sc_mac_ctx);
1419 PUT_32BIT(seq, st->incoming_sequence);
1420 ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
1421 }
4252c9cc 1422
9916cc1e 1423 for (;;) { /* Once around this loop per cipher block. */
1424 /* Read another cipher-block's worth, and tack it onto the end. */
1425 for (st->i = 0; st->i < st->cipherblk; st->i++) {
1426 while ((*datalen) == 0)
1427 crReturn(NULL);
1428 st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
1429 (*datalen)--;
1430 }
1431 /* Decrypt one more block (a little further back in the stream). */
1432 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1433 st->pktin->data + st->packetlen,
1434 st->cipherblk);
1435 /* Feed that block to the MAC. */
1436 ssh->scmac->bytes(ssh->sc_mac_ctx,
1437 st->pktin->data + st->packetlen, st->cipherblk);
1438 st->packetlen += st->cipherblk;
1439 /* See if that gives us a valid packet. */
1440 if (ssh->scmac->verresult(ssh->sc_mac_ctx,
1441 st->pktin->data + st->packetlen) &&
1442 (st->len = GET_32BIT(st->pktin->data)) + 4 == st->packetlen)
1443 break;
1444 if (st->packetlen >= OUR_V2_PACKETLIMIT) {
1445 bombout(("No valid incoming packet found"));
1446 ssh_free_packet(st->pktin);
1447 crStop(NULL);
1448 }
1449 }
1450 st->pktin->maxlen = st->packetlen + st->maclen;
1451 st->pktin->data = sresize(st->pktin->data,
1452 st->pktin->maxlen + APIEXTRA,
1453 unsigned char);
1454 } else {
1455 st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
1456
1457 /*
1458 * Acquire and decrypt the first block of the packet. This will
1459 * contain the length and padding details.
1460 */
1461 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
1462 while ((*datalen) == 0)
1463 crReturn(NULL);
1464 st->pktin->data[st->i] = *(*data)++;
1465 (*datalen)--;
1466 }
e5574168 1467
9916cc1e 1468 if (ssh->sccipher)
1469 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1470 st->pktin->data, st->cipherblk);
1471
1472 /*
1473 * Now get the length figure.
1474 */
1475 st->len = GET_32BIT(st->pktin->data);
1476
1477 /*
1478 * _Completely_ silly lengths should be stomped on before they
1479 * do us any more damage.
1480 */
1481 if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
1482 (st->len + 4) % st->cipherblk != 0) {
1483 bombout(("Incoming packet was garbled on decryption"));
1484 ssh_free_packet(st->pktin);
1485 crStop(NULL);
1486 }
e5574168 1487
9916cc1e 1488 /*
1489 * So now we can work out the total packet length.
1490 */
1491 st->packetlen = st->len + 4;
1492
1493 /*
1494 * Allocate memory for the rest of the packet.
1495 */
1496 st->pktin->maxlen = st->packetlen + st->maclen;
1497 st->pktin->data = sresize(st->pktin->data,
1498 st->pktin->maxlen + APIEXTRA,
1499 unsigned char);
1500
1501 /*
1502 * Read and decrypt the remainder of the packet.
1503 */
1504 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1505 st->i++) {
1506 while ((*datalen) == 0)
1507 crReturn(NULL);
1508 st->pktin->data[st->i] = *(*data)++;
1509 (*datalen)--;
1510 }
1511 /* Decrypt everything _except_ the MAC. */
1512 if (ssh->sccipher)
1513 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1514 st->pktin->data + st->cipherblk,
1515 st->packetlen - st->cipherblk);
1516
1517 /*
1518 * Check the MAC.
1519 */
1520 if (ssh->scmac
1521 && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
1522 st->len + 4, st->incoming_sequence)) {
1523 bombout(("Incorrect MAC received on packet"));
1524 ssh_free_packet(st->pktin);
1525 crStop(NULL);
1526 }
1527 }
1528 /* Get and sanity-check the amount of random padding. */
1529 st->pad = st->pktin->data[4];
1530 if (st->pad < 4 || st->len - st->pad < 1) {
1531 bombout(("Invalid padding length on received packet"));
ff3187f6 1532 ssh_free_packet(st->pktin);
1533 crStop(NULL);
717dc483 1534 }
717dc483 1535 /*
e5574168 1536 * This enables us to deduce the payload length.
1537 */
960e736a 1538 st->payload = st->len - st->pad - 1;
e5574168 1539
ff3187f6 1540 st->pktin->length = st->payload + 5;
9442dd57 1541 st->pktin->encrypted_len = st->packetlen;
1542
b09eaa88 1543 st->pktin->sequence = st->incoming_sequence++;
e5574168 1544
4ba9b64b 1545 /*
1546 * Decompress packet payload.
1547 */
1548 {
1549 unsigned char *newpayload;
1550 int newlen;
51470298 1551 if (ssh->sccomp &&
5366aed8 1552 ssh->sccomp->decompress(ssh->sc_comp_ctx,
ff3187f6 1553 st->pktin->data + 5, st->pktin->length - 5,
51470298 1554 &newpayload, &newlen)) {
ff3187f6 1555 if (st->pktin->maxlen < newlen + 5) {
1556 st->pktin->maxlen = newlen + 5;
1557 st->pktin->data = sresize(st->pktin->data,
1558 st->pktin->maxlen + APIEXTRA,
3d88e64d 1559 unsigned char);
4ba9b64b 1560 }
ff3187f6 1561 st->pktin->length = 5 + newlen;
1562 memcpy(st->pktin->data + 5, newpayload, newlen);
dcbde236 1563 sfree(newpayload);
4ba9b64b 1564 }
1565 }
1566
ff3187f6 1567 st->pktin->savedpos = 6;
1568 st->pktin->body = st->pktin->data;
1569 st->pktin->type = st->pktin->data[5];
e5574168 1570
9a10ecf4 1571 /*
1572 * Log incoming packet, possibly omitting sensitive fields.
1573 */
1574 if (ssh->logctx) {
1575 int nblanks = 0;
1576 struct logblank_t blank;
4a693cfc 1577 if (ssh->logomitdata) {
9a10ecf4 1578 int do_blank = FALSE, blank_prefix = 0;
1579 /* "Session data" packets - omit the data field */
ff3187f6 1580 if (st->pktin->type == SSH2_MSG_CHANNEL_DATA) {
9a10ecf4 1581 do_blank = TRUE; blank_prefix = 8;
a2724fba 1582 } else if (st->pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
1583 do_blank = TRUE; blank_prefix = 12;
9a10ecf4 1584 }
1585 if (do_blank) {
1586 blank.offset = blank_prefix;
ff3187f6 1587 blank.len = (st->pktin->length-6) - blank_prefix;
9a10ecf4 1588 blank.type = PKTLOG_OMIT;
1589 nblanks = 1;
1590 }
1591 }
ff3187f6 1592 log_packet(ssh->logctx, PKT_INCOMING, st->pktin->type,
acab36bc 1593 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
1594 st->pktin->type),
ff3187f6 1595 st->pktin->data+6, st->pktin->length-6,
0d13bfcd 1596 nblanks, &blank, &st->pktin->sequence);
9a10ecf4 1597 }
00db133f 1598
ff3187f6 1599 crFinish(st->pktin);
e5574168 1600}
1601
dacd8872 1602static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
32874aea 1603{
dacd8872 1604 int pad, biglen, i, pktoffs;
374330e2 1605 unsigned long crc;
fd7a4aad 1606#ifdef __SC__
1607 /*
1608 * XXX various versions of SC (including 8.8.4) screw up the
1609 * register allocation in this function and use the same register
1610 * (D6) for len and as a temporary, with predictable results. The
1611 * following sledgehammer prevents this.
1612 */
1613 volatile
1614#endif
1615 int len;
374330e2 1616
a8327734 1617 if (ssh->logctx)
dacd8872 1618 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
1619 ssh1_pkt_type(pkt->data[12]),
1620 pkt->body, pkt->length - (pkt->body - pkt->data),
0d13bfcd 1621 pkt->nblanks, pkt->blanks, NULL);
ff3187f6 1622 sfree(pkt->blanks); pkt->blanks = NULL;
1623 pkt->nblanks = 0;
00db133f 1624
51470298 1625 if (ssh->v1_compressing) {
4ba9b64b 1626 unsigned char *compblk;
1627 int complen;
5366aed8 1628 zlib_compress_block(ssh->cs_comp_ctx,
dacd8872 1629 pkt->data + 12, pkt->length - 12,
4ba9b64b 1630 &compblk, &complen);
48406e6b 1631 ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
dacd8872 1632 memcpy(pkt->data + 12, compblk, complen);
dcbde236 1633 sfree(compblk);
dacd8872 1634 pkt->length = complen + 12;
4ba9b64b 1635 }
1636
dacd8872 1637 ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
1638 pkt->length += 4;
1639 len = pkt->length - 4 - 8; /* len(type+data+CRC) */
32874aea 1640 pad = 8 - (len % 8);
dacd8872 1641 pktoffs = 8 - pad;
1642 biglen = len + pad; /* len(padding+type+data+CRC) */
374330e2 1643
dacd8872 1644 for (i = pktoffs; i < 4+8; i++)
1645 pkt->data[i] = random_byte();
1646 crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
1647 PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
1648 PUT_32BIT(pkt->data + pktoffs, len);
374330e2 1649
51470298 1650 if (ssh->cipher)
dacd8872 1651 ssh->cipher->encrypt(ssh->v1_cipher_ctx,
1652 pkt->data + pktoffs + 4, biglen);
374330e2 1653
dacd8872 1654 if (offset_p) *offset_p = pktoffs;
1655 return biglen + 4; /* len(length+padding+type+data+CRC) */
39065bed 1656}
1657
bf8a49a1 1658static int s_write(Ssh ssh, void *data, int len)
1659{
ff05dfef 1660 if (ssh->logctx)
0d13bfcd 1661 log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
1662 0, NULL, NULL);
bf8a49a1 1663 return sk_write(ssh->s, (char *)data, len);
1664}
1665
ff3187f6 1666static void s_wrpkt(Ssh ssh, struct Packet *pkt)
32874aea 1667{
dacd8872 1668 int len, backlog, offset;
1669 len = s_wrpkt_prepare(ssh, pkt, &offset);
bf8a49a1 1670 backlog = s_write(ssh, pkt->data + offset, len);
5471d09a 1671 if (backlog > SSH_MAX_BACKLOG)
51470298 1672 ssh_throttle_all(ssh, 1, backlog);
dacd8872 1673 ssh_free_packet(pkt);
39065bed 1674}
1675
ff3187f6 1676static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
32874aea 1677{
dacd8872 1678 int len, offset;
1679 len = s_wrpkt_prepare(ssh, pkt, &offset);
51470298 1680 if (ssh->deferred_len + len > ssh->deferred_size) {
1681 ssh->deferred_size = ssh->deferred_len + len + 128;
3d88e64d 1682 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1683 ssh->deferred_size,
1684 unsigned char);
39065bed 1685 }
dacd8872 1686 memcpy(ssh->deferred_send_data + ssh->deferred_len,
1687 pkt->data + offset, len);
51470298 1688 ssh->deferred_len += len;
dacd8872 1689 ssh_free_packet(pkt);
374330e2 1690}
1691
fb09bf1c 1692/*
dacd8872 1693 * Construct a SSH-1 packet with the specified contents.
1694 * (This all-at-once interface used to be the only one, but now SSH-1
1695 * packets can also be constructed incrementally.)
fb09bf1c 1696 */
dacd8872 1697static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
fb09bf1c 1698{
dacd8872 1699 int argtype;
7cca0d81 1700 Bignum bn;
ff3187f6 1701 struct Packet *pkt;
fb09bf1c 1702
dacd8872 1703 pkt = ssh1_pkt_init(pkttype);
fb09bf1c 1704
dacd8872 1705 while ((argtype = va_arg(ap, int)) != PKT_END) {
1706 unsigned char *argp, argchar;
8a9977e5 1707 char *sargp;
dacd8872 1708 unsigned long argint;
1709 int arglen;
fb09bf1c 1710 switch (argtype) {
9a10ecf4 1711 /* Actual fields in the packet */
fb09bf1c 1712 case PKT_INT:
dacd8872 1713 argint = va_arg(ap, int);
1714 ssh_pkt_adduint32(pkt, argint);
fb09bf1c 1715 break;
1716 case PKT_CHAR:
dacd8872 1717 argchar = (unsigned char) va_arg(ap, int);
1718 ssh_pkt_addbyte(pkt, argchar);
fb09bf1c 1719 break;
1720 case PKT_DATA:
dacd8872 1721 argp = va_arg(ap, unsigned char *);
1722 arglen = va_arg(ap, int);
1723 ssh_pkt_adddata(pkt, argp, arglen);
fb09bf1c 1724 break;
1725 case PKT_STR:
8a9977e5 1726 sargp = va_arg(ap, char *);
1727 ssh_pkt_addstring(pkt, sargp);
fb09bf1c 1728 break;
7cca0d81 1729 case PKT_BIGNUM:
dacd8872 1730 bn = va_arg(ap, Bignum);
1731 ssh1_pkt_addmp(pkt, bn);
9a10ecf4 1732 break;
1733 /* Tokens for modifications to packet logging */
1734 case PKTT_PASSWORD:
ff3187f6 1735 dont_log_password(ssh, pkt, PKTLOG_BLANK);
9a10ecf4 1736 break;
1737 case PKTT_DATA:
ff3187f6 1738 dont_log_data(ssh, pkt, PKTLOG_OMIT);
7cca0d81 1739 break;
9a10ecf4 1740 case PKTT_OTHER:
ff3187f6 1741 end_log_omission(ssh, pkt);
9a10ecf4 1742 break;
1743 }
fb09bf1c 1744 }
ff3187f6 1745
1746 return pkt;
39065bed 1747}
fb09bf1c 1748
51470298 1749static void send_packet(Ssh ssh, int pkttype, ...)
32874aea 1750{
ff3187f6 1751 struct Packet *pkt;
dacd8872 1752 va_list ap;
1753 va_start(ap, pkttype);
1754 pkt = construct_packet(ssh, pkttype, ap);
1755 va_end(ap);
ff3187f6 1756 s_wrpkt(ssh, pkt);
fb09bf1c 1757}
1758
51470298 1759static void defer_packet(Ssh ssh, int pkttype, ...)
32874aea 1760{
ff3187f6 1761 struct Packet *pkt;
dacd8872 1762 va_list ap;
1763 va_start(ap, pkttype);
1764 pkt = construct_packet(ssh, pkttype, ap);
1765 va_end(ap);
ff3187f6 1766 s_wrpkt_defer(ssh, pkt);
39065bed 1767}
1768
32874aea 1769static int ssh_versioncmp(char *a, char *b)
1770{
9697bfd2 1771 char *ae, *be;
1772 unsigned long av, bv;
1773
43aa02a7 1774 av = strtoul(a, &ae, 10);
1775 bv = strtoul(b, &be, 10);
32874aea 1776 if (av != bv)
1777 return (av < bv ? -1 : +1);
1778 if (*ae == '.')
1779 ae++;
1780 if (*be == '.')
1781 be++;
43aa02a7 1782 av = strtoul(ae, &ae, 10);
1783 bv = strtoul(be, &be, 10);
32874aea 1784 if (av != bv)
1785 return (av < bv ? -1 : +1);
9697bfd2 1786 return 0;
1787}
1788
e5574168 1789/*
a92dd380 1790 * Utility routines for putting an SSH-protocol `string' and
b672f405 1791 * `uint32' into a hash state.
e5574168 1792 */
b672f405 1793static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
32874aea 1794{
e5574168 1795 unsigned char lenblk[4];
e5574168 1796 PUT_32BIT(lenblk, len);
b672f405 1797 h->bytes(s, lenblk, 4);
1798 h->bytes(s, str, len);
e5574168 1799}
1800
b672f405 1801static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
32874aea 1802{
a92dd380 1803 unsigned char intblk[4];
1804 PUT_32BIT(intblk, i);
b672f405 1805 h->bytes(s, intblk, 4);
a92dd380 1806}
1807
7cca0d81 1808/*
dacd8872 1809 * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
7cca0d81 1810 */
dacd8872 1811static void ssh_pkt_ensure(struct Packet *pkt, int length)
32874aea 1812{
ff3187f6 1813 if (pkt->maxlen < length) {
dacd8872 1814 unsigned char *body = pkt->body;
3d71de0b 1815 int offset = body ? body - pkt->data : 0;
ff3187f6 1816 pkt->maxlen = length + 256;
1817 pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
dacd8872 1818 if (body) pkt->body = pkt->data + offset;
7cca0d81 1819 }
783415f8 1820}
dacd8872 1821static void ssh_pkt_adddata(struct Packet *pkt, void *data, int len)
32874aea 1822{
ff3187f6 1823 if (pkt->logmode != PKTLOG_EMIT) {
1824 pkt->nblanks++;
1825 pkt->blanks = sresize(pkt->blanks, pkt->nblanks, struct logblank_t);
dacd8872 1826 assert(pkt->body);
1827 pkt->blanks[pkt->nblanks-1].offset = pkt->length -
1828 (pkt->body - pkt->data);
ff3187f6 1829 pkt->blanks[pkt->nblanks-1].len = len;
1830 pkt->blanks[pkt->nblanks-1].type = pkt->logmode;
1831 }
1832 pkt->length += len;
dacd8872 1833 ssh_pkt_ensure(pkt, pkt->length);
ff3187f6 1834 memcpy(pkt->data + pkt->length - len, data, len);
7cca0d81 1835}
dacd8872 1836static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
32874aea 1837{
dacd8872 1838 ssh_pkt_adddata(pkt, &byte, 1);
7cca0d81 1839}
ff3187f6 1840static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
32874aea 1841{
dacd8872 1842 ssh_pkt_adddata(pkt, &value, 1);
7cca0d81 1843}
dacd8872 1844static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
32874aea 1845{
7cca0d81 1846 unsigned char x[4];
1847 PUT_32BIT(x, value);
dacd8872 1848 ssh_pkt_adddata(pkt, x, 4);
7cca0d81 1849}
dacd8872 1850static void ssh_pkt_addstring_start(struct Packet *pkt)
32874aea 1851{
dacd8872 1852 ssh_pkt_adduint32(pkt, 0);
ff3187f6 1853 pkt->savedpos = pkt->length;
7cca0d81 1854}
dacd8872 1855static void ssh_pkt_addstring_str(struct Packet *pkt, char *data)
32874aea 1856{
dacd8872 1857 ssh_pkt_adddata(pkt, data, strlen(data));
ff3187f6 1858 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
7cca0d81 1859}
dacd8872 1860static void ssh_pkt_addstring_data(struct Packet *pkt, char *data, int len)
32874aea 1861{
dacd8872 1862 ssh_pkt_adddata(pkt, data, len);
ff3187f6 1863 PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
7cca0d81 1864}
dacd8872 1865static void ssh_pkt_addstring(struct Packet *pkt, char *data)
1866{
1867 ssh_pkt_addstring_start(pkt);
1868 ssh_pkt_addstring_str(pkt, data);
1869}
1870static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
32874aea 1871{
dacd8872 1872 int len = ssh1_bignum_length(b);
8a9977e5 1873 unsigned char *data = snewn(len, unsigned char);
dacd8872 1874 (void) ssh1_write_bignum(data, b);
1875 ssh_pkt_adddata(pkt, data, len);
1876 sfree(data);
7cca0d81 1877}
d8baa528 1878static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
32874aea 1879{
7cca0d81 1880 unsigned char *p;
32874aea 1881 int i, n = (bignum_bitcount(b) + 7) / 8;
3d88e64d 1882 p = snewn(n + 1, unsigned char);
7cca0d81 1883 p[0] = 0;
3709bfe9 1884 for (i = 1; i <= n; i++)
32874aea 1885 p[i] = bignum_byte(b, n - i);
7cca0d81 1886 i = 0;
32874aea 1887 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1888 i++;
1889 memmove(p, p + i, n + 1 - i);
1890 *len = n + 1 - i;
7cca0d81 1891 return p;
1892}
ff3187f6 1893static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
32874aea 1894{
7cca0d81 1895 unsigned char *p;
1896 int len;
1897 p = ssh2_mpint_fmt(b, &len);
dacd8872 1898 ssh_pkt_addstring_start(pkt);
1899 ssh_pkt_addstring_data(pkt, (char *)p, len);
dcbde236 1900 sfree(p);
7cca0d81 1901}
b185170a 1902
dacd8872 1903static struct Packet *ssh1_pkt_init(int pkt_type)
1904{
1905 struct Packet *pkt = ssh_new_packet();
1906 pkt->length = 4 + 8; /* space for length + max padding */
1907 ssh_pkt_addbyte(pkt, pkt_type);
1908 pkt->body = pkt->data + pkt->length;
1909 return pkt;
1910}
1911
1912/* For legacy code (SSH-1 and -2 packet construction used to be separate) */
1913#define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
1914#define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
1915#define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
1916#define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
1917#define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
1918#define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
1919#define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
1920#define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
1921
1922static struct Packet *ssh2_pkt_init(int pkt_type)
1923{
1924 struct Packet *pkt = ssh_new_packet();
3d71de0b 1925 pkt->length = 5; /* space for packet length + padding length */
dacd8872 1926 pkt->forcepad = 0;
1927 ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
3d71de0b 1928 pkt->body = pkt->data + pkt->length; /* after packet type */
dacd8872 1929 return pkt;
1930}
1931
b185170a 1932/*
2e85c969 1933 * Construct an SSH-2 final-form packet: compress it, encrypt it,
b185170a 1934 * put the MAC on it. Final packet, ready to be sent, is stored in
ff3187f6 1935 * pkt->data. Total length is returned.
b185170a 1936 */
ff3187f6 1937static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
32874aea 1938{
7cca0d81 1939 int cipherblk, maclen, padding, i;
7cca0d81 1940
a8327734 1941 if (ssh->logctx)
ff3187f6 1942 log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
acab36bc 1943 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
dacd8872 1944 pkt->body, pkt->length - (pkt->body - pkt->data),
0d13bfcd 1945 pkt->nblanks, pkt->blanks, &ssh->v2_outgoing_sequence);
ff3187f6 1946 sfree(pkt->blanks); pkt->blanks = NULL;
1947 pkt->nblanks = 0;
00db133f 1948
7cca0d81 1949 /*
4ba9b64b 1950 * Compress packet payload.
1951 */
4ba9b64b 1952 {
1953 unsigned char *newpayload;
1954 int newlen;
51470298 1955 if (ssh->cscomp &&
ff3187f6 1956 ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
1957 pkt->length - 5,
51470298 1958 &newpayload, &newlen)) {
ff3187f6 1959 pkt->length = 5;
1960 ssh2_pkt_adddata(pkt, newpayload, newlen);
dcbde236 1961 sfree(newpayload);
4ba9b64b 1962 }
1963 }
1964
1965 /*
7cca0d81 1966 * Add padding. At least four bytes, and must also bring total
1967 * length (minus MAC) up to a multiple of the block size.
95d2d262 1968 * If pkt->forcepad is set, make sure the packet is at least that size
1969 * after padding.
7cca0d81 1970 */
51470298 1971 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
32874aea 1972 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
7cca0d81 1973 padding = 4;
95d2d262 1974 if (pkt->length + padding < pkt->forcepad)
1975 padding = pkt->forcepad - pkt->length;
32874aea 1976 padding +=
ff3187f6 1977 (cipherblk - (pkt->length + padding) % cipherblk) % cipherblk;
95d2d262 1978 assert(padding <= 255);
51470298 1979 maclen = ssh->csmac ? ssh->csmac->len : 0;
ff3187f6 1980 ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
1981 pkt->data[4] = padding;
7cca0d81 1982 for (i = 0; i < padding; i++)
ff3187f6 1983 pkt->data[pkt->length + i] = random_byte();
1984 PUT_32BIT(pkt->data, pkt->length + padding - 4);
51470298 1985 if (ssh->csmac)
ff3187f6 1986 ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
1987 pkt->length + padding,
51470298 1988 ssh->v2_outgoing_sequence);
1989 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1990
1991 if (ssh->cscipher)
371e569c 1992 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
ff3187f6 1993 pkt->data, pkt->length + padding);
51470298 1994
9442dd57 1995 pkt->encrypted_len = pkt->length + padding;
1996
ff3187f6 1997 /* Ready-to-send packet starts at pkt->data. We return length. */
1998 return pkt->length + padding + maclen;
b185170a 1999}
2000
2001/*
590f6a5f 2002 * Routines called from the main SSH code to send packets. There
2003 * are quite a few of these, because we have two separate
2004 * mechanisms for delaying the sending of packets:
2005 *
2006 * - In order to send an IGNORE message and a password message in
2007 * a single fixed-length blob, we require the ability to
2008 * concatenate the encrypted forms of those two packets _into_ a
2009 * single blob and then pass it to our <network.h> transport
2010 * layer in one go. Hence, there's a deferment mechanism which
2011 * works after packet encryption.
2012 *
2013 * - In order to avoid sending any connection-layer messages
2014 * during repeat key exchange, we have to queue up any such
2015 * outgoing messages _before_ they are encrypted (and in
2016 * particular before they're allocated sequence numbers), and
2017 * then send them once we've finished.
2018 *
2019 * I call these mechanisms `defer' and `queue' respectively, so as
2020 * to distinguish them reasonably easily.
2021 *
2022 * The functions send_noqueue() and defer_noqueue() free the packet
2023 * structure they are passed. Every outgoing packet goes through
2024 * precisely one of these functions in its life; packets passed to
2025 * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
2026 * these or get queued, and then when the queue is later emptied
2027 * the packets are all passed to defer_noqueue().
97ab28d7 2028 *
2029 * When using a CBC-mode cipher, it's necessary to ensure that an
2030 * attacker can't provide data to be encrypted using an IV that they
2031 * know. We ensure this by prefixing each packet that might contain
2032 * user data with an SSH_MSG_IGNORE. This is done using the deferral
2033 * mechanism, so in this case send_noqueue() ends up redirecting to
2034 * defer_noqueue(). If you don't like this inefficiency, don't use
2035 * CBC.
b185170a 2036 */
590f6a5f 2037
97ab28d7 2038static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
2039static void ssh_pkt_defersend(Ssh);
2040
590f6a5f 2041/*
2e85c969 2042 * Send an SSH-2 packet immediately, without queuing or deferring.
590f6a5f 2043 */
2044static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
32874aea 2045{
5471d09a 2046 int len;
2047 int backlog;
97ab28d7 2048 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
2049 /* We need to send two packets, so use the deferral mechanism. */
2050 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
2051 ssh_pkt_defersend(ssh);
2052 return;
2053 }
ff3187f6 2054 len = ssh2_pkt_construct(ssh, pkt);
bf8a49a1 2055 backlog = s_write(ssh, pkt->data, len);
5471d09a 2056 if (backlog > SSH_MAX_BACKLOG)
51470298 2057 ssh_throttle_all(ssh, 1, backlog);
9442dd57 2058
2059 ssh->outgoing_data_size += pkt->encrypted_len;
2060 if (!ssh->kex_in_progress &&
d57f70af 2061 ssh->max_data_size != 0 &&
2062 ssh->outgoing_data_size > ssh->max_data_size)
f382c87d 2063 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
9442dd57 2064
ff3187f6 2065 ssh_free_packet(pkt);
b185170a 2066}
2067
2068/*
2e85c969 2069 * Defer an SSH-2 packet.
b185170a 2070 */
97ab28d7 2071static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
32874aea 2072{
97ab28d7 2073 int len;
2074 if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
cf6ddb95 2075 ssh->deferred_len == 0 && !noignore &&
2076 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
97ab28d7 2077 /*
2078 * Interpose an SSH_MSG_IGNORE to ensure that user data don't
2079 * get encrypted with a known IV.
2080 */
2081 struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
27311cc7 2082 ssh2_pkt_addstring_start(ipkt);
97ab28d7 2083 ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
2084 }
2085 len = ssh2_pkt_construct(ssh, pkt);
51470298 2086 if (ssh->deferred_len + len > ssh->deferred_size) {
2087 ssh->deferred_size = ssh->deferred_len + len + 128;
3d88e64d 2088 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
2089 ssh->deferred_size,
2090 unsigned char);
b185170a 2091 }
ff3187f6 2092 memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->data, len);
51470298 2093 ssh->deferred_len += len;
9442dd57 2094 ssh->deferred_data_size += pkt->encrypted_len;
ff3187f6 2095 ssh_free_packet(pkt);
b185170a 2096}
2097
2098/*
2e85c969 2099 * Queue an SSH-2 packet.
590f6a5f 2100 */
2101static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
2102{
2103 assert(ssh->queueing);
2104
2105 if (ssh->queuelen >= ssh->queuesize) {
2106 ssh->queuesize = ssh->queuelen + 32;
2107 ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
2108 }
2109
2110 ssh->queue[ssh->queuelen++] = pkt;
2111}
2112
2113/*
2114 * Either queue or send a packet, depending on whether queueing is
2115 * set.
2116 */
2117static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
2118{
2119 if (ssh->queueing)
2120 ssh2_pkt_queue(ssh, pkt);
2121 else
2122 ssh2_pkt_send_noqueue(ssh, pkt);
2123}
2124
2125/*
2126 * Either queue or defer a packet, depending on whether queueing is
2127 * set.
2128 */
2129static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
2130{
2131 if (ssh->queueing)
2132 ssh2_pkt_queue(ssh, pkt);
2133 else
97ab28d7 2134 ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
590f6a5f 2135}
2136
2137/*
b185170a 2138 * Send the whole deferred data block constructed by
2e85c969 2139 * ssh2_pkt_defer() or SSH-1's defer_packet().
590f6a5f 2140 *
2141 * The expected use of the defer mechanism is that you call
2142 * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
2143 * not currently queueing, this simply sets up deferred_send_data
2144 * and then sends it. If we _are_ currently queueing, the calls to
2145 * ssh2_pkt_defer() put the deferred packets on to the queue
2146 * instead, and therefore ssh_pkt_defersend() has no deferred data
2147 * to send. Hence, there's no need to make it conditional on
2148 * ssh->queueing.
b185170a 2149 */
51470298 2150static void ssh_pkt_defersend(Ssh ssh)
32874aea 2151{
5471d09a 2152 int backlog;
bf8a49a1 2153 backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
51470298 2154 ssh->deferred_len = ssh->deferred_size = 0;
2155 sfree(ssh->deferred_send_data);
2156 ssh->deferred_send_data = NULL;
5471d09a 2157 if (backlog > SSH_MAX_BACKLOG)
51470298 2158 ssh_throttle_all(ssh, 1, backlog);
9442dd57 2159
2160 ssh->outgoing_data_size += ssh->deferred_data_size;
2161 if (!ssh->kex_in_progress &&
d57f70af 2162 ssh->max_data_size != 0 &&
2163 ssh->outgoing_data_size > ssh->max_data_size)
f382c87d 2164 do_ssh2_transport(ssh, "too much data sent", -1, NULL);
9442dd57 2165 ssh->deferred_data_size = 0;
7cca0d81 2166}
2167
590f6a5f 2168/*
18524056 2169 * Send a packet whose length needs to be disguised (typically
2170 * passwords or keyboard-interactive responses).
2171 */
2172static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
2173 int padsize)
2174{
2175#if 0
2176 if (0) {
2177 /*
2178 * The simplest way to do this is to adjust the
2179 * variable-length padding field in the outgoing packet.
2180 *
2181 * Currently compiled out, because some Cisco SSH servers
2182 * don't like excessively padded packets (bah, why's it
2183 * always Cisco?)
2184 */
2185 pkt->forcepad = padsize;
2186 ssh2_pkt_send(ssh, pkt);
2187 } else
2188#endif
2189 {
2190 /*
2191 * If we can't do that, however, an alternative approach is
2192 * to use the pkt_defer mechanism to bundle the packet
2193 * tightly together with an SSH_MSG_IGNORE such that their
2194 * combined length is a constant. So first we construct the
2195 * final form of this packet and defer its sending.
2196 */
2197 ssh2_pkt_defer(ssh, pkt);
2198
2199 /*
2200 * Now construct an SSH_MSG_IGNORE which includes a string
2201 * that's an exact multiple of the cipher block size. (If
2202 * the cipher is NULL so that the block size is
2203 * unavailable, we don't do this trick at all, because we
2204 * gain nothing by it.)
2205 */
cf6ddb95 2206 if (ssh->cscipher &&
2207 !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
18524056 2208 int stringlen, i;
2209
2210 stringlen = (256 - ssh->deferred_len);
2211 stringlen += ssh->cscipher->blksize - 1;
2212 stringlen -= (stringlen % ssh->cscipher->blksize);
2213 if (ssh->cscomp) {
2214 /*
2215 * Temporarily disable actual compression, so we
2216 * can guarantee to get this string exactly the
2217 * length we want it. The compression-disabling
2218 * routine should return an integer indicating how
2219 * many bytes we should adjust our string length
2220 * by.
2221 */
2222 stringlen -=
2223 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
2224 }
2225 pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
2226 ssh2_pkt_addstring_start(pkt);
2227 for (i = 0; i < stringlen; i++) {
2228 char c = (char) random_byte();
2229 ssh2_pkt_addstring_data(pkt, &c, 1);
2230 }
2231 ssh2_pkt_defer(ssh, pkt);
2232 }
2233 ssh_pkt_defersend(ssh);
2234 }
2235}
2236
2237/*
2e85c969 2238 * Send all queued SSH-2 packets. We send them by means of
590f6a5f 2239 * ssh2_pkt_defer_noqueue(), in case they included a pair of
2240 * packets that needed to be lumped together.
2241 */
2242static void ssh2_pkt_queuesend(Ssh ssh)
2243{
2244 int i;
2245
2246 assert(!ssh->queueing);
2247
2248 for (i = 0; i < ssh->queuelen; i++)
97ab28d7 2249 ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
590f6a5f 2250 ssh->queuelen = 0;
2251
2252 ssh_pkt_defersend(ssh);
2253}
2254
7cca0d81 2255#if 0
32874aea 2256void bndebug(char *string, Bignum b)
2257{
7cca0d81 2258 unsigned char *p;
2259 int i, len;
2260 p = ssh2_mpint_fmt(b, &len);
2261 debug(("%s", string));
2262 for (i = 0; i < len; i++)
32874aea 2263 debug((" %02x", p[i]));
765c4200 2264 debug(("\n"));
dcbde236 2265 sfree(p);
7cca0d81 2266}
2267#endif
2268
b672f405 2269static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
32874aea 2270{
7cca0d81 2271 unsigned char *p;
2272 int len;
2273 p = ssh2_mpint_fmt(b, &len);
b672f405 2274 hash_string(h, s, p, len);
dcbde236 2275 sfree(p);
7cca0d81 2276}
2277
2278/*
2e85c969 2279 * Packet decode functions for both SSH-1 and SSH-2.
7cca0d81 2280 */
ff3187f6 2281static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
32874aea 2282{
7cca0d81 2283 unsigned long value;
ff3187f6 2284 if (pkt->length - pkt->savedpos < 4)
32874aea 2285 return 0; /* arrgh, no way to decline (FIXME?) */
ff3187f6 2286 value = GET_32BIT(pkt->body + pkt->savedpos);
2287 pkt->savedpos += 4;
7cca0d81 2288 return value;
2289}
ff3187f6 2290static int ssh2_pkt_getbool(struct Packet *pkt)
32874aea 2291{
65a22376 2292 unsigned long value;
ff3187f6 2293 if (pkt->length - pkt->savedpos < 1)
32874aea 2294 return 0; /* arrgh, no way to decline (FIXME?) */
ff3187f6 2295 value = pkt->body[pkt->savedpos] != 0;
2296 pkt->savedpos++;
65a22376 2297 return value;
2298}
ff3187f6 2299static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
32874aea 2300{
57356d63 2301 int len;
7cca0d81 2302 *p = NULL;
45068b27 2303 *length = 0;
ff3187f6 2304 if (pkt->length - pkt->savedpos < 4)
32874aea 2305 return;
ff3187f6 2306 len = GET_32BIT(pkt->body + pkt->savedpos);
57356d63 2307 if (len < 0)
2308 return;
2309 *length = len;
ff3187f6 2310 pkt->savedpos += 4;
2311 if (pkt->length - pkt->savedpos < *length)
32874aea 2312 return;
ff3187f6 2313 *p = (char *)(pkt->body + pkt->savedpos);
2314 pkt->savedpos += *length;
7cca0d81 2315}
ff3187f6 2316static void *ssh_pkt_getdata(struct Packet *pkt, int length)
0016d70b 2317{
ff3187f6 2318 if (pkt->length - pkt->savedpos < length)
0016d70b 2319 return NULL;
ff3187f6 2320 pkt->savedpos += length;
2321 return pkt->body + (pkt->savedpos - length);
0016d70b 2322}
ff3187f6 2323static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
0016d70b 2324 unsigned char **keystr)
2325{
2326 int j;
2327
ff3187f6 2328 j = makekey(pkt->body + pkt->savedpos,
2329 pkt->length - pkt->savedpos,
0016d70b 2330 key, keystr, 0);
2331
2332 if (j < 0)
2333 return FALSE;
2334
ff3187f6 2335 pkt->savedpos += j;
2336 assert(pkt->savedpos < pkt->length);
0016d70b 2337
2338 return TRUE;
2339}
ff3187f6 2340static Bignum ssh1_pkt_getmp(struct Packet *pkt)
0016d70b 2341{
2342 int j;
2343 Bignum b;
2344
ff3187f6 2345 j = ssh1_read_bignum(pkt->body + pkt->savedpos,
2346 pkt->length - pkt->savedpos, &b);
0016d70b 2347
2348 if (j < 0)
2349 return NULL;
2350
ff3187f6 2351 pkt->savedpos += j;
0016d70b 2352 return b;
2353}
ff3187f6 2354static Bignum ssh2_pkt_getmp(struct Packet *pkt)
32874aea 2355{
7cca0d81 2356 char *p;
3709bfe9 2357 int length;
7cca0d81 2358 Bignum b;
2359
ff3187f6 2360 ssh_pkt_getstring(pkt, &p, &length);
7cca0d81 2361 if (!p)
32874aea 2362 return NULL;
ff3187f6 2363 if (p[0] & 0x80)
32874aea 2364 return NULL;
d8baa528 2365 b = bignum_from_bytes((unsigned char *)p, length);
7cca0d81 2366 return b;
2367}
2368
7d503c31 2369/*
2e85c969 2370 * Helper function to add an SSH-2 signature blob to a packet.
1dd353b5 2371 * Expects to be shown the public key blob as well as the signature
2372 * blob. Normally works just like ssh2_pkt_addstring, but will
2373 * fiddle with the signature packet if necessary for
2374 * BUG_SSH2_RSA_PADDING.
2375 */
ff3187f6 2376static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
2377 void *pkblob_v, int pkblob_len,
1dd353b5 2378 void *sigblob_v, int sigblob_len)
2379{
2380 unsigned char *pkblob = (unsigned char *)pkblob_v;
2381 unsigned char *sigblob = (unsigned char *)sigblob_v;
2382
2383 /* dmemdump(pkblob, pkblob_len); */
2384 /* dmemdump(sigblob, sigblob_len); */
2385
2386 /*
2387 * See if this is in fact an ssh-rsa signature and a buggy
2388 * server; otherwise we can just do this the easy way.
2389 */
51470298 2390 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1dd353b5 2391 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
2392 int pos, len, siglen;
2393
2394 /*
2395 * Find the byte length of the modulus.
2396 */
2397
2398 pos = 4+7; /* skip over "ssh-rsa" */
2399 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
2400 len = GET_32BIT(pkblob+pos); /* find length of modulus */
2401 pos += 4; /* find modulus itself */
2402 while (len > 0 && pkblob[pos] == 0)
2403 len--, pos++;
2404 /* debug(("modulus length is %d\n", len)); */
2405
2406 /*
2407 * Now find the signature integer.
2408 */
2409 pos = 4+7; /* skip over "ssh-rsa" */
2410 siglen = GET_32BIT(sigblob+pos);
2411 /* debug(("signature length is %d\n", siglen)); */
2412
2413 if (len != siglen) {
2414 unsigned char newlen[4];
ff3187f6 2415 ssh2_pkt_addstring_start(pkt);
2416 ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
1dd353b5 2417 /* dmemdump(sigblob, pos); */
2418 pos += 4; /* point to start of actual sig */
2419 PUT_32BIT(newlen, len);
ff3187f6 2420 ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
1dd353b5 2421 /* dmemdump(newlen, 4); */
2422 newlen[0] = 0;
2423 while (len-- > siglen) {
ff3187f6 2424 ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
1dd353b5 2425 /* dmemdump(newlen, 1); */
2426 }
ff3187f6 2427 ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
1dd353b5 2428 /* dmemdump(sigblob+pos, siglen); */
2429 return;
2430 }
2431
2432 /* Otherwise fall through and do it the easy way. */
2433 }
2434
ff3187f6 2435 ssh2_pkt_addstring_start(pkt);
2436 ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
1dd353b5 2437}
2438
2439/*
7d503c31 2440 * Examine the remote side's version string and compare it against
2441 * a list of known buggy implementations.
2442 */
51470298 2443static void ssh_detect_bugs(Ssh ssh, char *vstring)
32874aea 2444{
2445 char *imp; /* pointer to implementation part */
7d503c31 2446 imp = vstring;
2447 imp += strcspn(imp, "-");
bd358db1 2448 if (*imp) imp++;
7d503c31 2449 imp += strcspn(imp, "-");
bd358db1 2450 if (*imp) imp++;
7d503c31 2451
51470298 2452 ssh->remote_bugs = 0;
7d503c31 2453
bf982899 2454 /*
2455 * General notes on server version strings:
2456 * - Not all servers reporting "Cisco-1.25" have all the bugs listed
2457 * here -- in particular, we've heard of one that's perfectly happy
2458 * with SSH1_MSG_IGNOREs -- but this string never seems to change,
2459 * so we can't distinguish them.
2460 */
4a693cfc 2461 if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
2462 (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
2c9c6388 2463 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
2464 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
46ac09aa 2465 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
bd0b4caf 2466 !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
32874aea 2467 /*
2468 * These versions don't support SSH1_MSG_IGNORE, so we have
2469 * to use a different defence against password length
2470 * sniffing.
2471 */
51470298 2472 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
2e85c969 2473 logevent("We believe remote version has SSH-1 ignore bug");
7d503c31 2474 }
2475
4a693cfc 2476 if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
2477 (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
46ac09aa 2478 (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
bd358db1 2479 /*
2480 * These versions need a plain password sent; they can't
2481 * handle having a null and a random length of data after
2482 * the password.
2483 */
51470298 2484 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
2e85c969 2485 logevent("We believe remote version needs a plain SSH-1 password");
bd358db1 2486 }
2487
4a693cfc 2488 if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
2489 (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
2c9c6388 2490 (!strcmp(imp, "Cisco-1.25")))) {
0df73905 2491 /*
2492 * These versions apparently have no clue whatever about
2493 * RSA authentication and will panic and die if they see
2494 * an AUTH_RSA message.
2495 */
51470298 2496 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
19f47a7d 2497 logevent("We believe remote version can't handle SSH-1 RSA authentication");
0df73905 2498 }
2499
4a693cfc 2500 if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
2501 (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
b9f387af 2502 !wc_match("* VShell", imp) &&
831301f6 2503 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
2504 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
2505 wc_match("2.1 *", imp)))) {
32874aea 2506 /*
2507 * These versions have the HMAC bug.
2508 */
51470298 2509 ssh->remote_bugs |= BUG_SSH2_HMAC;
2e85c969 2510 logevent("We believe remote version has SSH-2 HMAC bug");
7d503c31 2511 }
1dd353b5 2512
4a693cfc 2513 if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
2514 (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
b9f387af 2515 !wc_match("* VShell", imp) &&
2856a1b9 2516 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
088bde77 2517 /*
2518 * These versions have the key-derivation bug (failing to
2519 * include the literal shared secret in the hashes that
2520 * generate the keys).
2521 */
51470298 2522 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
2e85c969 2523 logevent("We believe remote version has SSH-2 key-derivation bug");
088bde77 2524 }
2525
4a693cfc 2526 if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
2527 (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
831301f6 2528 (wc_match("OpenSSH_2.[5-9]*", imp) ||
2529 wc_match("OpenSSH_3.[0-2]*", imp)))) {
1dd353b5 2530 /*
2e85c969 2531 * These versions have the SSH-2 RSA padding bug.
1dd353b5 2532 */
51470298 2533 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
2e85c969 2534 logevent("We believe remote version has SSH-2 RSA padding bug");
1dd353b5 2535 }
8e975795 2536
4a693cfc 2537 if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
2538 (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
dda87a28 2539 wc_match("OpenSSH_2.[0-2]*", imp))) {
2540 /*
2e85c969 2541 * These versions have the SSH-2 session-ID bug in
dda87a28 2542 * public-key authentication.
2543 */
2544 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
2e85c969 2545 logevent("We believe remote version has SSH-2 public-key-session-ID bug");
dda87a28 2546 }
f382c87d 2547
4a693cfc 2548 if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
2549 (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
39b8712f 2550 (wc_match("DigiSSH_2.0", imp) ||
2551 wc_match("OpenSSH_2.[0-4]*", imp) ||
e12d95a5 2552 wc_match("OpenSSH_2.5.[0-3]*", imp) ||
2553 wc_match("Sun_SSH_1.0", imp) ||
f4275b53 2554 wc_match("Sun_SSH_1.0.1", imp) ||
96bd26de 2555 /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
2556 wc_match("WeOnlyDo-*", imp)))) {
f382c87d 2557 /*
2e85c969 2558 * These versions have the SSH-2 rekey bug.
f382c87d 2559 */
2560 ssh->remote_bugs |= BUG_SSH2_REKEY;
2e85c969 2561 logevent("We believe remote version has SSH-2 rekey bug");
f382c87d 2562 }
c9739dba 2563
4a693cfc 2564 if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
2565 (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
5ca836f2 2566 (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
2567 wc_match("1.36 sshlib: GlobalScape", imp)))) {
c9739dba 2568 /*
2569 * This version ignores our makpkt and needs to be throttled.
2570 */
2571 ssh->remote_bugs |= BUG_SSH2_MAXPKT;
2572 logevent("We believe remote version ignores SSH-2 maximum packet size");
2573 }
cf6ddb95 2574
4a693cfc 2575 if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
cf6ddb95 2576 /*
2577 * Servers that don't support SSH2_MSG_IGNORE. Currently,
2578 * none detected automatically.
2579 */
2580 ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
2581 logevent("We believe remote version has SSH-2 ignore bug");
2582 }
7d503c31 2583}
2584
d38d6a1f 2585/*
2586 * The `software version' part of an SSH version string is required
2587 * to contain no spaces or minus signs.
2588 */
2589static void ssh_fix_verstring(char *str)
2590{
2591 /* Eat "SSH-<protoversion>-". */
2592 assert(*str == 'S'); str++;
2593 assert(*str == 'S'); str++;
2594 assert(*str == 'H'); str++;
2595 assert(*str == '-'); str++;
2596 while (*str && *str != '-') str++;
2597 assert(*str == '-'); str++;
2598
2599 /* Convert minus signs and spaces in the remaining string into
2600 * underscores. */
2601 while (*str) {
2602 if (*str == '-' || *str == ' ')
2603 *str = '_';
2604 str++;
2605 }
2606}
2607
1fcd0d98 2608/*
2609 * Send an appropriate SSH version string.
2610 */
2611static void ssh_send_verstring(Ssh ssh, char *svers)
2612{
2613 char *verstring;
2614
2615 if (ssh->version == 2) {
2616 /*
2617 * Construct a v2 version string.
2618 */
2619 verstring = dupprintf("SSH-2.0-%s\015\012", sshver);
2620 } else {
2621 /*
2622 * Construct a v1 version string.
2623 */
2624 verstring = dupprintf("SSH-%s-%s\012",
2625 (ssh_versioncmp(svers, "1.5") <= 0 ?
2626 svers : "1.5"),
2627 sshver);
2628 }
2629
2630 ssh_fix_verstring(verstring);
2631
2632 if (ssh->version == 2) {
2633 size_t len;
2634 /*
2635 * Record our version string.
2636 */
2637 len = strcspn(verstring, "\015\012");
2638 ssh->v_c = snewn(len + 1, char);
2639 memcpy(ssh->v_c, verstring, len);
2640 ssh->v_c[len] = 0;
2641 }
2642
2643 logeventf(ssh, "We claim version: %.*s",
2644 strcspn(verstring, "\015\012"), verstring);
2645 s_write(ssh, verstring, strlen(verstring));
2646 sfree(verstring);
2647}
2648
51470298 2649static int do_ssh_init(Ssh ssh, unsigned char c)
32874aea 2650{
51470298 2651 struct do_ssh_init_state {
2652 int vslen;
2653 char version[10];
2654 char *vstring;
2655 int vstrsize;
2656 int i;
2657 int proto1, proto2;
2658 };
2659 crState(do_ssh_init_state);
374330e2 2660
51470298 2661 crBegin(ssh->do_ssh_init_crstate);
8df7a775 2662
8c1835c0 2663 /* Search for a line beginning with the string "SSH-" in the input. */
2664 for (;;) {
2665 if (c != 'S') goto no;
2666 crReturn(1);
2667 if (c != 'S') goto no;
2668 crReturn(1);
2669 if (c != 'H') goto no;
2670 crReturn(1);
2671 if (c != '-') goto no;
2672 break;
2673 no:
2674 while (c != '\012')
2675 crReturn(1);
2676 crReturn(1);
374330e2 2677 }
8df7a775 2678
51470298 2679 s->vstrsize = 16;
3d88e64d 2680 s->vstring = snewn(s->vstrsize, char);
51470298 2681 strcpy(s->vstring, "SSH-");
2682 s->vslen = 4;
2683 s->i = 0;
374330e2 2684 while (1) {
8df7a775 2685 crReturn(1); /* get another char */
51470298 2686 if (s->vslen >= s->vstrsize - 1) {
2687 s->vstrsize += 16;
3d88e64d 2688 s->vstring = sresize(s->vstring, s->vstrsize, char);
32874aea 2689 }
51470298 2690 s->vstring[s->vslen++] = c;
2691 if (s->i >= 0) {
374330e2 2692 if (c == '-') {
51470298 2693 s->version[s->i] = '\0';
2694 s->i = -1;
2695 } else if (s->i < sizeof(s->version) - 1)
2696 s->version[s->i++] = c;
c4ffc4d0 2697 } else if (c == '\012')
374330e2 2698 break;
2699 }
2700
51470298 2701 ssh->agentfwd_enabled = FALSE;
2702 ssh->rdpkt2_state.incoming_sequence = 0;
960e736a 2703
51470298 2704 s->vstring[s->vslen] = 0;
a7d4653a 2705 s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
fb983202 2706 logeventf(ssh, "Server version: %s", s->vstring);
51470298 2707 ssh_detect_bugs(ssh, s->vstring);
c5e9c988 2708
adf799dd 2709 /*
38d228a2 2710 * Decide which SSH protocol version to support.
adf799dd 2711 */
38d228a2 2712
2713 /* Anything strictly below "2.0" means protocol 1 is supported. */
51470298 2714 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
38d228a2 2715 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
51470298 2716 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
38d228a2 2717
4a693cfc 2718 if (conf_get_int(ssh->conf, CONF_sshprot) == 0 && !s->proto1) {
6b5cf8b4 2719 bombout(("SSH protocol version 1 required by user but not provided by server"));
7ffdbc1a 2720 crStop(0);
38d228a2 2721 }
4a693cfc 2722 if (conf_get_int(ssh->conf, CONF_sshprot) == 3 && !s->proto2) {
6b5cf8b4 2723 bombout(("SSH protocol version 2 required by user but not provided by server"));
7ffdbc1a 2724 crStop(0);
38d228a2 2725 }
2726
4a693cfc 2727 if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
1fcd0d98 2728 ssh->version = 2;
2729 else
2730 ssh->version = 1;
d38d6a1f 2731
2732 logeventf(ssh, "Using SSH protocol version %d", ssh->version);
2733
1fcd0d98 2734 /* Send the version string, if we haven't already */
4a693cfc 2735 if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
1fcd0d98 2736 ssh_send_verstring(ssh, s->version);
2737
2738 if (ssh->version == 2) {
2739 size_t len;
2740 /*
2741 * Record their version string.
2742 */
2743 len = strcspn(s->vstring, "\015\012");
2744 ssh->v_s = snewn(len + 1, char);
2745 memcpy(ssh->v_s, s->vstring, len);
2746 ssh->v_s[len] = 0;
2747
2748 /*
2749 * Initialise SSH-2 protocol.
2750 */
2751 ssh->protocol = ssh2_protocol;
2752 ssh2_protocol_setup(ssh);
2753 ssh->s_rdpkt = ssh2_rdpkt;
2754 } else {
2755 /*
2756 * Initialise SSH-1 protocol.
2757 */
2758 ssh->protocol = ssh1_protocol;
2759 ssh1_protocol_setup(ssh);
2760 ssh->s_rdpkt = ssh1_rdpkt;
2761 }
2762 if (ssh->version == 2)
2763 do_ssh2_transport(ssh, NULL, -1, NULL);
2764
125105d1 2765 update_specials_menu(ssh->frontend);
51470298 2766 ssh->state = SSH_STATE_BEFORE_SIZE;
4a693cfc 2767 ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
8df7a775 2768
51470298 2769 sfree(s->vstring);
50526e47 2770
8df7a775 2771 crFinish(0);
2772}
2773
3d9449a1 2774static void ssh_process_incoming_data(Ssh ssh,
2775 unsigned char **data, int *datalen)
2776{
bf8a49a1 2777 struct Packet *pktin;
2778
2779 pktin = ssh->s_rdpkt(ssh, data, datalen);
3d9449a1 2780 if (pktin) {
2781 ssh->protocol(ssh, NULL, 0, pktin);
2782 ssh_free_packet(pktin);
2783 }
2784}
2785
2786static void ssh_queue_incoming_data(Ssh ssh,
2787 unsigned char **data, int *datalen)
2788{
2789 bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
2790 *data += *datalen;
2791 *datalen = 0;
2792}
2793
2794static void ssh_process_queued_incoming_data(Ssh ssh)
2795{
2796 void *vdata;
2797 unsigned char *data;
2798 int len, origlen;
2799
2800 while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
2801 bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
2802 data = vdata;
2803 origlen = len;
2804
2805 while (!ssh->frozen && len > 0)
2806 ssh_process_incoming_data(ssh, &data, &len);
2807
2808 if (origlen > len)
2809 bufchain_consume(&ssh->queued_incoming_data, origlen - len);
2810 }
2811}
2812
2813static void ssh_set_frozen(Ssh ssh, int frozen)
2814{
a5a6f839 2815 if (ssh->s)
2816 sk_set_frozen(ssh->s, frozen);
3d9449a1 2817 ssh->frozen = frozen;
2818}
2819
51470298 2820static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
8df7a775 2821{
bf8a49a1 2822 /* Log raw data, if we're in that mode. */
ff05dfef 2823 if (ssh->logctx)
2824 log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
0d13bfcd 2825 0, NULL, NULL);
bf8a49a1 2826
51470298 2827 crBegin(ssh->ssh_gotdata_crstate);
8df7a775 2828
2829 /*
2830 * To begin with, feed the characters one by one to the
2831 * protocol initialisation / selection function do_ssh_init().
2832 * When that returns 0, we're done with the initial greeting
2833 * exchange and can move on to packet discipline.
2834 */
2835 while (1) {
51470298 2836 int ret; /* need not be kept across crReturn */
8df7a775 2837 if (datalen == 0)
2838 crReturnV; /* more data please */
51470298 2839 ret = do_ssh_init(ssh, *data);
32874aea 2840 data++;
2841 datalen--;
8df7a775 2842 if (ret == 0)
2843 break;
2844 }
2845
2846 /*
2847 * We emerge from that loop when the initial negotiation is
2848 * over and we have selected an s_rdpkt function. Now pass
2849 * everything to s_rdpkt, and then pass the resulting packets
2850 * to the proper protocol handler.
2851 */
3d9449a1 2852
8df7a775 2853 while (1) {
e375106c 2854 while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
2855 if (ssh->frozen) {
3d9449a1 2856 ssh_queue_incoming_data(ssh, &data, &datalen);
e375106c 2857 /* This uses up all data and cannot cause anything interesting
2858 * to happen; indeed, for anything to happen at all, we must
2859 * return, so break out. */
2860 break;
2861 } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
2862 /* This uses up some or all data, and may freeze the
2863 * session. */
2864 ssh_process_queued_incoming_data(ssh);
2865 } else {
2866 /* This uses up some or all data, and may freeze the
2867 * session. */
2868 ssh_process_incoming_data(ssh, &data, &datalen);
2869 }
2870 /* FIXME this is probably EBW. */
ff3187f6 2871 if (ssh->state == SSH_STATE_CLOSED)
2872 return;
8df7a775 2873 }
e375106c 2874 /* We're out of data. Go and get some more. */
8df7a775 2875 crReturnV;
2876 }
2877 crFinishV;
2878}
2879
ac934965 2880static int ssh_do_close(Ssh ssh, int notify_exit)
32874aea 2881{
80ffa58b 2882 int ret = 0;
36f94d1f 2883 struct ssh_channel *c;
2884
51470298 2885 ssh->state = SSH_STATE_CLOSED;
ecbb0000 2886 expire_timer_context(ssh);
51470298 2887 if (ssh->s) {
2888 sk_close(ssh->s);
2889 ssh->s = NULL;
ac934965 2890 if (notify_exit)
2891 notify_remote_exit(ssh->frontend);
2892 else
2893 ret = 1;
f3ab576e 2894 }
36f94d1f 2895 /*
80ffa58b 2896 * Now we must shut down any port- and X-forwarded channels going
36f94d1f 2897 * through this connection.
2898 */
74a98066 2899 if (ssh->channels) {
80ffa58b 2900 while (NULL != (c = index234(ssh->channels, 0))) {
74a98066 2901 switch (c->type) {
2902 case CHAN_X11:
2903 x11_close(c->u.x11.s);
2904 break;
2905 case CHAN_SOCKDATA:
409eca86 2906 case CHAN_SOCKDATA_DORMANT:
74a98066 2907 pfd_close(c->u.pfd.s);
2908 break;
2909 }
80ffa58b 2910 del234(ssh->channels, c); /* moving next one to index 0 */
74a98066 2911 if (ssh->version == 2)
2912 bufchain_clear(&c->v.v2.outbuffer);
2913 sfree(c);
36f94d1f 2914 }
36f94d1f 2915 }
f8c9f9df 2916 /*
2917 * Go through port-forwardings, and close any associated
2918 * listening sockets.
2919 */
2920 if (ssh->portfwds) {
2921 struct ssh_portfwd *pf;
2922 while (NULL != (pf = index234(ssh->portfwds, 0))) {
2923 /* Dispose of any listening socket. */
2924 if (pf->local)
2925 pfd_terminate(pf->local);
2926 del234(ssh->portfwds, pf); /* moving next one to index 0 */
2927 free_portfwd(pf);
2928 }
b72bdf11 2929 freetree234(ssh->portfwds);
2930 ssh->portfwds = NULL;
f8c9f9df 2931 }
ac934965 2932
2933 return ret;
36f94d1f 2934}
2935
7555d6a5 2936static void ssh_log(Plug plug, int type, SockAddr addr, int port,
2937 const char *error_msg, int error_code)
2938{
2939 Ssh ssh = (Ssh) plug;
2940 char addrbuf[256], *msg;
2941
2942 sk_getaddr(addr, addrbuf, lenof(addrbuf));
2943
2944 if (type == 0)
2945 msg = dupprintf("Connecting to %s port %d", addrbuf, port);
2946 else
2947 msg = dupprintf("Failed to connect to %s: %s", addrbuf, error_msg);
2948
2949 logevent(msg);
fb983202 2950 sfree(msg);
7555d6a5 2951}
2952
cbe2d68f 2953static int ssh_closing(Plug plug, const char *error_msg, int error_code,
36f94d1f 2954 int calling_back)
2955{
2956 Ssh ssh = (Ssh) plug;
ac934965 2957 int need_notify = ssh_do_close(ssh, FALSE);
2958
9e296bfa 2959 if (!error_msg) {
2960 if (!ssh->close_expected)
2961 error_msg = "Server unexpectedly closed network connection";
2962 else
2963 error_msg = "Server closed network connection";
ac934965 2964 }
2965
d051d1b4 2966 if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
2967 ssh->exitcode = 0;
2968
2425184b 2969 if (need_notify)
2970 notify_remote_exit(ssh->frontend);
2971
9e296bfa 2972 if (error_msg)
247308b5 2973 logevent(error_msg);
9e296bfa 2974 if (!ssh->close_expected || !ssh->clean_exit)
971bcc0a 2975 connection_fatal(ssh->frontend, "%s", error_msg);
7e78000d 2976 return 0;
2977}
2978
32874aea 2979static int ssh_receive(Plug plug, int urgent, char *data, int len)
2980{
51470298 2981 Ssh ssh = (Ssh) plug;
d8baa528 2982 ssh_gotdata(ssh, (unsigned char *)data, len);
51470298 2983 if (ssh->state == SSH_STATE_CLOSED) {
ac934965 2984 ssh_do_close(ssh, TRUE);
32874aea 2985 return 0;
3257deae 2986 }
fef97f43 2987 return 1;
374330e2 2988}
2989
5471d09a 2990static void ssh_sent(Plug plug, int bufsize)
2991{
51470298 2992 Ssh ssh = (Ssh) plug;
5471d09a 2993 /*
2994 * If the send backlog on the SSH socket itself clears, we
2995 * should unthrottle the whole world if it was throttled.
2996 */
2997 if (bufsize < SSH_MAX_BACKLOG)
51470298 2998 ssh_throttle_all(ssh, 0, bufsize);
5471d09a 2999}
3000
fb09bf1c 3001/*
8df7a775 3002 * Connect to specified host and port.
3003 * Returns an error message, or NULL on success.
6e1ebb76 3004 * Also places the canonical host name into `realhost'. It must be
3005 * freed by the caller.
8df7a775 3006 */
cbe2d68f 3007static const char *connect_to_host(Ssh ssh, char *host, int port,
79bf227b 3008 char **realhost, int nodelay, int keepalive)
8df7a775 3009{
51470298 3010 static const struct plug_function_table fn_table = {
7555d6a5 3011 ssh_log,
7e78000d 3012 ssh_closing,
5471d09a 3013 ssh_receive,
3014 ssh_sent,
3015 NULL
51470298 3016 };
7e78000d 3017
8df7a775 3018 SockAddr addr;
cbe2d68f 3019 const char *err;
4a693cfc 3020 char *loghost;
3021 int addressfamily, sshprot;
3022
3023 loghost = conf_get_str(ssh->conf, CONF_loghost);
3024 if (*loghost) {
881da168 3025 char *colon;
8df7a775 3026
4a693cfc 3027 ssh->savedhost = dupstr(loghost);
881da168 3028 ssh->savedport = 22; /* default ssh port */
3029
3030 /*
3031 * A colon suffix on savedhost also lets us affect
3032 * savedport.
3033 *
3034 * (FIXME: do something about IPv6 address literals here.)
3035 */
3036 colon = strrchr(ssh->savedhost, ':');
3037 if (colon) {
3038 *colon++ = '\0';
3039 if (*colon)
3040 ssh->savedport = atoi(colon);
3041 }
3042 } else {
3043 ssh->savedhost = dupstr(host);
3044 if (port < 0)
3045 port = 22; /* default ssh port */
3046 ssh->savedport = port;
3047 }
8df7a775 3048
3049 /*
3050 * Try to find host.
3051 */
4a693cfc 3052 addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
05581745 3053 logeventf(ssh, "Looking up host \"%s\"%s", host,
4a693cfc 3054 (addressfamily == ADDRTYPE_IPV4 ? " (IPv4)" :
3055 (addressfamily == ADDRTYPE_IPV6 ? " (IPv6)" : "")));
3056 addr = name_lookup(host, port, realhost, ssh->conf, addressfamily);
170c1e6e 3057 if ((err = sk_addr_error(addr)) != NULL) {
3058 sk_addr_free(addr);
8df7a775 3059 return err;
170c1e6e 3060 }
42af6a67 3061 ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
8df7a775 3062
8df7a775 3063 /*
3064 * Open socket.
3065 */
51470298 3066 ssh->fn = &fn_table;
e8fa8f62 3067 ssh->s = new_connection(addr, *realhost, port,
4a693cfc 3068 0, 1, nodelay, keepalive, (Plug) ssh, ssh->conf);
70e5d0fd 3069 if ((err = sk_socket_error(ssh->s)) != NULL) {
51470298 3070 ssh->s = NULL;
39934deb 3071 notify_remote_exit(ssh->frontend);
8df7a775 3072 return err;
67c4ba2e 3073 }
8df7a775 3074
ff05dfef 3075 /*
3076 * If the SSH version number's fixed, set it now, and if it's SSH-2,
3077 * send the version string too.
3078 */
4a693cfc 3079 sshprot = conf_get_int(ssh->conf, CONF_sshprot);
3080 if (sshprot == 0)
ff05dfef 3081 ssh->version = 1;
4a693cfc 3082 if (sshprot == 3) {
ff05dfef 3083 ssh->version = 2;
3084 ssh_send_verstring(ssh, NULL);
3085 }
3086
881da168 3087 /*
3088 * loghost, if configured, overrides realhost.
3089 */
4a693cfc 3090 if (*loghost) {
881da168 3091 sfree(*realhost);
4a693cfc 3092 *realhost = dupstr(loghost);
881da168 3093 }
3094
8df7a775 3095 return NULL;
3096}
3097
3098/*
5471d09a 3099 * Throttle or unthrottle the SSH connection.
3100 */
ff68564b 3101static void ssh_throttle_conn(Ssh ssh, int adjust)
5471d09a 3102{
ff68564b 3103 int old_count = ssh->conn_throttle_count;
3104 ssh->conn_throttle_count += adjust;
3105 assert(ssh->conn_throttle_count >= 0);
3106 if (ssh->conn_throttle_count && !old_count) {
3d9449a1 3107 ssh_set_frozen(ssh, 1);
ff68564b 3108 } else if (!ssh->conn_throttle_count && old_count) {
3d9449a1 3109 ssh_set_frozen(ssh, 0);
5471d09a 3110 }
3111}
3112
3113/*
3114 * Throttle or unthrottle _all_ local data streams (for when sends
3115 * on the SSH connection itself back up).
3116 */
51470298 3117static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
5471d09a 3118{
3119 int i;
3120 struct ssh_channel *c;
3121
51470298 3122 if (enable == ssh->throttled_all)
5471d09a 3123 return;
51470298 3124 ssh->throttled_all = enable;
3125 ssh->overall_bufsize = bufsize;
3126 if (!ssh->channels)
5471d09a 3127 return;
51470298 3128 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
5471d09a 3129 switch (c->type) {
3130 case CHAN_MAINSESSION:
3131 /*
3132 * This is treated separately, outside the switch.
3133 */
3134 break;
3135 case CHAN_X11:
3136 x11_override_throttle(c->u.x11.s, enable);
3137 break;
3138 case CHAN_AGENT:
3139 /* Agent channels require no buffer management. */
3140 break;
3141 case CHAN_SOCKDATA:
36f94d1f 3142 pfd_override_throttle(c->u.pfd.s, enable);
5471d09a 3143 break;
3144 }
3145 }
3146}
3147
f11d78f2 3148static void ssh_agent_callback(void *sshv, void *reply, int replylen)
839f10db 3149{
3150 Ssh ssh = (Ssh) sshv;
3151
3152 ssh->agent_response = reply;
3153 ssh->agent_response_len = replylen;
3154
3155 if (ssh->version == 1)
ff3187f6 3156 do_ssh1_login(ssh, NULL, -1, NULL);
839f10db 3157 else
ff3187f6 3158 do_ssh2_authconn(ssh, NULL, -1, NULL);
839f10db 3159}
3160
3d9449a1 3161static void ssh_dialog_callback(void *sshv, int ret)
3162{
3163 Ssh ssh = (Ssh) sshv;
3164
3165 ssh->user_response = ret;
3166
3167 if (ssh->version == 1)
3168 do_ssh1_login(ssh, NULL, -1, NULL);
3169 else
3170 do_ssh2_transport(ssh, NULL, -1, NULL);
3171
3172 /*
3173 * This may have unfrozen the SSH connection, so do a
3174 * queued-data run.
3175 */
3176 ssh_process_queued_incoming_data(ssh);
3177}
3178
f11d78f2 3179static void ssh_agentf_callback(void *cv, void *reply, int replylen)
839f10db 3180{
3181 struct ssh_channel *c = (struct ssh_channel *)cv;
3182 Ssh ssh = c->ssh;
3183 void *sentreply = reply;
3184
3185 if (!sentreply) {
3186 /* Fake SSH_AGENT_FAILURE. */
3187 sentreply = "\0\0\0\1\5";
3188 replylen = 5;
3189 }
3190 if (ssh->version == 2) {
3191 ssh2_add_channel_data(c, sentreply, replylen);
3192 ssh2_try_send(c);
3193 } else {
3194 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
3195 PKT_INT, c->remoteid,
3196 PKT_INT, replylen,
a2724fba 3197 PKTT_DATA,
839f10db 3198 PKT_DATA, sentreply, replylen,
9a10ecf4 3199 PKTT_OTHER,
839f10db 3200 PKT_END);
3201 }
3202 if (reply)
3203 sfree(reply);
3204}
3205
0405e71f 3206/*
9e296bfa 3207 * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
3208 * non-NULL, otherwise just close the connection. `client_reason' == NULL
3209 * => log `wire_reason'.
3210 */
3211static void ssh_disconnect(Ssh ssh, char *client_reason, char *wire_reason,
3212 int code, int clean_exit)
3213{
3214 char *error;
3215 if (!client_reason)
3216 client_reason = wire_reason;
3217 if (client_reason)
3218 error = dupprintf("Disconnected: %s", client_reason);
3219 else
3220 error = dupstr("Disconnected");
3221 if (wire_reason) {
3222 if (ssh->version == 1) {
3223 send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
3224 PKT_END);
3225 } else if (ssh->version == 2) {
3226 struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
3227 ssh2_pkt_adduint32(pktout, code);
3228 ssh2_pkt_addstring(pktout, wire_reason);
3229 ssh2_pkt_addstring(pktout, "en"); /* language tag */
3230 ssh2_pkt_send_noqueue(ssh, pktout);
3231 }
3232 }
3233 ssh->close_expected = TRUE;
3234 ssh->clean_exit = clean_exit;
3235 ssh_closing((Plug)ssh, error, 0, 0);
3236 sfree(error);
3237}
3238
3239/*
fb09bf1c 3240 * Handle the key exchange and user authentication phases.
3241 */
ff3187f6 3242static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen,
3243 struct Packet *pktin)
fb09bf1c 3244{
0016d70b 3245 int i, j, ret;
3246 unsigned char cookie[8], *ptr;
374330e2 3247 struct RSAKey servkey, hostkey;
3248 struct MD5Context md5c;
51470298 3249 struct do_ssh1_login_state {
3250 int len;
3251 unsigned char *rsabuf, *keystr1, *keystr2;
3252 unsigned long supported_ciphers_mask, supported_auths_mask;
3253 int tried_publickey, tried_agent;
3254 int tis_auth_refused, ccard_auth_refused;
3255 unsigned char session_id[16];
3256 int cipher_type;
51470298 3257 void *publickey_blob;
3258 int publickey_bloblen;
edd0cb8a 3259 char *publickey_comment;
3260 int publickey_encrypted;
3261 prompts_t *cur_prompt;
51470298 3262 char c;
3263 int pwpkt_type;
3264 unsigned char request[5], *response, *p;
3265 int responselen;
3266 int keyi, nkeys;
3267 int authed;
3268 struct RSAKey key;
3269 Bignum challenge;
3270 char *commentp;
3271 int commentlen;
3d9449a1 3272 int dlgret;
4a693cfc 3273 Filename *keyfile;
51470298 3274 };
3275 crState(do_ssh1_login_state);
3276
3277 crBegin(ssh->do_ssh1_login_crstate);
374330e2 3278
ff3187f6 3279 if (!pktin)
3280 crWaitUntil(pktin);
374330e2 3281
ff3187f6 3282 if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
6b5cf8b4 3283 bombout(("Public key packet not received"));
7ffdbc1a 3284 crStop(0);
8d5de777 3285 }
374330e2 3286
c5e9c988 3287 logevent("Received public keys");
374330e2 3288
ff3187f6 3289 ptr = ssh_pkt_getdata(pktin, 8);
0016d70b 3290 if (!ptr) {
2e85c969 3291 bombout(("SSH-1 public key packet stopped before random cookie"));
0016d70b 3292 crStop(0);
3293 }
3294 memcpy(cookie, ptr, 8);
374330e2 3295
ff3187f6 3296 if (!ssh1_pkt_getrsakey(pktin, &servkey, &s->keystr1) ||
3297 !ssh1_pkt_getrsakey(pktin, &hostkey, &s->keystr2)) {
2e85c969 3298 bombout(("Failed to read SSH-1 public keys from public key packet"));
0016d70b 3299 crStop(0);
3300 }
374330e2 3301
c5e9c988 3302 /*
1c2a93c4 3303 * Log the host key fingerprint.
c5e9c988 3304 */
c5e9c988 3305 {
3306 char logmsg[80];
1c2a93c4 3307 logevent("Host key fingerprint is:");
c5e9c988 3308 strcpy(logmsg, " ");
32874aea 3309 hostkey.comment = NULL;
3310 rsa_fingerprint(logmsg + strlen(logmsg),
3311 sizeof(logmsg) - strlen(logmsg), &hostkey);
c5e9c988 3312 logevent(logmsg);
3313 }
3314
ff3187f6 3315 ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
3316 s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
3317 s->supported_auths_mask = ssh_pkt_getuint32(pktin);
d5b2c841 3318 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
3319 s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
bea1ef5f 3320
51470298 3321 ssh->v1_local_protoflags =
3322 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
3323 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
b96dc54c 3324
c5e9c988 3325 MD5Init(&md5c);
51470298 3326 MD5Update(&md5c, s->keystr2, hostkey.bytes);
3327 MD5Update(&md5c, s->keystr1, servkey.bytes);
0016d70b 3328 MD5Update(&md5c, cookie, 8);
51470298 3329 MD5Final(s->session_id, &md5c);
374330e2 3330
32874aea 3331 for (i = 0; i < 32; i++)
51470298 3332 ssh->session_key[i] = random_byte();
374330e2 3333
0016d70b 3334 /*
3335 * Verify that the `bits' and `bytes' parameters match.
3336 */
3337 if (hostkey.bits > hostkey.bytes * 8 ||
3338 servkey.bits > servkey.bytes * 8) {
2e85c969 3339 bombout(("SSH-1 public keys were badly formatted"));
0016d70b 3340 crStop(0);
3341 }
3342
51470298 3343 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
374330e2 3344
3d88e64d 3345 s->rsabuf = snewn(s->len, unsigned char);
374330e2 3346
89ee5268 3347 /*
3348 * Verify the host key.
3349 */
3350 {
32874aea 3351 /*
3352 * First format the key into a string.
3353 */
3354 int len = rsastr_len(&hostkey);
3355 char fingerprint[100];
3d88e64d 3356 char *keystr = snewn(len, char);
32874aea 3357 rsastr_fmt(keystr, &hostkey);
3358 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
3d9449a1 3359
3360 ssh_set_frozen(ssh, 1);
3361 s->dlgret = verify_ssh_host_key(ssh->frontend,
3362 ssh->savedhost, ssh->savedport,
3363 "rsa", keystr, fingerprint,
3364 ssh_dialog_callback, ssh);
32874aea 3365 sfree(keystr);
3d9449a1 3366 if (s->dlgret < 0) {
3367 do {
3368 crReturn(0);
3369 if (pktin) {
3370 bombout(("Unexpected data from server while waiting"
3371 " for user host key response"));
3372 crStop(0);
3373 }
3374 } while (pktin || inlen > 0);
3375 s->dlgret = ssh->user_response;
3376 }
3377 ssh_set_frozen(ssh, 0);
3378
3379 if (s->dlgret == 0) {
9e296bfa 3380 ssh_disconnect(ssh, "User aborted at host key verification",
3381 NULL, 0, TRUE);
2b3f6c19 3382 crStop(0);
3d9449a1 3383 }
32874aea 3384 }
3385
3386 for (i = 0; i < 32; i++) {
51470298 3387 s->rsabuf[i] = ssh->session_key[i];
374330e2 3388 if (i < 16)
51470298 3389 s->rsabuf[i] ^= s->session_id[i];
374330e2 3390 }
3391
3392 if (hostkey.bytes > servkey.bytes) {
0016d70b 3393 ret = rsaencrypt(s->rsabuf, 32, &servkey);
3394 if (ret)
3395 ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
374330e2 3396 } else {
0016d70b 3397 ret = rsaencrypt(s->rsabuf, 32, &hostkey);
3398 if (ret)
3399 ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
3400 }
3401 if (!ret) {
2e85c969 3402 bombout(("SSH-1 public key encryptions failed due to bad formatting"));
0016d70b 3403 crStop(0);
374330e2 3404 }
3405
c5e9c988 3406 logevent("Encrypted session key");
3407
ca20bfcf 3408 {
3409 int cipher_chosen = 0, warn = 0;
3410 char *cipher_string = NULL;
51470298 3411 int i;
ca20bfcf 3412 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
4a693cfc 3413 int next_cipher = conf_get_int_int(ssh->conf,
3414 CONF_ssh_cipherlist, i);
ca20bfcf 3415 if (next_cipher == CIPHER_WARN) {
3416 /* If/when we choose a cipher, warn about it */
3417 warn = 1;
3418 } else if (next_cipher == CIPHER_AES) {
3419 /* XXX Probably don't need to mention this. */
2e85c969 3420 logevent("AES not supported in SSH-1, skipping");
ca20bfcf 3421 } else {
3422 switch (next_cipher) {
51470298 3423 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
ca20bfcf 3424 cipher_string = "3DES"; break;
51470298 3425 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
ca20bfcf 3426 cipher_string = "Blowfish"; break;
51470298 3427 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
ca20bfcf 3428 cipher_string = "single-DES"; break;
3429 }
51470298 3430 if (s->supported_ciphers_mask & (1 << s->cipher_type))
ca20bfcf 3431 cipher_chosen = 1;
3432 }
3433 }
3434 if (!cipher_chosen) {
51470298 3435 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
2e85c969 3436 bombout(("Server violates SSH-1 protocol by not "
ca20bfcf 3437 "supporting 3DES encryption"));
3438 else
3439 /* shouldn't happen */
6b5cf8b4 3440 bombout(("No supported ciphers found"));
7ffdbc1a 3441 crStop(0);
a99a05c0 3442 }
ca20bfcf 3443
3444 /* Warn about chosen cipher if necessary. */
bb348ab1 3445 if (warn) {
3d9449a1 3446 ssh_set_frozen(ssh, 1);
3447 s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
3448 ssh_dialog_callback, ssh);
3449 if (s->dlgret < 0) {
3450 do {
3451 crReturn(0);
3452 if (pktin) {
3453 bombout(("Unexpected data from server while waiting"
3454 " for user response"));
3455 crStop(0);
3456 }
3457 } while (pktin || inlen > 0);
3458 s->dlgret = ssh->user_response;
3459 }
3460 ssh_set_frozen(ssh, 0);
3461 if (s->dlgret == 0) {
9e296bfa 3462 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
3463 0, TRUE);
96ccde8b 3464 crStop(0);
3d9449a1 3465 }
bb348ab1 3466 }
bea1ef5f 3467 }
ca20bfcf 3468
51470298 3469 switch (s->cipher_type) {
32874aea 3470 case SSH_CIPHER_3DES:
3471 logevent("Using 3DES encryption");
3472 break;
3473 case SSH_CIPHER_DES:
3474 logevent("Using single-DES encryption");
3475 break;
3476 case SSH_CIPHER_BLOWFISH:
3477 logevent("Using Blowfish encryption");
3478 break;
c5e9c988 3479 }
bea1ef5f 3480
51470298 3481 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
3482 PKT_CHAR, s->cipher_type,
32874aea 3483 PKT_DATA, cookie, 8,
51470298 3484 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
3485 PKT_DATA, s->rsabuf, s->len,
3486 PKT_INT, ssh->v1_local_protoflags, PKT_END);
fb09bf1c 3487
c5e9c988 3488 logevent("Trying to enable encryption...");
374330e2 3489
51470298 3490 sfree(s->rsabuf);
374330e2 3491
51470298 3492 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
3493 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
3494 &ssh_3des);
371e569c 3495 ssh->v1_cipher_ctx = ssh->cipher->make_context();
3496 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
57356d63 3497 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
374330e2 3498
0183b242 3499 ssh->crcda_ctx = crcda_make_context();
3500 logevent("Installing CRC compensation attack detector");
3501
679539d7 3502 if (servkey.modulus) {
3503 sfree(servkey.modulus);
3504 servkey.modulus = NULL;
3505 }
3506 if (servkey.exponent) {
3507 sfree(servkey.exponent);
3508 servkey.exponent = NULL;
3509 }
3510 if (hostkey.modulus) {
3511 sfree(hostkey.modulus);
3512 hostkey.modulus = NULL;
3513 }
3514 if (hostkey.exponent) {
3515 sfree(hostkey.exponent);
3516 hostkey.exponent = NULL;
3517 }
ff3187f6 3518 crWaitUntil(pktin);
374330e2 3519
ff3187f6 3520 if (pktin->type != SSH1_SMSG_SUCCESS) {
6b5cf8b4 3521 bombout(("Encryption not successfully enabled"));
7ffdbc1a 3522 crStop(0);
8d5de777 3523 }
374330e2 3524
c5e9c988 3525 logevent("Successfully started encryption");
3526
edd0cb8a 3527 fflush(stdout); /* FIXME eh? */
374330e2 3528 {
4a693cfc 3529 if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
edd0cb8a 3530 int ret; /* need not be kept over crReturn */
3531 s->cur_prompt = new_prompts(ssh->frontend);
3532 s->cur_prompt->to_server = TRUE;
3533 s->cur_prompt->name = dupstr("SSH login name");
b61f81bc 3534 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
edd0cb8a 3535 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3536 while (ret < 0) {
51470298 3537 ssh->send_ok = 1;
edd0cb8a 3538 crWaitUntil(!pktin);
3539 ret = get_userpass_input(s->cur_prompt, in, inlen);
3540 ssh->send_ok = 0;
3541 }
3542 if (!ret) {
3543 /*
3544 * Failed to get a username. Terminate.
3545 */
3546 free_prompts(s->cur_prompt);
3547 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
3548 crStop(0);
32874aea 3549 }
4a693cfc 3550 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
edd0cb8a 3551 free_prompts(s->cur_prompt);
374330e2 3552 }
fb09bf1c 3553
4a693cfc 3554 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
c5e9c988 3555 {
4a693cfc 3556 char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
c5e9c988 3557 logevent(userlog);
32874aea 3558 if (flags & FLAG_INTERACTIVE &&
3559 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
51470298 3560 c_write_str(ssh, userlog);
edd0cb8a 3561 c_write_str(ssh, "\r\n");
3c8e959b 3562 }
edd0cb8a 3563 sfree(userlog);
c5e9c988 3564 }
374330e2 3565 }
3566
ff3187f6 3567 crWaitUntil(pktin);
374330e2 3568
d5b2c841 3569 if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
0df73905 3570 /* We must not attempt PK auth. Pretend we've already tried it. */
51470298 3571 s->tried_publickey = s->tried_agent = 1;
0df73905 3572 } else {
51470298 3573 s->tried_publickey = s->tried_agent = 0;
0df73905 3574 }
51470298 3575 s->tis_auth_refused = s->ccard_auth_refused = 0;
edd0cb8a 3576 /*
3577 * Load the public half of any configured keyfile for later use.
3578 */
4a693cfc 3579 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
962468d4 3580 if (!filename_is_null(s->keyfile)) {
edd0cb8a 3581 int keytype;
3582 logeventf(ssh, "Reading private key file \"%.150s\"",
4a693cfc 3583 filename_to_str(s->keyfile));
3584 keytype = key_type(s->keyfile);
edd0cb8a 3585 if (keytype == SSH_KEYTYPE_SSH1) {
3586 const char *error;
4a693cfc 3587 if (rsakey_pubblob(s->keyfile,
edd0cb8a 3588 &s->publickey_blob, &s->publickey_bloblen,
3589 &s->publickey_comment, &error)) {
4a693cfc 3590 s->publickey_encrypted = rsakey_encrypted(s->keyfile,
edd0cb8a 3591 NULL);
3592 } else {
3593 char *msgbuf;
3594 logeventf(ssh, "Unable to load private key (%s)", error);
3595 msgbuf = dupprintf("Unable to load private key file "
3596 "\"%.150s\" (%s)\r\n",
4a693cfc 3597 filename_to_str(s->keyfile),
edd0cb8a 3598 error);
3599 c_write_str(ssh, msgbuf);
3600 sfree(msgbuf);
3601 s->publickey_blob = NULL;
3602 }
3603 } else {
3604 char *msgbuf;
3605 logeventf(ssh, "Unable to use this key file (%s)",
3606 key_type_to_str(keytype));
3607 msgbuf = dupprintf("Unable to use key file \"%.150s\""
3608 " (%s)\r\n",
4a693cfc 3609 filename_to_str(s->keyfile),
edd0cb8a 3610 key_type_to_str(keytype));
3611 c_write_str(ssh, msgbuf);
3612 sfree(msgbuf);
51470298 3613 s->publickey_blob = NULL;
edd0cb8a 3614 }
396778f1 3615 } else
51470298 3616 s->publickey_blob = NULL;
7cca0d81 3617
ff3187f6 3618 while (pktin->type == SSH1_SMSG_FAILURE) {
51470298 3619 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
614a20a0 3620
4a693cfc 3621 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
32874aea 3622 /*
3623 * Attempt RSA authentication using Pageant.
3624 */
32874aea 3625 void *r;
3626
51470298 3627 s->authed = FALSE;
3628 s->tried_agent = 1;
32874aea 3629 logevent("Pageant is running. Requesting keys.");
3630
3631 /* Request the keys held by the agent. */
51470298 3632 PUT_32BIT(s->request, 1);
3633 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
839f10db 3634 if (!agent_query(s->request, 5, &r, &s->responselen,
3635 ssh_agent_callback, ssh)) {
3636 do {
3637 crReturn(0);
ff3187f6 3638 if (pktin) {
839f10db 3639 bombout(("Unexpected data from server while waiting"
3640 " for agent response"));
3641 crStop(0);
3642 }
ff3187f6 3643 } while (pktin || inlen > 0);
839f10db 3644 r = ssh->agent_response;
3645 s->responselen = ssh->agent_response_len;
3646 }
51470298 3647 s->response = (unsigned char *) r;
3648 if (s->response && s->responselen >= 5 &&
3649 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
3650 s->p = s->response + 5;
3651 s->nkeys = GET_32BIT(s->p);
3652 s->p += 4;
2e85c969 3653 logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
51470298 3654 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
94cd7c3a 3655 unsigned char *pkblob = s->p;
51470298 3656 s->p += 4;
0016d70b 3657 {
3658 int n, ok = FALSE;
3659 do { /* do while (0) to make breaking easy */
3660 n = ssh1_read_bignum
3661 (s->p, s->responselen-(s->p-s->response),
3662 &s->key.exponent);
3663 if (n < 0)
3664 break;
3665 s->p += n;
3666 n = ssh1_read_bignum
3667 (s->p, s->responselen-(s->p-s->response),
3668 &s->key.modulus);
3669 if (n < 0)
3670 break;
3671 s->p += n;
3672 if (s->responselen - (s->p-s->response) < 4)
3673 break;
3674 s->commentlen = GET_32BIT(s->p);
3675 s->p += 4;
3676 if (s->responselen - (s->p-s->response) <
3677 s->commentlen)
3678 break;
3679 s->commentp = (char *)s->p;
3680 s->p += s->commentlen;
3681 ok = TRUE;
3682 } while (0);
3683 if (!ok) {
3684 logevent("Pageant key list packet was truncated");
3685 break;
3686 }
3687 }
94cd7c3a 3688 if (s->publickey_blob) {
3689 if (!memcmp(pkblob, s->publickey_blob,
3690 s->publickey_bloblen)) {
3691 logeventf(ssh, "Pageant key #%d matches "
3692 "configured key file", s->keyi);
3693 s->tried_publickey = 1;
3694 } else
3695 /* Skip non-configured key */
3696 continue;
3697 }
3698 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
51470298 3699 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3700 PKT_BIGNUM, s->key.modulus, PKT_END);
ff3187f6 3701 crWaitUntil(pktin);
3702 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
32874aea 3703 logevent("Key refused");
3704 continue;
3705 }
3706 logevent("Received RSA challenge");
ff3187f6 3707 if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
0016d70b 3708 bombout(("Server's RSA challenge was badly formatted"));
3709 crStop(0);
3710 }
3711
32874aea 3712 {
3713 char *agentreq, *q, *ret;
2d466ffd 3714 void *vret;
32874aea 3715 int len, retlen;
3716 len = 1 + 4; /* message type, bit count */
51470298 3717 len += ssh1_bignum_length(s->key.exponent);
3718 len += ssh1_bignum_length(s->key.modulus);
3719 len += ssh1_bignum_length(s->challenge);
32874aea 3720 len += 16; /* session id */
3721 len += 4; /* response format */
3d88e64d 3722 agentreq = snewn(4 + len, char);
32874aea 3723 PUT_32BIT(agentreq, len);
3724 q = agentreq + 4;
3725 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
51470298 3726 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
32874aea 3727 q += 4;
51470298 3728 q += ssh1_write_bignum(q, s->key.exponent);
3729 q += ssh1_write_bignum(q, s->key.modulus);
3730 q += ssh1_write_bignum(q, s->challenge);
3731 memcpy(q, s->session_id, 16);
32874aea 3732 q += 16;
3733 PUT_32BIT(q, 1); /* response format */
839f10db 3734 if (!agent_query(agentreq, len + 4, &vret, &retlen,
3735 ssh_agent_callback, ssh)) {
3736 sfree(agentreq);
3737 do {
3738 crReturn(0);
ff3187f6 3739 if (pktin) {
839f10db 3740 bombout(("Unexpected data from server"
3741 " while waiting for agent"
3742 " response"));
3743 crStop(0);
3744 }
ff3187f6 3745 } while (pktin || inlen > 0);
839f10db 3746 vret = ssh->agent_response;
3747 retlen = ssh->agent_response_len;
3748 } else
3749 sfree(agentreq);
2d466ffd 3750 ret = vret;
32874aea 3751 if (ret) {
3752 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
3753 logevent("Sending Pageant's response");
51470298 3754 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
32874aea 3755 PKT_DATA, ret + 5, 16,
3756 PKT_END);
3757 sfree(ret);
ff3187f6 3758 crWaitUntil(pktin);
3759 if (pktin->type == SSH1_SMSG_SUCCESS) {
32874aea 3760 logevent
3761 ("Pageant's response accepted");
3762 if (flags & FLAG_VERBOSE) {
51470298 3763 c_write_str(ssh, "Authenticated using"
3764 " RSA key \"");
3765 c_write(ssh, s->commentp,
3766 s->commentlen);
3767 c_write_str(ssh, "\" from agent\r\n");
32874aea 3768 }
51470298 3769 s->authed = TRUE;
32874aea 3770 } else
3771 logevent
3772 ("Pageant's response not accepted");
3773 } else {
3774 logevent
3775 ("Pageant failed to answer challenge");
3776 sfree(ret);
3777 }
3778 } else {
3779 logevent("No reply received from Pageant");
3780 }
3781 }
51470298 3782 freebn(s->key.exponent);
3783 freebn(s->key.modulus);
3784 freebn(s->challenge);
3785 if (s->authed)
32874aea 3786 break;
3787 }
29b1d0b3 3788 sfree(s->response);
94cd7c3a 3789 if (s->publickey_blob && !s->tried_publickey)
3790 logevent("Configured key file not in Pageant");
5ff99b8e 3791 } else {
3792 logevent("Failed to get reply from Pageant");
3793 }
51470298 3794 if (s->authed)
32874aea 3795 break;
3796 }
edd0cb8a 3797 if (s->publickey_blob && !s->tried_publickey) {
3798 /*
3799 * Try public key authentication with the specified
3800 * key file.
3801 */
3802 int got_passphrase; /* need not be kept over crReturn */
3803 if (flags & FLAG_VERBOSE)
3804 c_write_str(ssh, "Trying public key authentication.\r\n");
4a693cfc 3805 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
edd0cb8a 3806 logeventf(ssh, "Trying public key \"%s\"",
4a693cfc 3807 filename_to_str(s->keyfile));
edd0cb8a 3808 s->tried_publickey = 1;
3809 got_passphrase = FALSE;
3810 while (!got_passphrase) {
3811 /*
3812 * Get a passphrase, if necessary.
3813 */
3814 char *passphrase = NULL; /* only written after crReturn */
3815 const char *error;
3816 if (!s->publickey_encrypted) {
3817 if (flags & FLAG_VERBOSE)
3818 c_write_str(ssh, "No passphrase required.\r\n");
3819 passphrase = NULL;
3820 } else {
3821 int ret; /* need not be kept over crReturn */
3822 s->cur_prompt = new_prompts(ssh->frontend);
3823 s->cur_prompt->to_server = FALSE;
3824 s->cur_prompt->name = dupstr("SSH key passphrase");
3825 add_prompt(s->cur_prompt,
3826 dupprintf("Passphrase for key \"%.100s\": ",
b61f81bc 3827 s->publickey_comment), FALSE);
edd0cb8a 3828 ret = get_userpass_input(s->cur_prompt, NULL, 0);
3829 while (ret < 0) {
3830 ssh->send_ok = 1;
3831 crWaitUntil(!pktin);
3832 ret = get_userpass_input(s->cur_prompt, in, inlen);
3833 ssh->send_ok = 0;
3834 }
3835 if (!ret) {
3836 /* Failed to get a passphrase. Terminate. */
3837 free_prompts(s->cur_prompt);
3838 ssh_disconnect(ssh, NULL, "Unable to authenticate",
3839 0, TRUE);
3840 crStop(0);
3841 }
3842 passphrase = dupstr(s->cur_prompt->prompts[0]->result);
3843 free_prompts(s->cur_prompt);
3844 }
3845 /*
3846 * Try decrypting key with passphrase.
3847 */
4a693cfc 3848 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
3849 ret = loadrsakey(s->keyfile, &s->key, passphrase,
edd0cb8a 3850 &error);
3851 if (passphrase) {
dfb88efd 3852 smemclr(passphrase, strlen(passphrase));
edd0cb8a 3853 sfree(passphrase);
3854 }
3855 if (ret == 1) {
3856 /* Correct passphrase. */
3857 got_passphrase = TRUE;
3858 } else if (ret == 0) {
3859 c_write_str(ssh, "Couldn't load private key from ");
4a693cfc 3860 c_write_str(ssh, filename_to_str(s->keyfile));
edd0cb8a 3861 c_write_str(ssh, " (");
3862 c_write_str(ssh, error);
3863 c_write_str(ssh, ").\r\n");
3864 got_passphrase = FALSE;
3865 break; /* go and try something else */
3866 } else if (ret == -1) {
3867 c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
edd0cb8a 3868 got_passphrase = FALSE;
3869 /* and try again */
43536490 3870 } else {
3871 assert(0 && "unexpected return from loadrsakey()");
edc23a8a 3872 got_passphrase = FALSE; /* placate optimisers */
edd0cb8a 3873 }
3874 }
3875
3876 if (got_passphrase) {
3877
3878 /*
3879 * Send a public key attempt.
3880 */
3881 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
3882 PKT_BIGNUM, s->key.modulus, PKT_END);
3883
3884 crWaitUntil(pktin);
3885 if (pktin->type == SSH1_SMSG_FAILURE) {
3886 c_write_str(ssh, "Server refused our public key.\r\n");
7b575324 3887 continue; /* go and try something else */
edd0cb8a 3888 }
3889 if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
3890 bombout(("Bizarre response to offer of public key"));
3891 crStop(0);
3892 }
3893
3894 {
3895 int i;
3896 unsigned char buffer[32];
3897 Bignum challenge, response;
3898
3899 if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
3900 bombout(("Server's RSA challenge was badly formatted"));
3901 crStop(0);
3902 }
3903 response = rsadecrypt(challenge, &s->key);
3904 freebn(s->key.private_exponent);/* burn the evidence */
3905
3906 for (i = 0; i < 32; i++) {
3907 buffer[i] = bignum_byte(response, 31 - i);
3908 }
3909
3910 MD5Init(&md5c);
3911 MD5Update(&md5c, buffer, 32);
3912 MD5Update(&md5c, s->session_id, 16);
3913 MD5Final(buffer, &md5c);
3914
3915 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
3916 PKT_DATA, buffer, 16, PKT_END);
3917
3918 freebn(challenge);
3919 freebn(response);
3920 }
3921
3922 crWaitUntil(pktin);
3923 if (pktin->type == SSH1_SMSG_FAILURE) {
3924 if (flags & FLAG_VERBOSE)
3925 c_write_str(ssh, "Failed to authenticate with"
3926 " our public key.\r\n");
7b575324 3927 continue; /* go and try something else */
edd0cb8a 3928 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
3929 bombout(("Bizarre response to RSA authentication response"));
3930 crStop(0);
3931 }
3932
3933 break; /* we're through! */
3934 }
3935
3936 }
3937
3938 /*
3939 * Otherwise, try various forms of password-like authentication.
3940 */
3941 s->cur_prompt = new_prompts(ssh->frontend);
32874aea 3942
4a693cfc 3943 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
51470298 3944 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
3945 !s->tis_auth_refused) {
3946 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
32874aea 3947 logevent("Requested TIS authentication");
51470298 3948 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
ff3187f6 3949 crWaitUntil(pktin);
3950 if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
32874aea 3951 logevent("TIS authentication declined");
3952 if (flags & FLAG_INTERACTIVE)
51470298 3953 c_write_str(ssh, "TIS authentication refused.\r\n");
3954 s->tis_auth_refused = 1;
614a20a0 3955 continue;
32874aea 3956 } else {
0016d70b 3957 char *challenge;
3958 int challengelen;
edd0cb8a 3959 char *instr_suf, *prompt;
0016d70b 3960
ff3187f6 3961 ssh_pkt_getstring(pktin, &challenge, &challengelen);
0016d70b 3962 if (!challenge) {
3963 bombout(("TIS challenge packet was badly formed"));
3964 crStop(0);
3965 }
32874aea 3966 logevent("Received TIS challenge");
edd0cb8a 3967 s->cur_prompt->to_server = TRUE;
3968 s->cur_prompt->name = dupstr("SSH TIS authentication");
614a20a0 3969 /* Prompt heuristic comes from OpenSSH */
edd0cb8a 3970 if (memchr(challenge, '\n', challengelen)) {
3971 instr_suf = dupstr("");
3972 prompt = dupprintf("%.*s", challengelen, challenge);
3973 } else {
3974 instr_suf = dupprintf("%.*s", challengelen, challenge);
3975 prompt = dupstr("Response: ");
3976 }
3977 s->cur_prompt->instruction =
3978 dupprintf("Using TIS authentication.%s%s",
3979 (*instr_suf) ? "\n" : "",
3980 instr_suf);
3981 s->cur_prompt->instr_reqd = TRUE;
b61f81bc 3982 add_prompt(s->cur_prompt, prompt, FALSE);
edd0cb8a 3983 sfree(instr_suf);
32874aea 3984 }
3985 }
4a693cfc 3986 if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
51470298 3987 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
3988 !s->ccard_auth_refused) {
3989 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
32874aea 3990 logevent("Requested CryptoCard authentication");
51470298 3991 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
ff3187f6 3992 crWaitUntil(pktin);
3993 if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
32874aea 3994 logevent("CryptoCard authentication declined");
51470298 3995 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
3996 s->ccard_auth_refused = 1;
614a20a0 3997 continue;
32874aea 3998 } else {
0016d70b 3999 char *challenge;
4000 int challengelen;
edd0cb8a 4001 char *instr_suf, *prompt;
0016d70b 4002
ff3187f6 4003 ssh_pkt_getstring(pktin, &challenge, &challengelen);
0016d70b 4004 if (!challenge) {
4005 bombout(("CryptoCard challenge packet was badly formed"));
4006 crStop(0);
4007 }
32874aea 4008 logevent("Received CryptoCard challenge");
edd0cb8a 4009 s->cur_prompt->to_server = TRUE;
4010 s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
4011 s->cur_prompt->name_reqd = FALSE;
4012 /* Prompt heuristic comes from OpenSSH */
4013 if (memchr(challenge, '\n', challengelen)) {
4014 instr_suf = dupstr("");
4015 prompt = dupprintf("%.*s", challengelen, challenge);
4016 } else {
4017 instr_suf = dupprintf("%.*s", challengelen, challenge);
4018 prompt = dupstr("Response: ");
4019 }
4020 s->cur_prompt->instruction =
4021 dupprintf("Using CryptoCard authentication.%s%s",
4022 (*instr_suf) ? "\n" : "",
4023 instr_suf);
4024 s->cur_prompt->instr_reqd = TRUE;
b61f81bc 4025 add_prompt(s->cur_prompt, prompt, FALSE);
edd0cb8a 4026 sfree(instr_suf);
32874aea 4027 }
4028 }
51470298 4029 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
8f9e3231 4030 if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
4031 bombout(("No supported authentication methods available"));
4032 crStop(0);
4033 }
edd0cb8a 4034 s->cur_prompt->to_server = TRUE;
4035 s->cur_prompt->name = dupstr("SSH password");
4a693cfc 4036 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
4037 ssh->username, ssh->savedhost),
b61f81bc 4038 FALSE);
32874aea 4039 }
a52f067e 4040
614a20a0 4041 /*
4042 * Show password prompt, having first obtained it via a TIS
4043 * or CryptoCard exchange if we're doing TIS or CryptoCard
4044 * authentication.
4045 */
edd0cb8a 4046 {
4047 int ret; /* need not be kept over crReturn */
4048 ret = get_userpass_input(s->cur_prompt, NULL, 0);
4049 while (ret < 0) {
4050 ssh->send_ok = 1;
4051 crWaitUntil(!pktin);
4052 ret = get_userpass_input(s->cur_prompt, in, inlen);
4053 ssh->send_ok = 0;
4054 }
4055 if (!ret) {
32874aea 4056 /*
edd0cb8a 4057 * Failed to get a password (for example
32874aea 4058 * because one was supplied on the command line
4059 * which has already failed to work). Terminate.
4060 */
edd0cb8a 4061 free_prompts(s->cur_prompt);
4062 ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
4063 crStop(0);
32874aea 4064 }
32874aea 4065 }
4066
edd0cb8a 4067 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
32874aea 4068 /*
edd0cb8a 4069 * Defence against traffic analysis: we send a
4070 * whole bunch of packets containing strings of
4071 * different lengths. One of these strings is the
4072 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
4073 * The others are all random data in
4074 * SSH1_MSG_IGNORE packets. This way a passive
4075 * listener can't tell which is the password, and
4076 * hence can't deduce the password length.
4077 *
4078 * Anybody with a password length greater than 16
4079 * bytes is going to have enough entropy in their
4080 * password that a listener won't find it _that_
4081 * much help to know how long it is. So what we'll
4082 * do is:
4083 *
4084 * - if password length < 16, we send 15 packets
4085 * containing string lengths 1 through 15
4086 *
4087 * - otherwise, we let N be the nearest multiple
4088 * of 8 below the password length, and send 8
4089 * packets containing string lengths N through
4090 * N+7. This won't obscure the order of
4091 * magnitude of the password length, but it will
4092 * introduce a bit of extra uncertainty.
4093 *
bf982899 4094 * A few servers can't deal with SSH1_MSG_IGNORE, at
4095 * least in this context. For these servers, we need
4096 * an alternative defence. We make use of the fact
4097 * that the password is interpreted as a C string:
4098 * so we can append a NUL, then some random data.
edd0cb8a 4099 *
bf982899 4100 * A few servers can deal with neither SSH1_MSG_IGNORE
4101 * here _nor_ a padded password string.
4102 * For these servers we are left with no defences
edd0cb8a 4103 * against password length sniffing.
32874aea 4104 */
bf982899 4105 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
4106 !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
32874aea 4107 /*
edd0cb8a 4108 * The server can deal with SSH1_MSG_IGNORE, so
4109 * we can use the primary defence.
32874aea 4110 */
edd0cb8a 4111 int bottom, top, pwlen, i;
4112 char *randomstr;
32874aea 4113
edd0cb8a 4114 pwlen = strlen(s->cur_prompt->prompts[0]->result);
4115 if (pwlen < 16) {
4116 bottom = 0; /* zero length passwords are OK! :-) */
4117 top = 15;
4118 } else {
4119 bottom = pwlen & ~7;
4120 top = bottom + 7;
4121 }
32874aea 4122
edd0cb8a 4123 assert(pwlen >= bottom && pwlen <= top);
32874aea 4124
edd0cb8a 4125 randomstr = snewn(top + 1, char);
32874aea 4126
edd0cb8a 4127 for (i = bottom; i <= top; i++) {
4128 if (i == pwlen) {
4129 defer_packet(ssh, s->pwpkt_type,
4130 PKTT_PASSWORD, PKT_STR,
4131 s->cur_prompt->prompts[0]->result,
4132 PKTT_OTHER, PKT_END);
4133 } else {
4134 for (j = 0; j < i; j++) {
4135 do {
4136 randomstr[j] = random_byte();
4137 } while (randomstr[j] == '\0');
32874aea 4138 }
edd0cb8a 4139 randomstr[i] = '\0';
4140 defer_packet(ssh, SSH1_MSG_IGNORE,
4141 PKT_STR, randomstr, PKT_END);
32874aea 4142 }
edd0cb8a 4143 }
4144 logevent("Sending password with camouflage packets");
4145 ssh_pkt_defersend(ssh);
4146 sfree(randomstr);
4147 }
4148 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
4149 /*
4150 * The server can't deal with SSH1_MSG_IGNORE
4151 * but can deal with padded passwords, so we
4152 * can use the secondary defence.
4153 */
4154 char string[64];
4155 char *ss;
4156 int len;
4157
4158 len = strlen(s->cur_prompt->prompts[0]->result);
4159 if (len < sizeof(string)) {
4160 ss = string;
4161 strcpy(string, s->cur_prompt->prompts[0]->result);
4162 len++; /* cover the zero byte */
4163 while (len < sizeof(string)) {
4164 string[len++] = (char) random_byte();
bd358db1 4165 }
bd358db1 4166 } else {
edd0cb8a 4167 ss = s->cur_prompt->prompts[0]->result;
32874aea 4168 }
edd0cb8a 4169 logevent("Sending length-padded password");
9a10ecf4 4170 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
edd0cb8a 4171 PKT_INT, len, PKT_DATA, ss, len,
4172 PKTT_OTHER, PKT_END);
4173 } else {
4174 /*
bf982899 4175 * The server is believed unable to cope with
4176 * any of our password camouflage methods.
edd0cb8a 4177 */
4178 int len;
4179 len = strlen(s->cur_prompt->prompts[0]->result);
4180 logevent("Sending unpadded password");
4181 send_packet(ssh, s->pwpkt_type,
4182 PKTT_PASSWORD, PKT_INT, len,
4183 PKT_DATA, s->cur_prompt->prompts[0]->result, len,
4184 PKTT_OTHER, PKT_END);
32874aea 4185 }
edd0cb8a 4186 } else {
4187 send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
4188 PKT_STR, s->cur_prompt->prompts[0]->result,
4189 PKTT_OTHER, PKT_END);
32874aea 4190 }
c5e9c988 4191 logevent("Sent password");
edd0cb8a 4192 free_prompts(s->cur_prompt);
ff3187f6 4193 crWaitUntil(pktin);
4194 if (pktin->type == SSH1_SMSG_FAILURE) {
32874aea 4195 if (flags & FLAG_VERBOSE)
51470298 4196 c_write_str(ssh, "Access denied\r\n");
c5e9c988 4197 logevent("Authentication refused");
ff3187f6 4198 } else if (pktin->type != SSH1_SMSG_SUCCESS) {
4199 bombout(("Strange packet received, type %d", pktin->type));
7ffdbc1a 4200 crStop(0);
374330e2 4201 }
4202 }
4203
edd0cb8a 4204 /* Clear up */
4205 if (s->publickey_blob) {
4206 sfree(s->publickey_blob);
4207 sfree(s->publickey_comment);
4208 }
4209
c5e9c988 4210 logevent("Authentication successful");
4211
fb09bf1c 4212 crFinish(1);
4213}
4214
bc06669b 4215static void ssh_channel_try_eof(struct ssh_channel *c)
4216{
4217 Ssh ssh = c->ssh;
4218 assert(c->pending_eof); /* precondition for calling us */
4219 if (c->halfopen)
4220 return; /* can't close: not even opened yet */
4221 if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
4222 return; /* can't send EOF: pending outgoing data */
4223
4224 if (ssh->version == 1) {
4225 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4226 PKT_END);
4227 c->closes |= CLOSES_SENT_EOF;
4228 } else {
4229 struct Packet *pktout;
4230 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
4231 ssh2_pkt_adduint32(pktout, c->remoteid);
4232 ssh2_pkt_send(ssh, pktout);
4233 c->closes |= CLOSES_SENT_EOF;
4234 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes)) {
4235 /*
4236 * Also send MSG_CLOSE.
4237 */
4238 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4239 ssh2_pkt_adduint32(pktout, c->remoteid);
4240 ssh2_pkt_send(ssh, pktout);
4241 c->closes |= CLOSES_SENT_CLOSE;
4242 }
4243 }
4244 c->pending_eof = FALSE; /* we've sent it now */
4245}
4246
4247void sshfwd_write_eof(struct ssh_channel *c)
32874aea 4248{
51470298 4249 Ssh ssh = c->ssh;
4250
1ef619ae 4251 if (ssh->state == SSH_STATE_CLOSED)
36f94d1f 4252 return;
36f94d1f 4253
bc06669b 4254 if (c->closes & CLOSES_SENT_EOF)
4255 return;
78280721 4256
bc06669b 4257 c->pending_eof = TRUE;
4258 ssh_channel_try_eof(c);
32874aea 4259}
4260
c6b41791 4261void sshfwd_unclean_close(struct ssh_channel *c)
4262{
4263 Ssh ssh = c->ssh;
4264 struct Packet *pktout;
4265
4266 if (ssh->state == SSH_STATE_CLOSED)
4267 return;
4268
96210393 4269 if (!(c->closes & CLOSES_SENT_CLOSE)) {
4270 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
4271 ssh2_pkt_adduint32(pktout, c->remoteid);
4272 ssh2_pkt_send(ssh, pktout);
4273 c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
4274 }
c6b41791 4275
c6b41791 4276 switch (c->type) {
4277 case CHAN_X11:
4278 x11_close(c->u.x11.s);
4279 break;
4280 case CHAN_SOCKDATA:
4281 case CHAN_SOCKDATA_DORMANT:
4282 pfd_close(c->u.pfd.s);
4283 break;
4284 }
4285 c->type = CHAN_ZOMBIE;
96210393 4286
c6b41791 4287 ssh2_channel_check_close(c);
4288}
4289
5471d09a 4290int sshfwd_write(struct ssh_channel *c, char *buf, int len)
32874aea 4291{
51470298 4292 Ssh ssh = c->ssh;
4293
1ef619ae 4294 if (ssh->state == SSH_STATE_CLOSED)
36f94d1f 4295 return 0;
36f94d1f 4296
51470298 4297 if (ssh->version == 1) {
4298 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
32874aea 4299 PKT_INT, c->remoteid,
a2724fba 4300 PKT_INT, len, PKTT_DATA, PKT_DATA, buf, len,
9a10ecf4 4301 PKTT_OTHER, PKT_END);
5471d09a 4302 /*
2e85c969 4303 * In SSH-1 we can return 0 here - implying that forwarded
5471d09a 4304 * connections are never individually throttled - because
4305 * the only circumstance that can cause throttling will be
4306 * the whole SSH connection backing up, in which case
4307 * _everything_ will be throttled as a whole.
4308 */
4309 return 0;
783415f8 4310 } else {
32874aea 4311 ssh2_add_channel_data(c, buf, len);
5471d09a 4312 return ssh2_try_send(c);
4313 }
4314}
4315
4316void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
4317{
51470298 4318 Ssh ssh = c->ssh;
ff68564b 4319 int buflimit;
51470298 4320
1ef619ae 4321 if (ssh->state == SSH_STATE_CLOSED)
36f94d1f 4322 return;
36f94d1f 4323
51470298 4324 if (ssh->version == 1) {
ff68564b 4325 buflimit = SSH1_BUFFER_LIMIT;
5471d09a 4326 } else {
ff68564b 4327 buflimit = c->v.v2.locmaxwin;
4328 ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
4329 }
4330 if (c->throttling_conn && bufsize <= buflimit) {
4331 c->throttling_conn = 0;
4332 ssh_throttle_conn(ssh, -1);
783415f8 4333 }
9c964e85 4334}
4335
06fadff5 4336static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
4337{
4338 struct queued_handler *qh = ssh->qhead;
4339
4340 assert(qh != NULL);
4341
4342 assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
4343
4344 if (qh->msg1 > 0) {
4345 assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
4346 ssh->packet_dispatch[qh->msg1] = NULL;
4347 }
4348 if (qh->msg2 > 0) {
4349 assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
4350 ssh->packet_dispatch[qh->msg2] = NULL;
4351 }
4352
4353 if (qh->next) {
4354 ssh->qhead = qh->next;
4355
4356 if (ssh->qhead->msg1 > 0) {
4357 assert(ssh->packet_dispatch[ssh->qhead->msg1] == NULL);
4358 ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
4359 }
4360 if (ssh->qhead->msg2 > 0) {
4361 assert(ssh->packet_dispatch[ssh->qhead->msg2] == NULL);
4362 ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
4363 }
4364 } else {
4365 ssh->qhead = ssh->qtail = NULL;
4366 ssh->packet_dispatch[pktin->type] = NULL;
4367 }
4368
4369 qh->handler(ssh, pktin, qh->ctx);
4370
4371 sfree(qh);
4372}
4373
4374static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
4375 chandler_fn_t handler, void *ctx)
4376{
4377 struct queued_handler *qh;
4378
4379 qh = snew(struct queued_handler);
4380 qh->msg1 = msg1;
4381 qh->msg2 = msg2;
4382 qh->handler = handler;
4383 qh->ctx = ctx;
4384 qh->next = NULL;
4385
4386 if (ssh->qtail == NULL) {
4387 ssh->qhead = qh;
4388
4389 if (qh->msg1 > 0) {
4390 assert(ssh->packet_dispatch[qh->msg1] == NULL);
4391 ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
4392 }
4393 if (qh->msg2 > 0) {
4394 assert(ssh->packet_dispatch[qh->msg2] == NULL);
4395 ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
4396 }
4397 } else {
4398 ssh->qtail->next = qh;
4399 }
4400 ssh->qtail = qh;
4401}
4402
4403static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
4404{
4405 struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
4406
4407 if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
4408 SSH2_MSG_REQUEST_SUCCESS)) {
4409 logeventf(ssh, "Remote port forwarding from %s enabled",
4410 pf->sportdesc);
4411 } else {
4412 logeventf(ssh, "Remote port forwarding from %s refused",
4413 pf->sportdesc);
4414
4415 rpf = del234(ssh->rportfwds, pf);
4416 assert(rpf == pf);
8aea57fd 4417 pf->pfrec->remote = NULL;
fda2feb1 4418 free_rportfwd(pf);
06fadff5 4419 }
4420}
4421
4a693cfc 4422static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
06fadff5 4423{
84328ddb 4424 struct ssh_portfwd *epf;
4425 int i;
4a693cfc 4426 char *key, *val;
06fadff5 4427
fda2feb1 4428 if (!ssh->portfwds) {
4429 ssh->portfwds = newtree234(ssh_portcmp);
4430 } else {
4431 /*
4432 * Go through the existing port forwardings and tag them
84328ddb 4433 * with status==DESTROY. Any that we want to keep will be
4434 * re-enabled (status==KEEP) as we go through the
4435 * configuration and find out which bits are the same as
4436 * they were before.
fda2feb1 4437 */
4438 struct ssh_portfwd *epf;
4439 int i;
4440 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
84328ddb 4441 epf->status = DESTROY;
fda2feb1 4442 }
4443
4a693cfc 4444 for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
4445 val != NULL;
4446 val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
4447 char *kp, *kp2, *vp, *vp2;
84328ddb 4448 char address_family, type;
4449 int sport,dport,sserv,dserv;
4a693cfc 4450 char *sports, *dports, *saddr, *host;
4451
4452 kp = key;
84328ddb 4453
05581745 4454 address_family = 'A';
4455 type = 'L';
4a693cfc 4456 if (*kp == 'A' || *kp == '4' || *kp == '6')
4457 address_family = *kp++;
4458 if (*kp == 'L' || *kp == 'R')
4459 type = *kp++;
4460
4461 if ((kp2 = strchr(kp, ':')) != NULL) {
4462 /*
4463 * There's a colon in the middle of the source port
4464 * string, which means that the part before it is
4465 * actually a source address.
4466 */
4467 saddr = dupprintf("%.*s", (int)(kp2 - kp), kp);
4468 sports = kp2+1;
06fadff5 4469 } else {
4a693cfc 4470 saddr = NULL;
4471 sports = kp;
06fadff5 4472 }
4473 sport = atoi(sports);
4474 sserv = 0;
4475 if (sport == 0) {
4476 sserv = 1;
4477 sport = net_service_lookup(sports);
4478 if (!sport) {
4479 logeventf(ssh, "Service lookup failed for source"
4480 " port \"%s\"", sports);
4481 }
4482 }
4a693cfc 4483
4484 if (type == 'L' && !strcmp(val, "D")) {
4485 /* dynamic forwarding */
4486 host = NULL;
4487 dports = NULL;
4488 dport = -1;
4489 dserv = 0;
4490 type = 'D';
4491 } else {
4492 /* ordinary forwarding */
4493 vp = val;
4494 vp2 = vp + strcspn(vp, ":");
4495 host = dupprintf("%.*s", (int)(vp2 - vp), vp);
4496 if (vp2)
4497 vp2++;
4498 dports = vp2;
4499 dport = atoi(dports);
4500 dserv = 0;
4501 if (dport == 0) {
4502 dserv = 1;
4503 dport = net_service_lookup(dports);
4504 if (!dport) {
4505 logeventf(ssh, "Service lookup failed for destination"
4506 " port \"%s\"", dports);
4507 }
4508 }
4509 }
4510
06fadff5 4511 if (sport && dport) {
4512 /* Set up a description of the source port. */
fda2feb1 4513 struct ssh_portfwd *pfrec, *epfrec;
fda2feb1 4514
4515 pfrec = snew(struct ssh_portfwd);
4516 pfrec->type = type;
4a693cfc 4517 pfrec->saddr = saddr;
3fe92132 4518 pfrec->sserv = sserv ? dupstr(sports) : NULL;
fda2feb1 4519 pfrec->sport = sport;
4a693cfc 4520 pfrec->daddr = host;
3fe92132 4521 pfrec->dserv = dserv ? dupstr(dports) : NULL;
fda2feb1 4522 pfrec->dport = dport;
4523 pfrec->local = NULL;
4524 pfrec->remote = NULL;
05581745 4525 pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
4526 address_family == '6' ? ADDRTYPE_IPV6 :
4527 ADDRTYPE_UNSPEC);
fda2feb1 4528
4529 epfrec = add234(ssh->portfwds, pfrec);
4530 if (epfrec != pfrec) {
c00c1931 4531 if (epfrec->status == DESTROY) {
4532 /*
4533 * We already have a port forwarding up and running
4534 * with precisely these parameters. Hence, no need
4535 * to do anything; simply re-tag the existing one
4536 * as KEEP.
4537 */
4538 epfrec->status = KEEP;
4539 }
fda2feb1 4540 /*
c00c1931 4541 * Anything else indicates that there was a duplicate
4542 * in our input, which we'll silently ignore.
fda2feb1 4543 */
fda2feb1 4544 free_portfwd(pfrec);
84328ddb 4545 } else {
4546 pfrec->status = CREATE;
4547 }
4a693cfc 4548 } else {
4549 sfree(saddr);
4550 sfree(host);
84328ddb 4551 }
4552 }
4553
4554 /*
4555 * Now go through and destroy any port forwardings which were
4556 * not re-enabled.
4557 */
4558 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4559 if (epf->status == DESTROY) {
4560 char *message;
4561
4562 message = dupprintf("%s port forwarding from %s%s%d",
4563 epf->type == 'L' ? "local" :
4564 epf->type == 'R' ? "remote" : "dynamic",
4565 epf->saddr ? epf->saddr : "",
4566 epf->saddr ? ":" : "",
4567 epf->sport);
4568
4569 if (epf->type != 'D') {
4570 char *msg2 = dupprintf("%s to %s:%d", message,
4571 epf->daddr, epf->dport);
4572 sfree(message);
4573 message = msg2;
4574 }
4575
4576 logeventf(ssh, "Cancelling %s", message);
4577 sfree(message);
4578
8aea57fd 4579 /* epf->remote or epf->local may be NULL if setting up a
4580 * forwarding failed. */
84328ddb 4581 if (epf->remote) {
4582 struct ssh_rportfwd *rpf = epf->remote;
4583 struct Packet *pktout;
4584
4585 /*
4586 * Cancel the port forwarding at the server
4587 * end.
4588 */
4589 if (ssh->version == 1) {
4590 /*
4591 * We cannot cancel listening ports on the
2e85c969 4592 * server side in SSH-1! There's no message
84328ddb 4593 * to support it. Instead, we simply remove
4594 * the rportfwd record from the local end
4595 * so that any connections the server tries
4596 * to make on it are rejected.
4597 */
4598 } else {
4599 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4600 ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
4601 ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
4602 if (epf->saddr) {
4603 ssh2_pkt_addstring(pktout, epf->saddr);
4a693cfc 4604 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
4605 /* XXX: rport_acceptall may not represent
5188540b 4606 * what was used to open the original connection,
4607 * since it's reconfigurable. */
84328ddb 4608 ssh2_pkt_addstring(pktout, "0.0.0.0");
4609 } else {
4610 ssh2_pkt_addstring(pktout, "127.0.0.1");
4611 }
4612 ssh2_pkt_adduint32(pktout, epf->sport);
4613 ssh2_pkt_send(ssh, pktout);
4614 }
4615
4616 del234(ssh->rportfwds, rpf);
4617 free_rportfwd(rpf);
4618 } else if (epf->local) {
4619 pfd_terminate(epf->local);
4620 }
4621
4622 delpos234(ssh->portfwds, i);
4623 free_portfwd(epf);
4624 i--; /* so we don't skip one in the list */
4625 }
4626
4627 /*
4628 * And finally, set up any new port forwardings (status==CREATE).
4629 */
4630 for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
4631 if (epf->status == CREATE) {
4632 char *sportdesc, *dportdesc;
3fe92132 4633 sportdesc = dupprintf("%s%s%s%s%d%s",
84328ddb 4634 epf->saddr ? epf->saddr : "",
4635 epf->saddr ? ":" : "",
3fe92132 4636 epf->sserv ? epf->sserv : "",
4637 epf->sserv ? "(" : "",
4638 epf->sport,
4639 epf->sserv ? ")" : "");
84328ddb 4640 if (epf->type == 'D') {
4641 dportdesc = NULL;
4642 } else {
3fe92132 4643 dportdesc = dupprintf("%s:%s%s%d%s",
4644 epf->daddr,
4645 epf->dserv ? epf->dserv : "",
4646 epf->dserv ? "(" : "",
4647 epf->dport,
4648 epf->dserv ? ")" : "");
84328ddb 4649 }
05581745 4650
84328ddb 4651 if (epf->type == 'L') {
4652 const char *err = pfd_addforward(epf->daddr, epf->dport,
4653 epf->saddr, epf->sport,
4a693cfc 4654 ssh, conf,
84328ddb 4655 &epf->local,
4656 epf->addressfamily);
4657
4658 logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
4659 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4660 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4661 sportdesc, dportdesc,
4662 err ? " failed: " : "", err ? err : "");
4663 } else if (epf->type == 'D') {
06fadff5 4664 const char *err = pfd_addforward(NULL, -1,
84328ddb 4665 epf->saddr, epf->sport,
4a693cfc 4666 ssh, conf,
84328ddb 4667 &epf->local,
4668 epf->addressfamily);
4669
4670 logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
4671 epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
4672 epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
4673 sportdesc,
4674 err ? " failed: " : "", err ? err : "");
06fadff5 4675 } else {
4676 struct ssh_rportfwd *pf;
4677
4678 /*
4679 * Ensure the remote port forwardings tree exists.
4680 */
4681 if (!ssh->rportfwds) {
4682 if (ssh->version == 1)
4683 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
4684 else
4685 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
4686 }
4687
4688 pf = snew(struct ssh_rportfwd);
84328ddb 4689 strncpy(pf->dhost, epf->daddr, lenof(pf->dhost)-1);
4690 pf->dhost[lenof(pf->dhost)-1] = '\0';
4691 pf->dport = epf->dport;
4692 pf->sport = epf->sport;
06fadff5 4693 if (add234(ssh->rportfwds, pf) != pf) {
4694 logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
84328ddb 4695 epf->daddr, epf->dport);
06fadff5 4696 sfree(pf);
4697 } else {
4698 logeventf(ssh, "Requesting remote port %s"
84328ddb 4699 " forward to %s", sportdesc, dportdesc);
06fadff5 4700
4701 pf->sportdesc = sportdesc;
4702 sportdesc = NULL;
84328ddb 4703 epf->remote = pf;
4704 pf->pfrec = epf;
06fadff5 4705
4706 if (ssh->version == 1) {
4707 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
84328ddb 4708 PKT_INT, epf->sport,
4709 PKT_STR, epf->daddr,
4710 PKT_INT, epf->dport,
06fadff5 4711 PKT_END);
4712 ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
4713 SSH1_SMSG_FAILURE,
4714 ssh_rportfwd_succfail, pf);
4715 } else {
4716 struct Packet *pktout;
4717 pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
4718 ssh2_pkt_addstring(pktout, "tcpip-forward");
4719 ssh2_pkt_addbool(pktout, 1);/* want reply */
84328ddb 4720 if (epf->saddr) {
4721 ssh2_pkt_addstring(pktout, epf->saddr);
4a693cfc 4722 } else if (conf_get_int(conf, CONF_rport_acceptall)) {
06fadff5 4723 ssh2_pkt_addstring(pktout, "0.0.0.0");
4724 } else {
4725 ssh2_pkt_addstring(pktout, "127.0.0.1");
4726 }
84328ddb 4727 ssh2_pkt_adduint32(pktout, epf->sport);
06fadff5 4728 ssh2_pkt_send(ssh, pktout);
4729
4730 ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
4731 SSH2_MSG_REQUEST_FAILURE,
4732 ssh_rportfwd_succfail, pf);
4733 }
4734 }
4735 }
4736 sfree(sportdesc);
84328ddb 4737 sfree(dportdesc);
06fadff5 4738 }
06fadff5 4739}
4740
51df0ab5 4741static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
4742{
4743 char *string;
4744 int stringlen, bufsize;
4745
4746 ssh_pkt_getstring(pktin, &string, &stringlen);
4747 if (string == NULL) {
4748 bombout(("Incoming terminal data packet was badly formed"));
4749 return;
4750 }
4751
4752 bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
4753 string, stringlen);
4754 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
4755 ssh->v1_stdout_throttling = 1;
ff68564b 4756 ssh_throttle_conn(ssh, +1);
51df0ab5 4757 }
4758}
4759
4760static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
4761{
4762 /* Remote side is trying to open a channel to talk to our
4763 * X-Server. Give them back a local channel number. */
4764 struct ssh_channel *c;
4765 int remoteid = ssh_pkt_getuint32(pktin);
4766
4767 logevent("Received X11 connect request");
4768 /* Refuse if X11 forwarding is disabled. */
4769 if (!ssh->X11_fwd_enabled) {
4770 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4771 PKT_INT, remoteid, PKT_END);
4772 logevent("Rejected X11 connect request");
4773 } else {
4774 c = snew(struct ssh_channel);
4775 c->ssh = ssh;
4776
8def70c3 4777 if (x11_init(&c->u.x11.s, ssh->x11disp, c,
4a693cfc 4778 NULL, -1, ssh->conf) != NULL) {
51df0ab5 4779 logevent("Opening X11 forward connection failed");
4780 sfree(c);
4781 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4782 PKT_INT, remoteid, PKT_END);
4783 } else {
4784 logevent
4785 ("Opening X11 forward connection succeeded");
4786 c->remoteid = remoteid;
64d6ff88 4787 c->halfopen = FALSE;
51df0ab5 4788 c->localid = alloc_channel_id(ssh);
4789 c->closes = 0;
bc06669b 4790 c->pending_eof = FALSE;
ff68564b 4791 c->throttling_conn = 0;
51df0ab5 4792 c->type = CHAN_X11; /* identify channel type */
4793 add234(ssh->channels, c);
4794 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4795 PKT_INT, c->remoteid, PKT_INT,
4796 c->localid, PKT_END);
4797 logevent("Opened X11 forward channel");
4798 }
4799 }
4800}
4801
4802static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
4803{
4804 /* Remote side is trying to open a channel to talk to our
4805 * agent. Give them back a local channel number. */
4806 struct ssh_channel *c;
4807 int remoteid = ssh_pkt_getuint32(pktin);
4808
4809 /* Refuse if agent forwarding is disabled. */
4810 if (!ssh->agentfwd_enabled) {
4811 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4812 PKT_INT, remoteid, PKT_END);
4813 } else {
4814 c = snew(struct ssh_channel);
4815 c->ssh = ssh;
4816 c->remoteid = remoteid;
64d6ff88 4817 c->halfopen = FALSE;
51df0ab5 4818 c->localid = alloc_channel_id(ssh);
4819 c->closes = 0;
bc06669b 4820 c->pending_eof = FALSE;
ff68564b 4821 c->throttling_conn = 0;
51df0ab5 4822 c->type = CHAN_AGENT; /* identify channel type */
4823 c->u.a.lensofar = 0;
bc06669b 4824 c->u.a.message = NULL;
51df0ab5 4825 add234(ssh->channels, c);
4826 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4827 PKT_INT, c->remoteid, PKT_INT, c->localid,
4828 PKT_END);
4829 }
4830}
4831
4832static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
4833{
4834 /* Remote side is trying to open a channel to talk to a
4835 * forwarded port. Give them back a local channel number. */
4836 struct ssh_channel *c;
05581745 4837 struct ssh_rportfwd pf, *pfp;
51df0ab5 4838 int remoteid;
4839 int hostsize, port;
fb983202 4840 char *host;
51df0ab5 4841 const char *e;
4842 c = snew(struct ssh_channel);
4843 c->ssh = ssh;
4844
4845 remoteid = ssh_pkt_getuint32(pktin);
4846 ssh_pkt_getstring(pktin, &host, &hostsize);
4847 port = ssh_pkt_getuint32(pktin);
4848
4849 if (hostsize >= lenof(pf.dhost))
4850 hostsize = lenof(pf.dhost)-1;
4851 memcpy(pf.dhost, host, hostsize);
4852 pf.dhost[hostsize] = '\0';
4853 pf.dport = port;
05581745 4854 pfp = find234(ssh->rportfwds, &pf, NULL);
51df0ab5 4855
05581745 4856 if (pfp == NULL) {
fb983202 4857 logeventf(ssh, "Rejected remote port open request for %s:%d",
4858 pf.dhost, port);
51df0ab5 4859 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4860 PKT_INT, remoteid, PKT_END);
4861 } else {
fb983202 4862 logeventf(ssh, "Received remote port open request for %s:%d",
4863 pf.dhost, port);
51df0ab5 4864 e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
4a693cfc 4865 c, ssh->conf, pfp->pfrec->addressfamily);
51df0ab5 4866 if (e != NULL) {
fb983202 4867 logeventf(ssh, "Port open failed: %s", e);
51df0ab5 4868 sfree(c);
4869 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
4870 PKT_INT, remoteid, PKT_END);
4871 } else {
4872 c->remoteid = remoteid;
64d6ff88 4873 c->halfopen = FALSE;
51df0ab5 4874 c->localid = alloc_channel_id(ssh);
4875 c->closes = 0;
bc06669b 4876 c->pending_eof = FALSE;
ff68564b 4877 c->throttling_conn = 0;
51df0ab5 4878 c->type = CHAN_SOCKDATA; /* identify channel type */
4879 add234(ssh->channels, c);
4880 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
4881 PKT_INT, c->remoteid, PKT_INT,
4882 c->localid, PKT_END);
4883 logevent("Forwarded port opened successfully");
4884 }
4885 }
4886}
4887
4888static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
4889{
4890 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4891 unsigned int localid = ssh_pkt_getuint32(pktin);
4892 struct ssh_channel *c;
4893
4894 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4895 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4896 c->remoteid = localid;
64d6ff88 4897 c->halfopen = FALSE;
51df0ab5 4898 c->type = CHAN_SOCKDATA;
ff68564b 4899 c->throttling_conn = 0;
51df0ab5 4900 pfd_confirm(c->u.pfd.s);
4901 }
4902
bc06669b 4903 if (c && c->pending_eof) {
51df0ab5 4904 /*
4905 * We have a pending close on this channel,
4906 * which we decided on before the server acked
4907 * the channel open. So now we know the
4908 * remoteid, we can close it again.
4909 */
bc06669b 4910 ssh_channel_try_eof(c);
51df0ab5 4911 }
4912}
4913
4914static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
4915{
4916 unsigned int remoteid = ssh_pkt_getuint32(pktin);
4917 struct ssh_channel *c;
4918
4919 c = find234(ssh->channels, &remoteid, ssh_channelfind);
4920 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
4921 logevent("Forwarded connection refused by server");
4922 pfd_close(c->u.pfd.s);
4923 del234(ssh->channels, c);
4924 sfree(c);
4925 }
4926}
4927
4928static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
4929{
4930 /* Remote side closes a channel. */
4931 unsigned i = ssh_pkt_getuint32(pktin);
4932 struct ssh_channel *c;
4933 c = find234(ssh->channels, &i, ssh_channelfind);
64d6ff88 4934 if (c && !c->halfopen) {
51df0ab5 4935
bc06669b 4936 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
4937 !(c->closes & CLOSES_RCVD_EOF)) {
4938 /*
4939 * Received CHANNEL_CLOSE, which we translate into
4940 * outgoing EOF.
4941 */
4942 int send_close = FALSE;
4943
4944 c->closes |= CLOSES_RCVD_EOF;
4945
4946 switch (c->type) {
4947 case CHAN_X11:
4948 if (c->u.x11.s)
4949 x11_send_eof(c->u.x11.s);
4950 else
4951 send_close = TRUE;
4952 case CHAN_SOCKDATA:
4953 if (c->u.pfd.s)
4954 x11_send_eof(c->u.pfd.s);
4955 else
4956 send_close = TRUE;
4957 case CHAN_AGENT:
4958 send_close = TRUE;
4959 }
51df0ab5 4960
bc06669b 4961 if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
4962 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4963 PKT_END);
4964 c->closes |= CLOSES_SENT_EOF;
4965 }
4966 }
4967
4968 if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
4969 !(c->closes & CLOSES_RCVD_CLOSE)) {
4970
4971 if (!(c->closes & CLOSES_SENT_EOF)) {
4972 bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
4973 " for which we never sent CHANNEL_CLOSE\n", i));
4974 }
4975
4976 c->closes |= CLOSES_RCVD_CLOSE;
4977 }
4978
4979 if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
4980 !(c->closes & CLOSES_SENT_CLOSE)) {
4981 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
4982 PKT_INT, c->remoteid, PKT_END);
4983 c->closes |= CLOSES_SENT_CLOSE;
4984 }
4985
4986 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
4987 ssh_channel_destroy(c);
51df0ab5 4988 } else {
4989 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
4990 pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
4991 "_CONFIRMATION", c ? "half-open" : "nonexistent",
4992 i));
4993 }
4994}
4995
4996static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
4997{
4998 /* Data sent down one of our channels. */
4999 int i = ssh_pkt_getuint32(pktin);
5000 char *p;
6d44acc9 5001 int len;
51df0ab5 5002 struct ssh_channel *c;
5003
5004 ssh_pkt_getstring(pktin, &p, &len);
5005
5006 c = find234(ssh->channels, &i, ssh_channelfind);
5007 if (c) {
5008 int bufsize = 0;
5009 switch (c->type) {
5010 case CHAN_X11:
5011 bufsize = x11_send(c->u.x11.s, p, len);
5012 break;
5013 case CHAN_SOCKDATA:
5014 bufsize = pfd_send(c->u.pfd.s, p, len);
5015 break;
5016 case CHAN_AGENT:
5017 /* Data for an agent message. Buffer it. */
5018 while (len > 0) {
5019 if (c->u.a.lensofar < 4) {
62ddb51e 5020 unsigned int l = min(4 - c->u.a.lensofar, (unsigned)len);
51df0ab5 5021 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
5022 l);
5023 p += l;
5024 len -= l;
5025 c->u.a.lensofar += l;
5026 }
5027 if (c->u.a.lensofar == 4) {
5028 c->u.a.totallen =
5029 4 + GET_32BIT(c->u.a.msglen);
5030 c->u.a.message = snewn(c->u.a.totallen,
5031 unsigned char);
5032 memcpy(c->u.a.message, c->u.a.msglen, 4);
5033 }
5034 if (c->u.a.lensofar >= 4 && len > 0) {
aa63ab7e 5035 unsigned int l =
51df0ab5 5036 min(c->u.a.totallen - c->u.a.lensofar,
62ddb51e 5037 (unsigned)len);
51df0ab5 5038 memcpy(c->u.a.message + c->u.a.lensofar, p,
5039 l);
5040 p += l;
5041 len -= l;
5042 c->u.a.lensofar += l;
5043 }
5044 if (c->u.a.lensofar == c->u.a.totallen) {
5045 void *reply;
5046 int replylen;
5047 if (agent_query(c->u.a.message,
5048 c->u.a.totallen,
5049 &reply, &replylen,
5050 ssh_agentf_callback, c))
5051 ssh_agentf_callback(c, reply, replylen);
5052 sfree(c->u.a.message);
5053 c->u.a.lensofar = 0;
5054 }
5055 }
5056 bufsize = 0; /* agent channels never back up */
5057 break;
5058 }
ff68564b 5059 if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
5060 c->throttling_conn = 1;
5061 ssh_throttle_conn(ssh, +1);
51df0ab5 5062 }
5063 }
5064}
5065
5066static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
5067{
51df0ab5 5068 ssh->exitcode = ssh_pkt_getuint32(pktin);
fb983202 5069 logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
51df0ab5 5070 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
5071 /*
5072 * In case `helpful' firewalls or proxies tack
5073 * extra human-readable text on the end of the
5074 * session which we might mistake for another
5075 * encrypted packet, we close the session once
5076 * we've sent EXIT_CONFIRMATION.
5077 */
9e296bfa 5078 ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
51df0ab5 5079}
5080
c6ccd5c2 5081/* Helper function to deal with sending tty modes for REQUEST_PTY */
5082static void ssh1_send_ttymode(void *data, char *mode, char *val)
5083{
5084 struct Packet *pktout = (struct Packet *)data;
5085 int i = 0;
5086 unsigned int arg = 0;
5087 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
5088 if (i == lenof(ssh_ttymodes)) return;
5089 switch (ssh_ttymodes[i].type) {
5090 case TTY_OP_CHAR:
5091 arg = ssh_tty_parse_specchar(val);
5092 break;
5093 case TTY_OP_BOOL:
5094 arg = ssh_tty_parse_boolean(val);
5095 break;
5096 }
5097 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
5098 ssh2_pkt_addbyte(pktout, arg);
5099}
5100
5101
b09eaa88 5102static void do_ssh1_connection(Ssh ssh, unsigned char *in, int inlen,
5103 struct Packet *pktin)
32874aea 5104{
b09eaa88 5105 crBegin(ssh->do_ssh1_connection_crstate);
fb09bf1c 5106
51df0ab5 5107 ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
5108 ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
5109 ssh1_smsg_stdout_stderr_data;
5110
5111 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
5112 ssh1_msg_channel_open_confirmation;
5113 ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
5114 ssh1_msg_channel_open_failure;
5115 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
5116 ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
5117 ssh1_msg_channel_close;
5118 ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
5119 ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
5120
4a693cfc 5121 if (conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
32874aea 5122 logevent("Requesting agent forwarding");
51470298 5123 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
32874aea 5124 do {
5125 crReturnV;
ff3187f6 5126 } while (!pktin);
5127 if (pktin->type != SSH1_SMSG_SUCCESS
5128 && pktin->type != SSH1_SMSG_FAILURE) {
6b5cf8b4 5129 bombout(("Protocol confusion"));
7ffdbc1a 5130 crStopV;
ff3187f6 5131 } else if (pktin->type == SSH1_SMSG_FAILURE) {
32874aea 5132 logevent("Agent forwarding refused");
5133 } else {
5134 logevent("Agent forwarding enabled");
51470298 5135 ssh->agentfwd_enabled = TRUE;
51df0ab5 5136 ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
db7d555c 5137 }
dacbd0e8 5138 }
5139
4a693cfc 5140 if (conf_get_int(ssh->conf, CONF_x11_forward) &&
5141 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
5142 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
32874aea 5143 logevent("Requesting X11 forwarding");
f68353be 5144 /*
5145 * Note that while we blank the X authentication data here, we don't
5146 * take any special action to blank the start of an X11 channel,
5147 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
5148 * without having session blanking enabled is likely to leak your
5149 * cookie into the log.
5150 */
51470298 5151 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
5152 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
8def70c3 5153 PKT_STR, ssh->x11disp->remoteauthprotoname,
5154 PKTT_PASSWORD,
5155 PKT_STR, ssh->x11disp->remoteauthdatastring,
5156 PKTT_OTHER,
5157 PKT_INT, ssh->x11disp->screennum,
421d6835 5158 PKT_END);
32874aea 5159 } else {
51470298 5160 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
8def70c3 5161 PKT_STR, ssh->x11disp->remoteauthprotoname,
5162 PKTT_PASSWORD,
5163 PKT_STR, ssh->x11disp->remoteauthdatastring,
5164 PKTT_OTHER,
5165 PKT_END);
32874aea 5166 }
5167 do {
5168 crReturnV;
ff3187f6 5169 } while (!pktin);
5170 if (pktin->type != SSH1_SMSG_SUCCESS
5171 && pktin->type != SSH1_SMSG_FAILURE) {
6b5cf8b4 5172 bombout(("Protocol confusion"));
7ffdbc1a 5173 crStopV;
ff3187f6 5174 } else if (pktin->type == SSH1_SMSG_FAILURE) {
32874aea 5175 logevent("X11 forwarding refused");
5176 } else {
5177 logevent("X11 forwarding enabled");
51470298 5178 ssh->X11_fwd_enabled = TRUE;
51df0ab5 5179 ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
9c964e85 5180 }
5181 }
5182
4a693cfc 5183 ssh_setup_portfwd(ssh, ssh->conf);
06fadff5 5184 ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
d74d141c 5185
4a693cfc 5186 if (!conf_get_int(ssh->conf, CONF_nopty)) {
c6ccd5c2 5187 struct Packet *pkt;
a5dd8467 5188 /* Unpick the terminal-speed string. */
5189 /* XXX perhaps we should allow no speeds to be sent. */
db219738 5190 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
4a693cfc 5191 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
a5dd8467 5192 /* Send the pty request. */
c6ccd5c2 5193 pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
4a693cfc 5194 ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
c6ccd5c2 5195 ssh_pkt_adduint32(pkt, ssh->term_height);
5196 ssh_pkt_adduint32(pkt, ssh->term_width);
5197 ssh_pkt_adduint32(pkt, 0); /* width in pixels */
5198 ssh_pkt_adduint32(pkt, 0); /* height in pixels */
4a693cfc 5199 parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
c6ccd5c2 5200 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
5201 ssh_pkt_adduint32(pkt, ssh->ispeed);
5202 ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
5203 ssh_pkt_adduint32(pkt, ssh->ospeed);
5204 ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
5205 s_wrpkt(ssh, pkt);
51470298 5206 ssh->state = SSH_STATE_INTERMED;
32874aea 5207 do {
5208 crReturnV;
ff3187f6 5209 } while (!pktin);
5210 if (pktin->type != SSH1_SMSG_SUCCESS
5211 && pktin->type != SSH1_SMSG_FAILURE) {
6b5cf8b4 5212 bombout(("Protocol confusion"));
7ffdbc1a 5213 crStopV;
ff3187f6 5214 } else if (pktin->type == SSH1_SMSG_FAILURE) {
51470298 5215 c_write_str(ssh, "Server refused to allocate pty\r\n");
5216 ssh->editing = ssh->echoing = 1;
4a202fc6 5217 } else {
5218 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
5219 ssh->ospeed, ssh->ispeed);
5220 ssh->got_pty = TRUE;
5221 }
0965bee0 5222 } else {
51470298 5223 ssh->editing = ssh->echoing = 1;
374330e2 5224 }
5225
4a693cfc 5226 if (conf_get_int(ssh->conf, CONF_compression)) {
51470298 5227 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
32874aea 5228 do {
5229 crReturnV;
ff3187f6 5230 } while (!pktin);
5231 if (pktin->type != SSH1_SMSG_SUCCESS
5232 && pktin->type != SSH1_SMSG_FAILURE) {
6b5cf8b4 5233 bombout(("Protocol confusion"));
7ffdbc1a 5234 crStopV;
ff3187f6 5235 } else if (pktin->type == SSH1_SMSG_FAILURE) {
51470298 5236 c_write_str(ssh, "Server refused to compress\r\n");
32874aea 5237 }
4ba9b64b 5238 logevent("Started compression");
51470298 5239 ssh->v1_compressing = TRUE;
5366aed8 5240 ssh->cs_comp_ctx = zlib_compress_init();
5241 logevent("Initialised zlib (RFC1950) compression");
5242 ssh->sc_comp_ctx = zlib_decompress_init();
5243 logevent("Initialised zlib (RFC1950) decompression");
4ba9b64b 5244 }
5245
fd5e5847 5246 /*
5247 * Start the shell or command.
5248 *
2e85c969 5249 * Special case: if the first-choice command is an SSH-2
fd5e5847 5250 * subsystem (hence not usable here) and the second choice
5251 * exists, we fall straight back to that.
5252 */
5253 {
4a693cfc 5254 char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
fd5e5847 5255
4a693cfc 5256 if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
5257 conf_get_str(ssh->conf, CONF_remote_cmd2)) {
5258 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
51470298 5259 ssh->fallback_cmd = TRUE;
fd5e5847 5260 }
5261 if (*cmd)
51470298 5262 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
fd5e5847 5263 else
51470298 5264 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
fd5e5847 5265 logevent("Started session");
5266 }
374330e2 5267
51470298 5268 ssh->state = SSH_STATE_SESSION;
5269 if (ssh->size_needed)
5270 ssh_size(ssh, ssh->term_width, ssh->term_height);
5271 if (ssh->eof_needed)
5272 ssh_special(ssh, TS_EOF);
374330e2 5273
b9d7bcad 5274 if (ssh->ldisc)
5275 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
51470298 5276 ssh->send_ok = 1;
5277 ssh->channels = newtree234(ssh_channelcmp);
374330e2 5278 while (1) {
d74d141c 5279
51df0ab5 5280 /*
5281 * By this point, most incoming packets are already being
5282 * handled by the dispatch table, and we need only pay
5283 * attention to the unusual ones.
5284 */
0357890f 5285
51df0ab5 5286 crReturnV;
5287 if (pktin) {
5288 if (pktin->type == SSH1_SMSG_SUCCESS) {
972a41c8 5289 /* may be from EXEC_SHELL on some servers */
ff3187f6 5290 } else if (pktin->type == SSH1_SMSG_FAILURE) {
972a41c8 5291 /* may be from EXEC_SHELL on some servers
374330e2 5292 * if no pty is available or in other odd cases. Ignore */
374330e2 5293 } else {
ff3187f6 5294 bombout(("Strange packet received: type %d", pktin->type));
7ffdbc1a 5295 crStopV;
374330e2 5296 }
5297 } else {
8df7a775 5298 while (inlen > 0) {
5299 int len = min(inlen, 512);
a2724fba 5300 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
5301 PKT_INT, len, PKTT_DATA, PKT_DATA, in, len,
9a10ecf4 5302 PKTT_OTHER, PKT_END);
8df7a775 5303 in += len;
5304 inlen -= len;
5305 }
374330e2 5306 }
5307 }
5308
5309 crFinishV;
5310}
5311
5312/*
2e85c969 5313 * Handle the top-level SSH-2 protocol.
b09eaa88 5314 */
5315static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
5316{
fb983202 5317 char *msg;
b09eaa88 5318 int msglen;
5319
5320 ssh_pkt_getstring(pktin, &msg, &msglen);
fb983202 5321 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
b09eaa88 5322}
5323
5324static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
5325{
5326 /* log reason code in disconnect message */
5327 char *msg;
5328 int msglen;
5329
5330 ssh_pkt_getstring(pktin, &msg, &msglen);
5331 bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
5332}
5333
409bfa77 5334static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
b09eaa88 5335{
5336 /* Do nothing, because we're ignoring it! Duhh. */
5337}
5338
5339static void ssh1_protocol_setup(Ssh ssh)
5340{
5341 int i;
5342
5343 /*
5344 * Most messages are handled by the coroutines.
5345 */
5346 for (i = 0; i < 256; i++)
5347 ssh->packet_dispatch[i] = NULL;
5348
5349 /*
5350 * These special message types we install handlers for.
5351 */
5352 ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
5353 ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
5354 ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
5355}
5356
1c1a7262 5357static void ssh1_protocol(Ssh ssh, void *vin, int inlen,
b09eaa88 5358 struct Packet *pktin)
5359{
1c1a7262 5360 unsigned char *in=(unsigned char*)vin;
b09eaa88 5361 if (ssh->state == SSH_STATE_CLOSED)
5362 return;
5363
5364 if (pktin && ssh->packet_dispatch[pktin->type]) {
5365 ssh->packet_dispatch[pktin->type](ssh, pktin);
5366 return;
5367 }
5368
5369 if (!ssh->protocol_initial_phase_done) {
5370 if (do_ssh1_login(ssh, in, inlen, pktin))
5371 ssh->protocol_initial_phase_done = TRUE;
5372 else
5373 return;
5374 }
5375
5376 do_ssh1_connection(ssh, in, inlen, pktin);
5377}
5378
5379/*
e5574168 5380 * Utility routine for decoding comma-separated strings in KEXINIT.
5381 */
32874aea 5382static int in_commasep_string(char *needle, char *haystack, int haylen)
5383{
57356d63 5384 int needlen;
5385 if (!needle || !haystack) /* protect against null pointers */
5386 return 0;
5387 needlen = strlen(needle);
e5574168 5388 while (1) {
32874aea 5389 /*
5390 * Is it at the start of the string?
5391 */
5392 if (haylen >= needlen && /* haystack is long enough */
5393 !memcmp(needle, haystack, needlen) && /* initial match */
5394 (haylen == needlen || haystack[needlen] == ',')
5395 /* either , or EOS follows */
5396 )
5397 return 1;
5398 /*
5399 * If not, search for the next comma and resume after that.
5400 * If no comma found, terminate.
5401 */
5402 while (haylen > 0 && *haystack != ',')
5403 haylen--, haystack++;
5404 if (haylen == 0)
5405 return 0;
5406 haylen--, haystack++; /* skip over comma itself */
e5574168 5407 }
5408}
5409
5410/*
b59743d5 5411 * Similar routine for checking whether we have the first string in a list.
5412 */
5413static int first_in_commasep_string(char *needle, char *haystack, int haylen)
5414{
5415 int needlen;
5416 if (!needle || !haystack) /* protect against null pointers */
5417 return 0;
5418 needlen = strlen(needle);
5419 /*
5420 * Is it at the start of the string?
5421 */
5422 if (haylen >= needlen && /* haystack is long enough */
5423 !memcmp(needle, haystack, needlen) && /* initial match */
5424 (haylen == needlen || haystack[needlen] == ',')
5425 /* either , or EOS follows */
5426 )
5427 return 1;
5428 return 0;
5429}
5430
5431
5432/*
2e85c969 5433 * SSH-2 key creation method.
754c0df9 5434 * (Currently assumes 2 lots of any hash are sufficient to generate
5435 * keys/IVs for any cipher/MAC. SSH2_MKKEY_ITERS documents this assumption.)
d39f364a 5436 */
754c0df9 5437#define SSH2_MKKEY_ITERS (2)
b672f405 5438static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H, char chr,
d8baa528 5439 unsigned char *keyspace)
32874aea 5440{
b672f405 5441 const struct ssh_hash *h = ssh->kex->hash;
5442 void *s;
5443 /* First hlen bytes. */
5444 s = h->init();
51470298 5445 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
b672f405 5446 hash_mpint(h, s, K);
5447 h->bytes(s, H, h->hlen);
5448 h->bytes(s, &chr, 1);
5449 h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
5450 h->final(s, keyspace);
5451 /* Next hlen bytes. */
5452 s = h->init();
51470298 5453 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
b672f405 5454 hash_mpint(h, s, K);
5455 h->bytes(s, H, h->hlen);
5456 h->bytes(s, keyspace, h->hlen);
5457 h->final(s, keyspace + h->hlen);
d39f364a 5458}
5459
5460/*
2e85c969 5461 * Handle the SSH-2 transport layer.
e5574168 5462 */
1c1a7262 5463static int do_ssh2_transport(Ssh ssh, void *vin, int inlen,
ff3187f6 5464 struct Packet *pktin)
e5574168 5465{
1c1a7262 5466 unsigned char *in = (unsigned char *)vin;
51470298 5467 struct do_ssh2_transport_state {
4763c1c2 5468 int nbits, pbits, warn_kex, warn_cscipher, warn_sccipher;
51470298 5469 Bignum p, g, e, f, K;
3dc9a6a7 5470 void *our_kexinit;
5471 int our_kexinitlen;
51470298 5472 int kex_init_value, kex_reply_value;
5473 const struct ssh_mac **maclist;
5474 int nmacs;
5475 const struct ssh2_cipher *cscipher_tobe;
5476 const struct ssh2_cipher *sccipher_tobe;
5477 const struct ssh_mac *csmac_tobe;
5478 const struct ssh_mac *scmac_tobe;
5479 const struct ssh_compress *cscomp_tobe;
5480 const struct ssh_compress *sccomp_tobe;
fae1a71b 5481 char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
5482 int hostkeylen, siglen, rsakeylen;
51470298 5483 void *hkey; /* actual host key */
fae1a71b 5484 void *rsakey; /* for RSA kex */
754c0df9 5485 unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
83e7d008 5486 int n_preferred_kex;
34557659 5487 const struct ssh_kexes *preferred_kex[KEX_MAX];
51470298 5488 int n_preferred_ciphers;
5489 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
5490 const struct ssh_compress *preferred_comp;
ab18ccff 5491 int userauth_succeeded; /* for delayed compression */
5492 int pending_compression;
e13bba36 5493 int got_session_id, activated_authconn;
ff3187f6 5494 struct Packet *pktout;
3d9449a1 5495 int dlgret;
5496 int guessok;
4763c1c2 5497 int ignorepkt;
51470298 5498 };
5499 crState(do_ssh2_transport_state);
5500
5501 crBegin(ssh->do_ssh2_transport_crstate);
5502
5503 s->cscipher_tobe = s->sccipher_tobe = NULL;
5504 s->csmac_tobe = s->scmac_tobe = NULL;
5505 s->cscomp_tobe = s->sccomp_tobe = NULL;
5506
e13bba36 5507 s->got_session_id = s->activated_authconn = FALSE;
ab18ccff 5508 s->userauth_succeeded = FALSE;
5509 s->pending_compression = FALSE;
e5574168 5510
e13bba36 5511 /*
5512 * Be prepared to work around the buggy MAC problem.
5513 */
5514 if (ssh->remote_bugs & BUG_SSH2_HMAC)
5515 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
5516 else
5517 s->maclist = macs, s->nmacs = lenof(macs);
5518
5519 begin_key_exchange:
acab36bc 5520 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
51470298 5521 {
e13bba36 5522 int i, j, commalist_started;
5523
51470298 5524 /*
83e7d008 5525 * Set up the preferred key exchange. (NULL => warn below here)
5526 */
5527 s->n_preferred_kex = 0;
5528 for (i = 0; i < KEX_MAX; i++) {
4a693cfc 5529 switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
83e7d008 5530 case KEX_DHGEX:
5531 s->preferred_kex[s->n_preferred_kex++] =
5532 &ssh_diffiehellman_gex;
5533 break;
5534 case KEX_DHGROUP14:
5535 s->preferred_kex[s->n_preferred_kex++] =
5536 &ssh_diffiehellman_group14;
5537 break;
5538 case KEX_DHGROUP1:
5539 s->preferred_kex[s->n_preferred_kex++] =
5540 &ssh_diffiehellman_group1;
5541 break;
fae1a71b 5542 case KEX_RSA:
5543 s->preferred_kex[s->n_preferred_kex++] =
5544 &ssh_rsa_kex;
5545 break;
754c0df9 5546 case KEX_WARN:
83e7d008 5547 /* Flag for later. Don't bother if it's the last in
5548 * the list. */
5549 if (i < KEX_MAX - 1) {
5550 s->preferred_kex[s->n_preferred_kex++] = NULL;
5551 }
5552 break;
5553 }
5554 }
83e7d008 5555
83e7d008 5556 /*
51470298 5557 * Set up the preferred ciphers. (NULL => warn below here)
5558 */
5559 s->n_preferred_ciphers = 0;
5560 for (i = 0; i < CIPHER_MAX; i++) {
4a693cfc 5561 switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
51470298 5562 case CIPHER_BLOWFISH:
5563 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
5564 break;
5565 case CIPHER_DES:
4a693cfc 5566 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
51470298 5567 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
5568 }
5569 break;
5570 case CIPHER_3DES:
5571 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
5572 break;
5573 case CIPHER_AES:
5574 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
5575 break;
a2add208 5576 case CIPHER_ARCFOUR:
5577 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
5578 break;
51470298 5579 case CIPHER_WARN:
5580 /* Flag for later. Don't bother if it's the last in
5581 * the list. */
5582 if (i < CIPHER_MAX - 1) {
5583 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
5584 }
5585 break;
ca20bfcf 5586 }
ca20bfcf 5587 }
7591b9ff 5588
e13bba36 5589 /*
5590 * Set up preferred compression.
5591 */
4a693cfc 5592 if (conf_get_int(ssh->conf, CONF_compression))
e13bba36 5593 s->preferred_comp = &ssh_zlib;
5594 else
5595 s->preferred_comp = &ssh_comp_none;
51470298 5596
5597 /*
590f6a5f 5598 * Enable queueing of outgoing auth- or connection-layer
5599 * packets while we are in the middle of a key exchange.
5600 */
5601 ssh->queueing = TRUE;
5602
5603 /*
9442dd57 5604 * Flag that KEX is in progress.
5605 */
5606 ssh->kex_in_progress = TRUE;
5607
5608 /*
51470298 5609 * Construct and send our key exchange packet.
5610 */
ff3187f6 5611 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
51470298 5612 for (i = 0; i < 16; i++)
ff3187f6 5613 ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
51470298 5614 /* List key exchange algorithms. */
ff3187f6 5615 ssh2_pkt_addstring_start(s->pktout);
83e7d008 5616 commalist_started = 0;
5617 for (i = 0; i < s->n_preferred_kex; i++) {
34557659 5618 const struct ssh_kexes *k = s->preferred_kex[i];
83e7d008 5619 if (!k) continue; /* warning flag */
34557659 5620 for (j = 0; j < k->nkexes; j++) {
5621 if (commalist_started)
5622 ssh2_pkt_addstring_str(s->pktout, ",");
5623 ssh2_pkt_addstring_str(s->pktout, k->list[j]->name);
5624 commalist_started = 1;
5625 }
32874aea 5626 }
51470298 5627 /* List server host key algorithms. */
ff3187f6 5628 ssh2_pkt_addstring_start(s->pktout);
51470298 5629 for (i = 0; i < lenof(hostkey_algs); i++) {
ff3187f6 5630 ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
51470298 5631 if (i < lenof(hostkey_algs) - 1)
ff3187f6 5632 ssh2_pkt_addstring_str(s->pktout, ",");
32874aea 5633 }
51470298 5634 /* List client->server encryption algorithms. */
ff3187f6 5635 ssh2_pkt_addstring_start(s->pktout);
83e7d008 5636 commalist_started = 0;
51470298 5637 for (i = 0; i < s->n_preferred_ciphers; i++) {
5638 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5639 if (!c) continue; /* warning flag */
5640 for (j = 0; j < c->nciphers; j++) {
83e7d008 5641 if (commalist_started)
ff3187f6 5642 ssh2_pkt_addstring_str(s->pktout, ",");
5643 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
83e7d008 5644 commalist_started = 1;
51470298 5645 }
5646 }
5647 /* List server->client encryption algorithms. */
ff3187f6 5648 ssh2_pkt_addstring_start(s->pktout);
83e7d008 5649 commalist_started = 0;
51470298 5650 for (i = 0; i < s->n_preferred_ciphers; i++) {
5651 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5652 if (!c) continue; /* warning flag */
5653 for (j = 0; j < c->nciphers; j++) {
83e7d008 5654 if (commalist_started)
ff3187f6 5655 ssh2_pkt_addstring_str(s->pktout, ",");
5656 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
83e7d008 5657 commalist_started = 1;
51470298 5658 }
5659 }
5660 /* List client->server MAC algorithms. */
ff3187f6 5661 ssh2_pkt_addstring_start(s->pktout);
51470298 5662 for (i = 0; i < s->nmacs; i++) {
ff3187f6 5663 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
51470298 5664 if (i < s->nmacs - 1)
ff3187f6 5665 ssh2_pkt_addstring_str(s->pktout, ",");
51470298 5666 }
5667 /* List server->client MAC algorithms. */
ff3187f6 5668 ssh2_pkt_addstring_start(s->pktout);
51470298 5669 for (i = 0; i < s->nmacs; i++) {
ff3187f6 5670 ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
51470298 5671 if (i < s->nmacs - 1)
ff3187f6 5672 ssh2_pkt_addstring_str(s->pktout, ",");
51470298 5673 }
ab18ccff 5674 /* List client->server compression algorithms,
5675 * then server->client compression algorithms. (We use the
5676 * same set twice.) */
5677 for (j = 0; j < 2; j++) {
5678 ssh2_pkt_addstring_start(s->pktout);
5679 assert(lenof(compressions) > 1);
5680 /* Prefer non-delayed versions */
5681 ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5682 /* We don't even list delayed versions of algorithms until
5683 * they're allowed to be used, to avoid a race. See the end of
5684 * this function. */
5685 if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
ff3187f6 5686 ssh2_pkt_addstring_str(s->pktout, ",");
ab18ccff 5687 ssh2_pkt_addstring_str(s->pktout,
5688 s->preferred_comp->delayed_name);
f6e0abe2 5689 }
ab18ccff 5690 for (i = 0; i < lenof(compressions); i++) {
5691 const struct ssh_compress *c = compressions[i];
5692 if (c != s->preferred_comp) {
5693 ssh2_pkt_addstring_str(s->pktout, ",");
5694 ssh2_pkt_addstring_str(s->pktout, c->name);
5695 if (s->userauth_succeeded && c->delayed_name) {
5696 ssh2_pkt_addstring_str(s->pktout, ",");
5697 ssh2_pkt_addstring_str(s->pktout, c->delayed_name);
5698 }
5699 }
f6e0abe2 5700 }
51470298 5701 }
5702 /* List client->server languages. Empty list. */
ff3187f6 5703 ssh2_pkt_addstring_start(s->pktout);
51470298 5704 /* List server->client languages. Empty list. */
ff3187f6 5705 ssh2_pkt_addstring_start(s->pktout);
51470298 5706 /* First KEX packet does _not_ follow, because we're not that brave. */
ff3187f6 5707 ssh2_pkt_addbool(s->pktout, FALSE);
51470298 5708 /* Reserved. */
ff3187f6 5709 ssh2_pkt_adduint32(s->pktout, 0);
e5574168 5710 }
0db56f73 5711
3dc9a6a7 5712 s->our_kexinitlen = s->pktout->length - 5;
5713 s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
5714 memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
0db56f73 5715
590f6a5f 5716 ssh2_pkt_send_noqueue(ssh, s->pktout);
e5574168 5717
ff3187f6 5718 if (!pktin)
5719 crWaitUntil(pktin);
e5574168 5720
5721 /*
5722 * Now examine the other side's KEXINIT to see what we're up
5723 * to.
5724 */
51470298 5725 {
4763c1c2 5726 char *str, *preferred;
3d9449a1 5727 int i, j, len;
51470298 5728
ff3187f6 5729 if (pktin->type != SSH2_MSG_KEXINIT) {
6b5cf8b4 5730 bombout(("expected key exchange packet from server"));
7ffdbc1a 5731 crStop(0);
32874aea 5732 }
51470298 5733 ssh->kex = NULL;
5734 ssh->hostkey = NULL;
5735 s->cscipher_tobe = NULL;
5736 s->sccipher_tobe = NULL;
5737 s->csmac_tobe = NULL;
5738 s->scmac_tobe = NULL;
5739 s->cscomp_tobe = NULL;
5740 s->sccomp_tobe = NULL;
4763c1c2 5741 s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5742
ff3187f6 5743 pktin->savedpos += 16; /* skip garbage cookie */
5744 ssh_pkt_getstring(pktin, &str, &len); /* key exchange algorithms */
4763c1c2 5745
5746 preferred = NULL;
83e7d008 5747 for (i = 0; i < s->n_preferred_kex; i++) {
34557659 5748 const struct ssh_kexes *k = s->preferred_kex[i];
83e7d008 5749 if (!k) {
4763c1c2 5750 s->warn_kex = TRUE;
5751 } else {
34557659 5752 for (j = 0; j < k->nkexes; j++) {
5753 if (!preferred) preferred = k->list[j]->name;
5754 if (in_commasep_string(k->list[j]->name, str, len)) {
5755 ssh->kex = k->list[j];
5756 break;
5757 }
5758 }
83e7d008 5759 }
4763c1c2 5760 if (ssh->kex)
51470298 5761 break;
32874aea 5762 }
83e7d008 5763 if (!ssh->kex) {
5764 bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5765 str ? str : "(null)"));
5766 crStop(0);
5767 }
b59743d5 5768 /*
5769 * Note that the server's guess is considered wrong if it doesn't match
5770 * the first algorithm in our list, even if it's still the algorithm
5771 * we end up using.
5772 */
4763c1c2 5773 s->guessok = first_in_commasep_string(preferred, str, len);
ff3187f6 5774 ssh_pkt_getstring(pktin, &str, &len); /* host key algorithms */
51470298 5775 for (i = 0; i < lenof(hostkey_algs); i++) {
5776 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5777 ssh->hostkey = hostkey_algs[i];
5778 break;
5779 }
5780 }
fc40b431 5781 if (!ssh->hostkey) {
5782 bombout(("Couldn't agree a host key algorithm (available: %s)",
5783 str ? str : "(null)"));
5784 crStop(0);
5785 }
5786
3d9449a1 5787 s->guessok = s->guessok &&
b59743d5 5788 first_in_commasep_string(hostkey_algs[0]->name, str, len);
ff3187f6 5789 ssh_pkt_getstring(pktin, &str, &len); /* client->server cipher */
51470298 5790 for (i = 0; i < s->n_preferred_ciphers; i++) {
5791 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5792 if (!c) {
4763c1c2 5793 s->warn_cscipher = TRUE;
51470298 5794 } else {
5795 for (j = 0; j < c->nciphers; j++) {
5796 if (in_commasep_string(c->list[j]->name, str, len)) {
5797 s->cscipher_tobe = c->list[j];
5798 break;
5799 }
ca20bfcf 5800 }
32874aea 5801 }
4763c1c2 5802 if (s->cscipher_tobe)
51470298 5803 break;
32874aea 5804 }
51470298 5805 if (!s->cscipher_tobe) {
6b5cf8b4 5806 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
57356d63 5807 str ? str : "(null)"));
7ffdbc1a 5808 crStop(0);
ca20bfcf 5809 }
0ef8f407 5810
ff3187f6 5811 ssh_pkt_getstring(pktin, &str, &len); /* server->client cipher */
51470298 5812 for (i = 0; i < s->n_preferred_ciphers; i++) {
5813 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5814 if (!c) {
4763c1c2 5815 s->warn_sccipher = TRUE;
51470298 5816 } else {
5817 for (j = 0; j < c->nciphers; j++) {
5818 if (in_commasep_string(c->list[j]->name, str, len)) {
5819 s->sccipher_tobe = c->list[j];
5820 break;
5821 }
ca20bfcf 5822 }
32874aea 5823 }
4763c1c2 5824 if (s->sccipher_tobe)
51470298 5825 break;
32874aea 5826 }
51470298 5827 if (!s->sccipher_tobe) {
6b5cf8b4 5828 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
57356d63 5829 str ? str : "(null)"));
7ffdbc1a 5830 crStop(0);
ca20bfcf 5831 }
0ef8f407 5832
ff3187f6 5833 ssh_pkt_getstring(pktin, &str, &len); /* client->server mac */
51470298 5834 for (i = 0; i < s->nmacs; i++) {
5835 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5836 s->csmac_tobe = s->maclist[i];
5837 break;
5838 }
32874aea 5839 }
ff3187f6 5840 ssh_pkt_getstring(pktin, &str, &len); /* server->client mac */
51470298 5841 for (i = 0; i < s->nmacs; i++) {
5842 if (in_commasep_string(s->maclist[i]->name, str, len)) {
5843 s->scmac_tobe = s->maclist[i];
5844 break;
5845 }
32874aea 5846 }
ff3187f6 5847 ssh_pkt_getstring(pktin, &str, &len); /* client->server compression */
51470298 5848 for (i = 0; i < lenof(compressions) + 1; i++) {
5849 const struct ssh_compress *c =
5850 i == 0 ? s->preferred_comp : compressions[i - 1];
5851 if (in_commasep_string(c->name, str, len)) {
5852 s->cscomp_tobe = c;
5853 break;
ab18ccff 5854 } else if (in_commasep_string(c->delayed_name, str, len)) {
5855 if (s->userauth_succeeded) {
5856 s->cscomp_tobe = c;
5857 break;
5858 } else {
5859 s->pending_compression = TRUE; /* try this later */
5860 }
51470298 5861 }
32874aea 5862 }
ff3187f6 5863 ssh_pkt_getstring(pktin, &str, &len); /* server->client compression */
51470298 5864 for (i = 0; i < lenof(compressions) + 1; i++) {
5865 const struct ssh_compress *c =
5866 i == 0 ? s->preferred_comp : compressions[i - 1];
5867 if (in_commasep_string(c->name, str, len)) {
5868 s->sccomp_tobe = c;
5869 break;
ab18ccff 5870 } else if (in_commasep_string(c->delayed_name, str, len)) {
5871 if (s->userauth_succeeded) {
5872 s->sccomp_tobe = c;
5873 break;
5874 } else {
5875 s->pending_compression = TRUE; /* try this later */
5876 }
51470298 5877 }
32874aea 5878 }
ab18ccff 5879 if (s->pending_compression) {
5880 logevent("Server supports delayed compression; "
5881 "will try this later");
5882 }
b59743d5 5883 ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
5884 ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
4763c1c2 5885 s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5886
5887 if (s->warn_kex) {
5888 ssh_set_frozen(ssh, 1);
5889 s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5890 ssh->kex->name,
5891 ssh_dialog_callback, ssh);
5892 if (s->dlgret < 0) {
5893 do {
5894 crReturn(0);
5895 if (pktin) {
5896 bombout(("Unexpected data from server while"
5897 " waiting for user response"));
5898 crStop(0);
5899 }
5900 } while (pktin || inlen > 0);
5901 s->dlgret = ssh->user_response;
5902 }
5903 ssh_set_frozen(ssh, 0);
5904 if (s->dlgret == 0) {
9e296bfa 5905 ssh_disconnect(ssh, "User aborted at kex warning", NULL,
5906 0, TRUE);
a5a6f839 5907 crStop(0);
4763c1c2 5908 }
5909 }
5910
5911 if (s->warn_cscipher) {
5912 ssh_set_frozen(ssh, 1);
5913 s->dlgret = askalg(ssh->frontend,
5914 "client-to-server cipher",
5915 s->cscipher_tobe->name,
5916 ssh_dialog_callback, ssh);
5917 if (s->dlgret < 0) {
5918 do {
5919 crReturn(0);
5920 if (pktin) {
5921 bombout(("Unexpected data from server while"
5922 " waiting for user response"));
5923 crStop(0);
5924 }
5925 } while (pktin || inlen > 0);
5926 s->dlgret = ssh->user_response;
5927 }
5928 ssh_set_frozen(ssh, 0);
5929 if (s->dlgret == 0) {
9e296bfa 5930 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5931 0, TRUE);
a5a6f839 5932 crStop(0);
4763c1c2 5933 }
5934 }
5935
5936 if (s->warn_sccipher) {
5937 ssh_set_frozen(ssh, 1);
5938 s->dlgret = askalg(ssh->frontend,
5939 "server-to-client cipher",
5940 s->sccipher_tobe->name,
5941 ssh_dialog_callback, ssh);
5942 if (s->dlgret < 0) {
5943 do {
5944 crReturn(0);
5945 if (pktin) {
5946 bombout(("Unexpected data from server while"
5947 " waiting for user response"));
5948 crStop(0);
5949 }
5950 } while (pktin || inlen > 0);
5951 s->dlgret = ssh->user_response;
5952 }
5953 ssh_set_frozen(ssh, 0);
5954 if (s->dlgret == 0) {
9e296bfa 5955 ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
5956 0, TRUE);
a5a6f839 5957 crStop(0);
4763c1c2 5958 }
5959 }
5960
b672f405 5961 ssh->exhash = ssh->kex->hash->init();
5962 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
5963 hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
5964 hash_string(ssh->kex->hash, ssh->exhash,
5965 s->our_kexinit, s->our_kexinitlen);
3dc9a6a7 5966 sfree(s->our_kexinit);
5967 if (pktin->length > 5)
b672f405 5968 hash_string(ssh->kex->hash, ssh->exhash,
5969 pktin->data + 5, pktin->length - 5);
3dc9a6a7 5970
4763c1c2 5971 if (s->ignorepkt) /* first_kex_packet_follows */
b59743d5 5972 crWaitUntil(pktin); /* Ignore packet */
e5574168 5973 }
e5574168 5974
fae1a71b 5975 if (ssh->kex->main_type == KEXTYPE_DH) {
30774ba3 5976 /*
5977 * Work out the number of bits of key we will need from the
5978 * key exchange. We start with the maximum key length of
5979 * either cipher...
5980 */
5981 {
5982 int csbits, scbits;
5983
5984 csbits = s->cscipher_tobe->keylen;
5985 scbits = s->sccipher_tobe->keylen;
5986 s->nbits = (csbits > scbits ? csbits : scbits);
5987 }
5988 /* The keys only have hlen-bit entropy, since they're based on
5989 * a hash. So cap the key size at hlen bits. */
5990 if (s->nbits > ssh->kex->hash->hlen * 8)
5991 s->nbits = ssh->kex->hash->hlen * 8;
5992
5993 /*
5994 * If we're doing Diffie-Hellman group exchange, start by
5995 * requesting a group.
5996 */
5997 if (!ssh->kex->pdata) {
5998 logevent("Doing Diffie-Hellman group exchange");
acab36bc 5999 ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
30774ba3 6000 /*
6001 * Work out how big a DH group we will need to allow that
6002 * much data.
6003 */
6004 s->pbits = 512 << ((s->nbits - 1) / 64);
6005 s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
6006 ssh2_pkt_adduint32(s->pktout, s->pbits);
6007 ssh2_pkt_send_noqueue(ssh, s->pktout);
6008
6009 crWaitUntil(pktin);
6010 if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6011 bombout(("expected key exchange group packet from server"));
6012 crStop(0);
6013 }
6014 s->p = ssh2_pkt_getmp(pktin);
6015 s->g = ssh2_pkt_getmp(pktin);
6016 if (!s->p || !s->g) {
6017 bombout(("unable to read mp-ints from incoming group packet"));
6018 crStop(0);
6019 }
6020 ssh->kex_ctx = dh_setup_gex(s->p, s->g);
6021 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
6022 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
6023 } else {
acab36bc 6024 ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
30774ba3 6025 ssh->kex_ctx = dh_setup_group(ssh->kex);
6026 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
6027 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
6028 logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
6029 ssh->kex->groupname);
6030 }
e5574168 6031
30774ba3 6032 logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
6033 ssh->kex->hash->text_name);
6034 /*
6035 * Now generate and send e for Diffie-Hellman.
6036 */
6037 set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
6038 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
6039 s->pktout = ssh2_pkt_init(s->kex_init_value);
6040 ssh2_pkt_addmp(s->pktout, s->e);
6041 ssh2_pkt_send_noqueue(ssh, s->pktout);
6042
6043 set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
6044 crWaitUntil(pktin);
6045 if (pktin->type != s->kex_reply_value) {
6046 bombout(("expected key exchange reply packet from server"));
6047 crStop(0);
6048 }
6049 set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
6050 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6051 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6052 s->f = ssh2_pkt_getmp(pktin);
6053 if (!s->f) {
6054 bombout(("unable to parse key exchange reply packet"));
6055 crStop(0);
6056 }
6057 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
e5574168 6058
30774ba3 6059 s->K = dh_find_K(ssh->kex_ctx, s->f);
e5574168 6060
30774ba3 6061 /* We assume everything from now on will be quick, and it might
6062 * involve user interaction. */
6063 set_busy_status(ssh->frontend, BUSY_NOT);
755e0524 6064
30774ba3 6065 hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
6066 if (!ssh->kex->pdata) {
6067 hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
6068 hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
6069 hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
6070 }
6071 hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
6072 hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
6073
6074 dh_cleanup(ssh->kex_ctx);
6075 freebn(s->f);
6076 if (!ssh->kex->pdata) {
6077 freebn(s->g);
6078 freebn(s->p);
6079 }
fae1a71b 6080 } else {
6081 logeventf(ssh, "Doing RSA key exchange with hash %s",
6082 ssh->kex->hash->text_name);
acab36bc 6083 ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
fae1a71b 6084 /*
6085 * RSA key exchange. First expect a KEXRSA_PUBKEY packet
6086 * from the server.
6087 */
6088 crWaitUntil(pktin);
6089 if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
6090 bombout(("expected RSA public key packet from server"));
6091 crStop(0);
6092 }
6093
6094 ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
6095 hash_string(ssh->kex->hash, ssh->exhash,
6096 s->hostkeydata, s->hostkeylen);
6097 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
6098
6099 {
6100 char *keydata;
6101 ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
6102 s->rsakeydata = snewn(s->rsakeylen, char);
6103 memcpy(s->rsakeydata, keydata, s->rsakeylen);
6104 }
6105
6106 s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
6107 if (!s->rsakey) {
6108 sfree(s->rsakeydata);
6109 bombout(("unable to parse RSA public key from server"));
6110 crStop(0);
6111 }
6112
6113 hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
6114
6115 /*
6116 * Next, set up a shared secret K, of precisely KLEN -
6117 * 2*HLEN - 49 bits, where KLEN is the bit length of the
6118 * RSA key modulus and HLEN is the bit length of the hash
6119 * we're using.
6120 */
6121 {
6122 int klen = ssh_rsakex_klen(s->rsakey);
6123 int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
6124 int i, byte = 0;
6125 unsigned char *kstr1, *kstr2, *outstr;
6126 int kstr1len, kstr2len, outstrlen;
6127
6128 s->K = bn_power_2(nbits - 1);
6129
6130 for (i = 0; i < nbits; i++) {
6131 if ((i & 7) == 0) {
6132 byte = random_byte();
6133 }
6134 bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
6135 }
6136
6137 /*
6138 * Encode this as an mpint.
6139 */
6140 kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
6141 kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
6142 PUT_32BIT(kstr2, kstr1len);
6143 memcpy(kstr2 + 4, kstr1, kstr1len);
6144
6145 /*
6146 * Encrypt it with the given RSA key.
6147 */
6148 outstrlen = (klen + 7) / 8;
6149 outstr = snewn(outstrlen, unsigned char);
6150 ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
6151 outstr, outstrlen, s->rsakey);
6152
6153 /*
6154 * And send it off in a return packet.
6155 */
6156 s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
6157 ssh2_pkt_addstring_start(s->pktout);
7108a872 6158 ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
fae1a71b 6159 ssh2_pkt_send_noqueue(ssh, s->pktout);
6160
6161 hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
6162
6163 sfree(kstr2);
6164 sfree(kstr1);
6165 sfree(outstr);
6166 }
6167
6168 ssh_rsakex_freekey(s->rsakey);
6169
6170 crWaitUntil(pktin);
6171 if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
6172 sfree(s->rsakeydata);
6173 bombout(("expected signature packet from server"));
6174 crStop(0);
6175 }
6176
6177 ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
6178
6179 sfree(s->rsakeydata);
6180 }
6181
b672f405 6182 hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
6183 assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
6184 ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
e5574168 6185
fabd1805 6186 ssh->kex_ctx = NULL;
3709bfe9 6187
7cca0d81 6188#if 0
765c4200 6189 debug(("Exchange hash is:\n"));
b672f405 6190 dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
7cca0d81 6191#endif
6192
51470298 6193 if (!s->hkey ||
6194 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
b672f405 6195 (char *)s->exchange_hash,
6196 ssh->kex->hash->hlen)) {
6b5cf8b4 6197 bombout(("Server's host key did not match the signature supplied"));
7ffdbc1a 6198 crStop(0);
8d5de777 6199 }
e5574168 6200
6201 /*
7cca0d81 6202 * Authenticate remote host: verify host key. (We've already
6203 * checked the signature of the exchange hash.)
e5574168 6204 */
51470298 6205 s->keystr = ssh->hostkey->fmtkey(s->hkey);
6206 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
3d9449a1 6207 ssh_set_frozen(ssh, 1);
6208 s->dlgret = verify_ssh_host_key(ssh->frontend,
6209 ssh->savedhost, ssh->savedport,
6210 ssh->hostkey->keytype, s->keystr,
6211 s->fingerprint,
6212 ssh_dialog_callback, ssh);
6213 if (s->dlgret < 0) {
6214 do {
6215 crReturn(0);
6216 if (pktin) {
6217 bombout(("Unexpected data from server while waiting"
6218 " for user host key response"));
6219 crStop(0);
6220 }
6221 } while (pktin || inlen > 0);
6222 s->dlgret = ssh->user_response;
6223 }
6224 ssh_set_frozen(ssh, 0);
6225 if (s->dlgret == 0) {
9e296bfa 6226 ssh_disconnect(ssh, "User aborted at host key verification", NULL,
6227 0, TRUE);
3d9449a1 6228 crStop(0);
6229 }
e13bba36 6230 if (!s->got_session_id) { /* don't bother logging this in rekeys */
5e0d7cb8 6231 logevent("Host key fingerprint is:");
51470298 6232 logevent(s->fingerprint);
5e0d7cb8 6233 }
51470298 6234 sfree(s->fingerprint);
6235 sfree(s->keystr);
6236 ssh->hostkey->freekey(s->hkey);
d39f364a 6237
6238 /*
9442dd57 6239 * The exchange hash from the very first key exchange is also
6240 * the session id, used in session key construction and
6241 * authentication.
6242 */
e13bba36 6243 if (!s->got_session_id) {
b672f405 6244 assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
9442dd57 6245 memcpy(ssh->v2_session_id, s->exchange_hash,
6246 sizeof(s->exchange_hash));
b672f405 6247 ssh->v2_session_id_len = ssh->kex->hash->hlen;
6052bb76 6248 assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
e13bba36 6249 s->got_session_id = TRUE;
6250 }
9442dd57 6251
6252 /*
7cca0d81 6253 * Send SSH2_MSG_NEWKEYS.
d39f364a 6254 */
ff3187f6 6255 s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
590f6a5f 6256 ssh2_pkt_send_noqueue(ssh, s->pktout);
9442dd57 6257 ssh->outgoing_data_size = 0; /* start counting from here */
6258
6259 /*
6260 * We've sent client NEWKEYS, so create and initialise
c64fe7d4 6261 * client-to-server session keys.
9442dd57 6262 */
6263 if (ssh->cs_cipher_ctx)
6264 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6265 ssh->cscipher = s->cscipher_tobe;
6266 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
6267
6268 if (ssh->cs_mac_ctx)
6269 ssh->csmac->free_context(ssh->cs_mac_ctx);
6270 ssh->csmac = s->csmac_tobe;
6271 ssh->cs_mac_ctx = ssh->csmac->make_context();
6272
6273 if (ssh->cs_comp_ctx)
6274 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6275 ssh->cscomp = s->cscomp_tobe;
6276 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
6277
6278 /*
6279 * Set IVs on client-to-server keys. Here we use the exchange
6280 * hash from the _first_ key exchange.
6281 */
6282 {
754c0df9 6283 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6284 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
b672f405 6285 ssh2_mkkey(ssh,s->K,s->exchange_hash,'C',keyspace);
754c0df9 6286 assert((ssh->cscipher->keylen+7) / 8 <=
6287 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
9442dd57 6288 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
b672f405 6289 ssh2_mkkey(ssh,s->K,s->exchange_hash,'A',keyspace);
754c0df9 6290 assert(ssh->cscipher->blksize <=
6291 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
9442dd57 6292 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
b672f405 6293 ssh2_mkkey(ssh,s->K,s->exchange_hash,'E',keyspace);
754c0df9 6294 assert(ssh->csmac->len <=
6295 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
9442dd57 6296 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
dfb88efd 6297 smemclr(keyspace, sizeof(keyspace));
9442dd57 6298 }
6299
6300 logeventf(ssh, "Initialised %.200s client->server encryption",
6301 ssh->cscipher->text_name);
6302 logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
6303 ssh->csmac->text_name);
6304 if (ssh->cscomp->text_name)
6305 logeventf(ssh, "Initialised %s compression",
6306 ssh->cscomp->text_name);
590f6a5f 6307
6308 /*
6309 * Now our end of the key exchange is complete, we can send all
6310 * our queued higher-layer packets.
6311 */
6312 ssh->queueing = FALSE;
6313 ssh2_pkt_queuesend(ssh);
d39f364a 6314
6315 /*
8406eaf9 6316 * Expect SSH2_MSG_NEWKEYS from server.
6317 */
ff3187f6 6318 crWaitUntil(pktin);
6319 if (pktin->type != SSH2_MSG_NEWKEYS) {
6b5cf8b4 6320 bombout(("expected new-keys packet from server"));
7ffdbc1a 6321 crStop(0);
8406eaf9 6322 }
9442dd57 6323 ssh->incoming_data_size = 0; /* start counting from here */
8406eaf9 6324
6325 /*
9442dd57 6326 * We've seen server NEWKEYS, so create and initialise
6327 * server-to-client session keys.
d39f364a 6328 */
371e569c 6329 if (ssh->sc_cipher_ctx)
6330 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
51470298 6331 ssh->sccipher = s->sccipher_tobe;
371e569c 6332 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
e0e1a00d 6333
e0e1a00d 6334 if (ssh->sc_mac_ctx)
6335 ssh->scmac->free_context(ssh->sc_mac_ctx);
51470298 6336 ssh->scmac = s->scmac_tobe;
e0e1a00d 6337 ssh->sc_mac_ctx = ssh->scmac->make_context();
6338
5366aed8 6339 if (ssh->sc_comp_ctx)
6340 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
51470298 6341 ssh->sccomp = s->sccomp_tobe;
5366aed8 6342 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
6343
d39f364a 6344 /*
9442dd57 6345 * Set IVs on server-to-client keys. Here we use the exchange
6346 * hash from the _first_ key exchange.
d39f364a 6347 */
51470298 6348 {
754c0df9 6349 unsigned char keyspace[SSH2_KEX_MAX_HASH_LEN * SSH2_MKKEY_ITERS];
6350 assert(sizeof(keyspace) >= ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
b672f405 6351 ssh2_mkkey(ssh,s->K,s->exchange_hash,'D',keyspace);
754c0df9 6352 assert((ssh->sccipher->keylen+7) / 8 <=
6353 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
371e569c 6354 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
b672f405 6355 ssh2_mkkey(ssh,s->K,s->exchange_hash,'B',keyspace);
754c0df9 6356 assert(ssh->sccipher->blksize <=
6357 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
371e569c 6358 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
b672f405 6359 ssh2_mkkey(ssh,s->K,s->exchange_hash,'F',keyspace);
754c0df9 6360 assert(ssh->scmac->len <=
6361 ssh->kex->hash->hlen * SSH2_MKKEY_ITERS);
e0e1a00d 6362 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
dfb88efd 6363 smemclr(keyspace, sizeof(keyspace));
51470298 6364 }
57356d63 6365 logeventf(ssh, "Initialised %.200s server->client encryption",
6366 ssh->sccipher->text_name);
6c135243 6367 logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
6368 ssh->scmac->text_name);
57356d63 6369 if (ssh->sccomp->text_name)
6370 logeventf(ssh, "Initialised %s decompression",
6371 ssh->sccomp->text_name);
9442dd57 6372
6373 /*
fae1a71b 6374 * Free shared secret.
9442dd57 6375 */
679539d7 6376 freebn(s->K);
d39f364a 6377
033b4cef 6378 /*
e13bba36 6379 * Key exchange is over. Loop straight back round if we have a
6380 * deferred rekey reason.
6381 */
6382 if (ssh->deferred_rekey_reason) {
6383 logevent(ssh->deferred_rekey_reason);
6384 pktin = NULL;
6385 ssh->deferred_rekey_reason = NULL;
6386 goto begin_key_exchange;
6387 }
6388
6389 /*
6390 * Otherwise, schedule a timer for our next rekey.
9442dd57 6391 */
6392 ssh->kex_in_progress = FALSE;
e6c1536e 6393 ssh->last_rekey = GETTICKCOUNT();
4a693cfc 6394 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
6395 ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
d57f70af 6396 ssh2_timer, ssh);
e13bba36 6397
9442dd57 6398 /*
0db56f73 6399 * If this is the first key exchange phase, we must pass the
6400 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
6401 * wants to see it but because it will need time to initialise
6402 * itself before it sees an actual packet. In subsequent key
6403 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
6404 * it would only confuse the layer above.
6405 */
e13bba36 6406 if (s->activated_authconn) {
0e3607ed 6407 crReturn(0);
0db56f73 6408 }
e13bba36 6409 s->activated_authconn = TRUE;
0db56f73 6410
6411 /*
7cca0d81 6412 * Now we're encrypting. Begin returning 1 to the protocol main
6413 * function so that other things can run on top of the
6414 * transport. If we ever see a KEXINIT, we must go back to the
6415 * start.
9442dd57 6416 *
6417 * We _also_ go back to the start if we see pktin==NULL and
ab18ccff 6418 * inlen negative, because this is a special signal meaning
9442dd57 6419 * `initiate client-driven rekey', and `in' contains a message
6420 * giving the reason for the rekey.
ab18ccff 6421 *
6422 * inlen==-1 means always initiate a rekey;
6423 * inlen==-2 means that userauth has completed successfully and
6424 * we should consider rekeying (for delayed compression).
033b4cef 6425 */
9442dd57 6426 while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
ab18ccff 6427 (!pktin && inlen < 0))) {
f382c87d 6428 wait_for_rekey:
32874aea 6429 crReturn(1);
e96adf72 6430 }
9442dd57 6431 if (pktin) {
6432 logevent("Server initiated key re-exchange");
6433 } else {
ab18ccff 6434 if (inlen == -2) {
6435 /*
6436 * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
6437 * delayed compression, if it's available.
6438 *
6439 * draft-miller-secsh-compression-delayed-00 says that you
6440 * negotiate delayed compression in the first key exchange, and
6441 * both sides start compressing when the server has sent
6442 * USERAUTH_SUCCESS. This has a race condition -- the server
6443 * can't know when the client has seen it, and thus which incoming
6444 * packets it should treat as compressed.
6445 *
6446 * Instead, we do the initial key exchange without offering the
6447 * delayed methods, but note if the server offers them; when we
6448 * get here, if a delayed method was available that was higher
6449 * on our list than what we got, we initiate a rekey in which we
6450 * _do_ list the delayed methods (and hopefully get it as a
6451 * result). Subsequent rekeys will do the same.
6452 */
6453 assert(!s->userauth_succeeded); /* should only happen once */
6454 s->userauth_succeeded = TRUE;
6455 if (!s->pending_compression)
6456 /* Can't see any point rekeying. */
6457 goto wait_for_rekey; /* this is utterly horrid */
6458 /* else fall through to rekey... */
6459 s->pending_compression = FALSE;
6460 }
f382c87d 6461 /*
ab18ccff 6462 * Now we've decided to rekey.
6463 *
f382c87d 6464 * Special case: if the server bug is set that doesn't
6465 * allow rekeying, we give a different log message and
6466 * continue waiting. (If such a server _initiates_ a rekey,
6467 * we process it anyway!)
6468 */
6469 if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
6470 logeventf(ssh, "Server bug prevents key re-exchange (%s)",
6471 (char *)in);
6472 /* Reset the counters, so that at least this message doesn't
6473 * hit the event log _too_ often. */
6474 ssh->outgoing_data_size = 0;
6475 ssh->incoming_data_size = 0;
4a693cfc 6476 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
f382c87d 6477 ssh->next_rekey =
4a693cfc 6478 schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
f382c87d 6479 ssh2_timer, ssh);
6480 }
ab18ccff 6481 goto wait_for_rekey; /* this is still utterly horrid */
f382c87d 6482 } else {
6483 logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
f382c87d 6484 }
9442dd57 6485 }
7cca0d81 6486 goto begin_key_exchange;
e5574168 6487
6488 crFinish(1);
6489}
6490
7cca0d81 6491/*
2e85c969 6492 * Add data to an SSH-2 channel output buffer.
783415f8 6493 */
32874aea 6494static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
6495 int len)
6496{
5471d09a 6497 bufchain_add(&c->v.v2.outbuffer, buf, len);
783415f8 6498}
6499
6500/*
2e85c969 6501 * Attempt to send data on an SSH-2 channel.
783415f8 6502 */
5471d09a 6503static int ssh2_try_send(struct ssh_channel *c)
32874aea 6504{
51470298 6505 Ssh ssh = c->ssh;
ff3187f6 6506 struct Packet *pktout;
bc06669b 6507 int ret;
51470298 6508
5471d09a 6509 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
6510 int len;
6511 void *data;
6512 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
6513 if ((unsigned)len > c->v.v2.remwindow)
6514 len = c->v.v2.remwindow;
6515 if ((unsigned)len > c->v.v2.remmaxpkt)
6516 len = c->v.v2.remmaxpkt;
ff3187f6 6517 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
6518 ssh2_pkt_adduint32(pktout, c->remoteid);
ff3187f6 6519 ssh2_pkt_addstring_start(pktout);
a2724fba 6520 dont_log_data(ssh, pktout, PKTLOG_OMIT);
ff3187f6 6521 ssh2_pkt_addstring_data(pktout, data, len);
6522 end_log_omission(ssh, pktout);
6523 ssh2_pkt_send(ssh, pktout);
5471d09a 6524 bufchain_consume(&c->v.v2.outbuffer, len);
6525 c->v.v2.remwindow -= len;
6526 }
6527
6528 /*
6529 * After having sent as much data as we can, return the amount
6530 * still buffered.
6531 */
bc06669b 6532 ret = bufchain_size(&c->v.v2.outbuffer);
6533
6534 /*
6535 * And if there's no data pending but we need to send an EOF, send
6536 * it.
6537 */
6538 if (!ret && c->pending_eof)
6539 ssh_channel_try_eof(c);
6540
6541 return ret;
5471d09a 6542}
6543
78280721 6544static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
1bfc7e93 6545{
6546 int bufsize;
bc06669b 6547 if (c->closes & CLOSES_SENT_EOF)
6548 return; /* don't send on channels we've EOFed */
1bfc7e93 6549 bufsize = ssh2_try_send(c);
6550 if (bufsize == 0) {
6551 switch (c->type) {
6552 case CHAN_MAINSESSION:
6553 /* stdin need not receive an unthrottle
6554 * notification since it will be polled */
6555 break;
6556 case CHAN_X11:
6557 x11_unthrottle(c->u.x11.s);
6558 break;
6559 case CHAN_AGENT:
6560 /* agent sockets are request/response and need no
6561 * buffer management */
6562 break;
6563 case CHAN_SOCKDATA:
6564 pfd_unthrottle(c->u.pfd.s);
6565 break;
6566 }
6567 }
6568}
6569
5471d09a 6570/*
94bdfe40 6571 * Set up most of a new ssh_channel for SSH-2.
6572 */
6573static void ssh2_channel_init(struct ssh_channel *c)
6574{
6575 Ssh ssh = c->ssh;
6576 c->localid = alloc_channel_id(ssh);
6577 c->closes = 0;
bc06669b 6578 c->pending_eof = FALSE;
94bdfe40 6579 c->throttling_conn = FALSE;
6580 c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
4a693cfc 6581 conf_get_int(ssh->conf, CONF_ssh_simple) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
94bdfe40 6582 c->v.v2.winadj_head = c->v.v2.winadj_tail = NULL;
6583 c->v.v2.throttle_state = UNTHROTTLED;
6584 bufchain_init(&c->v.v2.outbuffer);
6585}
6586
6587/*
2e85c969 6588 * Potentially enlarge the window on an SSH-2 channel.
5471d09a 6589 */
9fca3f8c 6590static void ssh2_set_window(struct ssh_channel *c, int newwin)
5471d09a 6591{
51470298 6592 Ssh ssh = c->ssh;
6593
6b69f42e 6594 /*
bc06669b 6595 * Never send WINDOW_ADJUST for a channel that the remote side has
6596 * already sent EOF on; there's no point, since it won't be
beff003a 6597 * sending any more data anyway. Ditto if _we've_ already sent
6598 * CLOSE.
6b69f42e 6599 */
beff003a 6600 if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
6b69f42e 6601 return;
6602
d252310a 6603 /*
c9739dba 6604 * If the remote end has a habit of ignoring maxpkt, limit the
6605 * window so that it has no choice (assuming it doesn't ignore the
6606 * window as well).
6607 */
6608 if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
6609 newwin = OUR_V2_MAXPKT;
c9739dba 6610
6611 /*
d252310a 6612 * Only send a WINDOW_ADJUST if there's significantly more window
6613 * available than the other end thinks there is. This saves us
6614 * sending a WINDOW_ADJUST for every character in a shell session.
6615 *
6616 * "Significant" is arbitrarily defined as half the window size.
6617 */
3361b80a 6618 if (newwin / 2 >= c->v.v2.locwindow) {
ff3187f6 6619 struct Packet *pktout;
0e443c99 6620 struct winadj *wa;
ff3187f6 6621
0e443c99 6622 /*
6623 * In order to keep track of how much window the client
6624 * actually has available, we'd like it to acknowledge each
6625 * WINDOW_ADJUST. We can't do that directly, so we accompany
6626 * it with a CHANNEL_REQUEST that has to be acknowledged.
6627 *
6628 * This is only necessary if we're opening the window wide.
6629 * If we're not, then throughput is being constrained by
6630 * something other than the maximum window size anyway.
6631 *
6632 * We also only send this if the main channel has finished its
6633 * initial CHANNEL_REQUESTs and installed the default
6634 * CHANNEL_FAILURE handler, so as not to risk giving it
6635 * unexpected CHANNEL_FAILUREs.
6636 */
6637 if (newwin == c->v.v2.locmaxwin &&
6638 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE]) {
6639 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
6640 ssh2_pkt_adduint32(pktout, c->remoteid);
6641 ssh2_pkt_addstring(pktout, "winadj@putty.projects.tartarus.org");
6642 ssh2_pkt_addbool(pktout, TRUE);
6643 ssh2_pkt_send(ssh, pktout);
6644
6645 /*
6646 * CHANNEL_FAILURE doesn't come with any indication of
6647 * what message caused it, so we have to keep track of the
6648 * outstanding CHANNEL_REQUESTs ourselves.
6649 */
6650 wa = snew(struct winadj);
6651 wa->size = newwin - c->v.v2.locwindow;
6652 wa->next = NULL;
6653 if (!c->v.v2.winadj_head)
6654 c->v.v2.winadj_head = wa;
6655 else
6656 c->v.v2.winadj_tail->next = wa;
6657 c->v.v2.winadj_tail = wa;
6658 if (c->v.v2.throttle_state != UNTHROTTLED)
6659 c->v.v2.throttle_state = UNTHROTTLING;
6660 } else {
6661 /* Pretend the WINDOW_ADJUST was acked immediately. */
6662 c->v.v2.remlocwin = newwin;
6663 c->v.v2.throttle_state = THROTTLED;
6664 }
ff3187f6 6665 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
6666 ssh2_pkt_adduint32(pktout, c->remoteid);
6667 ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
6668 ssh2_pkt_send(ssh, pktout);
5471d09a 6669 c->v.v2.locwindow = newwin;
783415f8 6670 }
6671}
6672
e223b7c7 6673/*
6674 * Find the channel associated with a message. If there's no channel,
6675 * or it's not properly open, make a noise about it and return NULL.
6676 */
6677static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
6678{
6679 unsigned localid = ssh_pkt_getuint32(pktin);
6680 struct ssh_channel *c;
6681
6682 c = find234(ssh->channels, &localid, ssh_channelfind);
6683 if (!c ||
6684 (c->halfopen && pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
6685 pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
6686 char *buf = dupprintf("Received %s for %s channel %u",
6687 ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
6688 pktin->type),
6689 c ? "half-open" : "nonexistent", localid);
6690 ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6691 sfree(buf);
6692 return NULL;
6693 }
6694 return c;
6695}
6696
e030765f 6697static int ssh2_handle_winadj_response(struct ssh_channel *c)
6698{
6699 struct winadj *wa = c->v.v2.winadj_head;
6700 if (!wa)
6701 return FALSE;
6702 c->v.v2.winadj_head = wa->next;
6703 c->v.v2.remlocwin += wa->size;
6704 sfree(wa);
6705 /*
6706 * winadj messages are only sent when the window is fully open, so
6707 * if we get an ack of one, we know any pending unthrottle is
6708 * complete.
6709 */
6710 if (c->v.v2.throttle_state == UNTHROTTLING)
6711 c->v.v2.throttle_state = UNTHROTTLED;
997097db 6712 /*
6713 * We may now initiate channel-closing procedures, if that winadj
6714 * was the last thing outstanding before we send CHANNEL_CLOSE.
6715 */
6716 ssh2_channel_check_close(c);
e030765f 6717 return TRUE;
6718}
6719
837d6ba6 6720static void ssh2_msg_channel_success(Ssh ssh, struct Packet *pktin)
6721{
6722 /*
6723 * This should never get called. All channel requests are either
e030765f 6724 * sent with want_reply false, are sent before this handler gets
6725 * installed, or are "winadj@putty" requests, which servers should
6726 * never respond to with success.
6727 *
6728 * However, at least one server ("boks_sshd") is known to return
6729 * SUCCESS for channel requests it's never heard of, such as
6730 * "winadj@putty". Raised with foxt.com as bug 090916-090424, but
6731 * for the sake of a quiet life, we handle it just the same as the
6732 * expected FAILURE.
837d6ba6 6733 */
6734 struct ssh_channel *c;
837d6ba6 6735
6736 c = ssh2_channel_msg(ssh, pktin);
6737 if (!c)
6738 return;
e030765f 6739 if (!ssh2_handle_winadj_response(c))
837d6ba6 6740 ssh_disconnect(ssh, NULL,
6741 "Received unsolicited SSH_MSG_CHANNEL_SUCCESS",
6742 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
6743}
6744
0e443c99 6745static void ssh2_msg_channel_failure(Ssh ssh, struct Packet *pktin)
6746{
6747 /*
6748 * The only time this should get called is for "winadj@putty"
6749 * messages sent above. All other channel requests are either
6750 * sent with want_reply false or are sent before this handler gets
6751 * installed.
6752 */
0e443c99 6753 struct ssh_channel *c;
0e443c99 6754
e223b7c7 6755 c = ssh2_channel_msg(ssh, pktin);
0e443c99 6756 if (!c)
e223b7c7 6757 return;
e030765f 6758 if (!ssh2_handle_winadj_response(c))
837d6ba6 6759 ssh_disconnect(ssh, NULL,
6760 "Received unsolicited SSH_MSG_CHANNEL_FAILURE",
6761 SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
0e443c99 6762}
6763
51df0ab5 6764static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
b09eaa88 6765{
b09eaa88 6766 struct ssh_channel *c;
e223b7c7 6767 c = ssh2_channel_msg(ssh, pktin);
6768 if (!c)
6769 return;
bc06669b 6770 if (!(c->closes & CLOSES_SENT_EOF)) {
b09eaa88 6771 c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
78280721 6772 ssh2_try_send_and_unthrottle(ssh, c);
1bfc7e93 6773 }
b09eaa88 6774}
6775
51df0ab5 6776static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
6777{
6778 char *data;
6d44acc9 6779 int length;
51df0ab5 6780 struct ssh_channel *c;
e223b7c7 6781 c = ssh2_channel_msg(ssh, pktin);
51df0ab5 6782 if (!c)
e223b7c7 6783 return;
51df0ab5 6784 if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
6785 ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
6786 return; /* extended but not stderr */
6787 ssh_pkt_getstring(pktin, &data, &length);
6788 if (data) {
6789 int bufsize = 0;
6790 c->v.v2.locwindow -= length;
0e443c99 6791 c->v.v2.remlocwin -= length;
51df0ab5 6792 switch (c->type) {
6793 case CHAN_MAINSESSION:
6794 bufsize =
6795 from_backend(ssh->frontend, pktin->type ==
6796 SSH2_MSG_CHANNEL_EXTENDED_DATA,
6797 data, length);
6798 break;
6799 case CHAN_X11:
6800 bufsize = x11_send(c->u.x11.s, data, length);
6801 break;
6802 case CHAN_SOCKDATA:
6803 bufsize = pfd_send(c->u.pfd.s, data, length);
6804 break;
6805 case CHAN_AGENT:
6806 while (length > 0) {
6807 if (c->u.a.lensofar < 4) {
62ddb51e 6808 unsigned int l = min(4 - c->u.a.lensofar,
6809 (unsigned)length);
51df0ab5 6810 memcpy(c->u.a.msglen + c->u.a.lensofar,
6811 data, l);
6812 data += l;
6813 length -= l;
6814 c->u.a.lensofar += l;
6815 }
6816 if (c->u.a.lensofar == 4) {
6817 c->u.a.totallen =
6818 4 + GET_32BIT(c->u.a.msglen);
6819 c->u.a.message = snewn(c->u.a.totallen,
6820 unsigned char);
6821 memcpy(c->u.a.message, c->u.a.msglen, 4);
6822 }
6823 if (c->u.a.lensofar >= 4 && length > 0) {
aa63ab7e 6824 unsigned int l =
51df0ab5 6825 min(c->u.a.totallen - c->u.a.lensofar,
62ddb51e 6826 (unsigned)length);
51df0ab5 6827 memcpy(c->u.a.message + c->u.a.lensofar,
6828 data, l);
6829 data += l;
6830 length -= l;
6831 c->u.a.lensofar += l;
6832 }
6833 if (c->u.a.lensofar == c->u.a.totallen) {
6834 void *reply;
6835 int replylen;
6836 if (agent_query(c->u.a.message,
6837 c->u.a.totallen,
6838 &reply, &replylen,
6839 ssh_agentf_callback, c))
6840 ssh_agentf_callback(c, reply, replylen);
6841 sfree(c->u.a.message);
bc06669b 6842 c->u.a.message = NULL;
51df0ab5 6843 c->u.a.lensofar = 0;
6844 }
6845 }
6846 bufsize = 0;
6847 break;
6848 }
6849 /*
0e443c99 6850 * If it looks like the remote end hit the end of its window,
6851 * and we didn't want it to do that, think about using a
6852 * larger window.
6853 */
6854 if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
6855 c->v.v2.locmaxwin < 0x40000000)
6856 c->v.v2.locmaxwin += OUR_V2_WINSIZE;
6857 /*
51df0ab5 6858 * If we are not buffering too much data,
6859 * enlarge the window again at the remote side.
467e064d 6860 * If we are buffering too much, we may still
6861 * need to adjust the window if the server's
6862 * sent excess data.
51df0ab5 6863 */
9b53e9b8 6864 ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
6865 c->v.v2.locmaxwin - bufsize : 0);
ff68564b 6866 /*
6867 * If we're either buffering way too much data, or if we're
6868 * buffering anything at all and we're in "simple" mode,
6869 * throttle the whole channel.
6870 */
6871 if ((bufsize > c->v.v2.locmaxwin ||
4a693cfc 6872 (conf_get_int(ssh->conf, CONF_ssh_simple) && bufsize > 0)) &&
ff68564b 6873 !c->throttling_conn) {
6874 c->throttling_conn = 1;
6875 ssh_throttle_conn(ssh, +1);
6876 }
51df0ab5 6877 }
6878}
6879
bc06669b 6880static void ssh_channel_destroy(struct ssh_channel *c)
51df0ab5 6881{
bc06669b 6882 Ssh ssh = c->ssh;
51df0ab5 6883
bc06669b 6884 switch (c->type) {
6885 case CHAN_MAINSESSION:
6886 ssh->mainchan = NULL;
6887 update_specials_menu(ssh->frontend);
6888 break;
6889 case CHAN_X11:
6890 if (c->u.x11.s != NULL)
6891 x11_close(c->u.x11.s);
6892 logevent("Forwarded X11 connection terminated");
6893 break;
6894 case CHAN_AGENT:
6895 sfree(c->u.a.message);
6896 break;
6897 case CHAN_SOCKDATA:
6898 if (c->u.pfd.s != NULL)
6899 pfd_close(c->u.pfd.s);
6900 logevent("Forwarded port closed");
6901 break;
6902 }
6903
6904 del234(ssh->channels, c);
6905 if (ssh->version == 2)
6906 bufchain_clear(&c->v.v2.outbuffer);
6907 sfree(c);
6908
6909 /*
6910 * See if that was the last channel left open.
6911 * (This is only our termination condition if we're
6912 * not running in -N mode.)
6913 */
6914 if (ssh->version == 2 &&
6915 !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
6916 count234(ssh->channels) == 0) {
6917 /*
6918 * We used to send SSH_MSG_DISCONNECT here,
6919 * because I'd believed that _every_ conforming
6920 * SSH-2 connection had to end with a disconnect
6921 * being sent by at least one side; apparently
6922 * I was wrong and it's perfectly OK to
6923 * unceremoniously slam the connection shut
6924 * when you're done, and indeed OpenSSH feels
6925 * this is more polite than sending a
6926 * DISCONNECT. So now we don't.
6927 */
6928 ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
6929 }
6930}
6931
6932static void ssh2_channel_check_close(struct ssh_channel *c)
6933{
6934 Ssh ssh = c->ssh;
6935 struct Packet *pktout;
6936
6937 if ((c->closes & (CLOSES_SENT_EOF | CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
997097db 6938 == (CLOSES_SENT_EOF | CLOSES_RCVD_EOF) && !c->v.v2.winadj_head) {
bc06669b 6939 /*
997097db 6940 * We have both sent and received EOF, and we have no
6941 * outstanding winadj channel requests, which means the
6942 * channel is in final wind-up. But we haven't sent CLOSE, so
6943 * let's do so now.
bc06669b 6944 */
6945 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
6946 ssh2_pkt_adduint32(pktout, c->remoteid);
6947 ssh2_pkt_send(ssh, pktout);
6948 c->closes |= CLOSES_SENT_CLOSE;
6949 }
6950
6951 if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
6952 /*
6953 * We have both sent and received CLOSE, which means we're
6954 * completely done with the channel.
6955 */
6956 ssh_channel_destroy(c);
6957 }
6958}
6959
6960static void ssh2_channel_got_eof(struct ssh_channel *c)
6961{
6962 if (c->closes & CLOSES_RCVD_EOF)
6963 return; /* already seen EOF */
6964 c->closes |= CLOSES_RCVD_EOF;
51df0ab5 6965
6966 if (c->type == CHAN_X11) {
bc06669b 6967 x11_send_eof(c->u.x11.s);
51df0ab5 6968 } else if (c->type == CHAN_AGENT) {
bc06669b 6969 /* Manufacture an outgoing EOF in response to the incoming one. */
6970 sshfwd_write_eof(c);
51df0ab5 6971 } else if (c->type == CHAN_SOCKDATA) {
bc06669b 6972 pfd_send_eof(c->u.pfd.s);
6973 } else if (c->type == CHAN_MAINSESSION) {
6974 Ssh ssh = c->ssh;
6975
4a202fc6 6976 if (!ssh->sent_console_eof &&
6977 (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
bc06669b 6978 /*
4a202fc6 6979 * Either from_backend_eof told us that the front end
6980 * wants us to close the outgoing side of the connection
6981 * as soon as we see EOF from the far end, or else we've
6982 * unilaterally decided to do that because we've allocated
6983 * a remote pty and hence EOF isn't a particularly
6984 * meaningful concept.
bc06669b 6985 */
6986 sshfwd_write_eof(c);
6987 }
6988 ssh->sent_console_eof = TRUE;
51df0ab5 6989 }
bc06669b 6990
6991 ssh2_channel_check_close(c);
6992}
6993
6994static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
6995{
6996 struct ssh_channel *c;
6997
6998 c = ssh2_channel_msg(ssh, pktin);
6999 if (!c)
7000 return;
7001 ssh2_channel_got_eof(c);
51df0ab5 7002}
7003
7004static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
7005{
51df0ab5 7006 struct ssh_channel *c;
51df0ab5 7007
e223b7c7 7008 c = ssh2_channel_msg(ssh, pktin);
7009 if (!c)
51df0ab5 7010 return;
51df0ab5 7011
7012 /*
bc06669b 7013 * When we receive CLOSE on a channel, we assume it comes with an
7014 * implied EOF if we haven't seen EOF yet.
51df0ab5 7015 */
bc06669b 7016 ssh2_channel_got_eof(c);
7017
7018 /*
3effbcf2 7019 * And we also send an outgoing EOF, if we haven't already, on the
7020 * assumption that CLOSE is a pretty forceful announcement that
7021 * the remote side is doing away with the entire channel. (If it
7022 * had wanted to send us EOF and continue receiving data from us,
7023 * it would have just sent CHANNEL_EOF.)
3effbcf2 7024 */
a699eb41 7025 if (!(c->closes & CLOSES_SENT_EOF)) {
7026 /*
7027 * Make sure we don't read any more from whatever our local
7028 * data source is for this channel.
7029 */
7030 switch (c->type) {
7031 case CHAN_MAINSESSION:
7032 ssh->send_ok = 0; /* stop trying to read from stdin */
7033 break;
7034 case CHAN_X11:
7035 x11_override_throttle(c->u.x11.s, 1);
7036 break;
7037 case CHAN_SOCKDATA:
7038 pfd_override_throttle(c->u.pfd.s, 1);
7039 break;
7040 }
7041
7042 /*
7043 * Send outgoing EOF.
7044 */
7539afa2 7045 sshfwd_write_eof(c);
3effbcf2 7046 }
7047
7048 /*
bc06669b 7049 * Now process the actual close.
7050 */
7051 if (!(c->closes & CLOSES_RCVD_CLOSE)) {
7052 c->closes |= CLOSES_RCVD_CLOSE;
7053 ssh2_channel_check_close(c);
51df0ab5 7054 }
7055}
7056
7057static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
7058{
51df0ab5 7059 struct ssh_channel *c;
51df0ab5 7060
e223b7c7 7061 c = ssh2_channel_msg(ssh, pktin);
51df0ab5 7062 if (!c)
e223b7c7 7063 return;
51df0ab5 7064 if (c->type != CHAN_SOCKDATA_DORMANT)
7065 return; /* dunno why they're confirming this */
7066 c->remoteid = ssh_pkt_getuint32(pktin);
64d6ff88 7067 c->halfopen = FALSE;
51df0ab5 7068 c->type = CHAN_SOCKDATA;
7069 c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7070 c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7071 if (c->u.pfd.s)
7072 pfd_confirm(c->u.pfd.s);
bc06669b 7073 if (c->pending_eof)
7074 ssh_channel_try_eof(c);
51df0ab5 7075}
7076
7077static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
7078{
7079 static const char *const reasons[] = {
7080 "<unknown reason code>",
7081 "Administratively prohibited",
7082 "Connect failed",
7083 "Unknown channel type",
7084 "Resource shortage",
7085 };
51df0ab5 7086 unsigned reason_code;
7087 char *reason_string;
7088 int reason_length;
51df0ab5 7089 struct ssh_channel *c;
e223b7c7 7090 c = ssh2_channel_msg(ssh, pktin);
51df0ab5 7091 if (!c)
e223b7c7 7092 return;
51df0ab5 7093 if (c->type != CHAN_SOCKDATA_DORMANT)
7094 return; /* dunno why they're failing this */
7095
7096 reason_code = ssh_pkt_getuint32(pktin);
7097 if (reason_code >= lenof(reasons))
7098 reason_code = 0; /* ensure reasons[reason_code] in range */
7099 ssh_pkt_getstring(pktin, &reason_string, &reason_length);
fb983202 7100 logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
7101 reasons[reason_code], reason_length, reason_string);
51df0ab5 7102
7103 pfd_close(c->u.pfd.s);
7104
7105 del234(ssh->channels, c);
7106 sfree(c);
7107}
7108
7109static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
7110{
51df0ab5 7111 char *type;
7112 int typelen, want_reply;
7113 int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
7114 struct ssh_channel *c;
7115 struct Packet *pktout;
7116
e223b7c7 7117 c = ssh2_channel_msg(ssh, pktin);
7118 if (!c)
7119 return;
51df0ab5 7120 ssh_pkt_getstring(pktin, &type, &typelen);
7121 want_reply = ssh2_pkt_getbool(pktin);
7122
7123 /*
51df0ab5 7124 * Having got the channel number, we now look at
7125 * the request type string to see if it's something
7126 * we recognise.
7127 */
7128 if (c == ssh->mainchan) {
7129 /*
7130 * We recognise "exit-status" and "exit-signal" on
7131 * the primary channel.
7132 */
7133 if (typelen == 11 &&
7134 !memcmp(type, "exit-status", 11)) {
7135
7136 ssh->exitcode = ssh_pkt_getuint32(pktin);
7137 logeventf(ssh, "Server sent command exit status %d",
7138 ssh->exitcode);
7139 reply = SSH2_MSG_CHANNEL_SUCCESS;
7140
7141 } else if (typelen == 11 &&
7142 !memcmp(type, "exit-signal", 11)) {
7143
7144 int is_plausible = TRUE, is_int = FALSE;
7145 char *fmt_sig = "", *fmt_msg = "";
7146 char *msg;
7147 int msglen = 0, core = FALSE;
7148 /* ICK: older versions of OpenSSH (e.g. 3.4p1)
7149 * provide an `int' for the signal, despite its
bccbeb71 7150 * having been a `string' in the drafts of RFC 4254 since at
51df0ab5 7151 * least 2001. (Fixed in session.c 1.147.) Try to
7152 * infer which we can safely parse it as. */
7153 {
7154 unsigned char *p = pktin->body +
7155 pktin->savedpos;
7156 long len = pktin->length - pktin->savedpos;
7157 unsigned long num = GET_32BIT(p); /* what is it? */
7158 /* If it's 0, it hardly matters; assume string */
7159 if (num == 0) {
7160 is_int = FALSE;
7161 } else {
7162 int maybe_int = FALSE, maybe_str = FALSE;
7163#define CHECK_HYPOTHESIS(offset, result) \
7164 do { \
7165 long q = offset; \
7166 if (q >= 0 && q+4 <= len) { \
7167 q = q + 4 + GET_32BIT(p+q); \
7168 if (q >= 0 && q+4 <= len && \
c849ff23 7169 ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
51df0ab5 7170 result = TRUE; \
7171 } \
7172 } while(0)
7173 CHECK_HYPOTHESIS(4+1, maybe_int);
7174 CHECK_HYPOTHESIS(4+num+1, maybe_str);
7175#undef CHECK_HYPOTHESIS
7176 if (maybe_int && !maybe_str)
7177 is_int = TRUE;
7178 else if (!maybe_int && maybe_str)
7179 is_int = FALSE;
7180 else
7181 /* Crikey. Either or neither. Panic. */
7182 is_plausible = FALSE;
7183 }
7184 }
d051d1b4 7185 ssh->exitcode = 128; /* means `unknown signal' */
51df0ab5 7186 if (is_plausible) {
7187 if (is_int) {
7188 /* Old non-standard OpenSSH. */
7189 int signum = ssh_pkt_getuint32(pktin);
7190 fmt_sig = dupprintf(" %d", signum);
d051d1b4 7191 ssh->exitcode = 128 + signum;
51df0ab5 7192 } else {
bccbeb71 7193 /* As per RFC 4254. */
51df0ab5 7194 char *sig;
7195 int siglen;
7196 ssh_pkt_getstring(pktin, &sig, &siglen);
7197 /* Signal name isn't supposed to be blank, but
7198 * let's cope gracefully if it is. */
7199 if (siglen) {
7200 fmt_sig = dupprintf(" \"%.*s\"",
7201 siglen, sig);
7202 }
d051d1b4 7203
7204 /*
7205 * Really hideous method of translating the
7206 * signal description back into a locally
7207 * meaningful number.
7208 */
7209
7210 if (0)
7211 ;
b707973a 7212#define TRANSLATE_SIGNAL(s) \
7213 else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
7214 ssh->exitcode = 128 + SIG ## s
d051d1b4 7215#ifdef SIGABRT
b707973a 7216 TRANSLATE_SIGNAL(ABRT);
d051d1b4 7217#endif
7218#ifdef SIGALRM
b707973a 7219 TRANSLATE_SIGNAL(ALRM);
d051d1b4 7220#endif
7221#ifdef SIGFPE
b707973a 7222 TRANSLATE_SIGNAL(FPE);
d051d1b4 7223#endif
7224#ifdef SIGHUP
b707973a 7225 TRANSLATE_SIGNAL(HUP);
d051d1b4 7226#endif
7227#ifdef SIGILL
b707973a 7228 TRANSLATE_SIGNAL(ILL);
d051d1b4 7229#endif
7230#ifdef SIGINT
b707973a 7231 TRANSLATE_SIGNAL(INT);
d051d1b4 7232#endif
7233#ifdef SIGKILL
b707973a 7234 TRANSLATE_SIGNAL(KILL);
d051d1b4 7235#endif
7236#ifdef SIGPIPE
b707973a 7237 TRANSLATE_SIGNAL(PIPE);
d051d1b4 7238#endif
7239#ifdef SIGQUIT
b707973a 7240 TRANSLATE_SIGNAL(QUIT);
d051d1b4 7241#endif
7242#ifdef SIGSEGV
b707973a 7243 TRANSLATE_SIGNAL(SEGV);
d051d1b4 7244#endif
7245#ifdef SIGTERM
b707973a 7246 TRANSLATE_SIGNAL(TERM);
d051d1b4 7247#endif
7248#ifdef SIGUSR1
b707973a 7249 TRANSLATE_SIGNAL(USR1);
d051d1b4 7250#endif
7251#ifdef SIGUSR2
b707973a 7252 TRANSLATE_SIGNAL(USR2);
d051d1b4 7253#endif
b707973a 7254#undef TRANSLATE_SIGNAL
d051d1b4 7255 else
7256 ssh->exitcode = 128;
51df0ab5 7257 }
7258 core = ssh2_pkt_getbool(pktin);
7259 ssh_pkt_getstring(pktin, &msg, &msglen);
7260 if (msglen) {
7261 fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
7262 }
7263 /* ignore lang tag */
7264 } /* else don't attempt to parse */
7265 logeventf(ssh, "Server exited on signal%s%s%s",
7266 fmt_sig, core ? " (core dumped)" : "",
7267 fmt_msg);
7268 if (*fmt_sig) sfree(fmt_sig);
7269 if (*fmt_msg) sfree(fmt_msg);
7270 reply = SSH2_MSG_CHANNEL_SUCCESS;
7271
7272 }
7273 } else {
7274 /*
7275 * This is a channel request we don't know
7276 * about, so we now either ignore the request
7277 * or respond with CHANNEL_FAILURE, depending
7278 * on want_reply.
7279 */
7280 reply = SSH2_MSG_CHANNEL_FAILURE;
7281 }
7282 if (want_reply) {
7283 pktout = ssh2_pkt_init(reply);
7284 ssh2_pkt_adduint32(pktout, c->remoteid);
7285 ssh2_pkt_send(ssh, pktout);
7286 }
7287}
7288
7289static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
7290{
7291 char *type;
7292 int typelen, want_reply;
7293 struct Packet *pktout;
7294
7295 ssh_pkt_getstring(pktin, &type, &typelen);
7296 want_reply = ssh2_pkt_getbool(pktin);
7297
7298 /*
7299 * We currently don't support any global requests
7300 * at all, so we either ignore the request or
7301 * respond with REQUEST_FAILURE, depending on
7302 * want_reply.
7303 */
7304 if (want_reply) {
7305 pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
7306 ssh2_pkt_send(ssh, pktout);
7307 }
7308}
7309
7310static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
7311{
7312 char *type;
7313 int typelen;
7314 char *peeraddr;
7315 int peeraddrlen;
7316 int peerport;
7317 char *error = NULL;
7318 struct ssh_channel *c;
7319 unsigned remid, winsize, pktsize;
7320 struct Packet *pktout;
7321
7322 ssh_pkt_getstring(pktin, &type, &typelen);
7323 c = snew(struct ssh_channel);
7324 c->ssh = ssh;
7325
7326 remid = ssh_pkt_getuint32(pktin);
7327 winsize = ssh_pkt_getuint32(pktin);
7328 pktsize = ssh_pkt_getuint32(pktin);
7329
7330 if (typelen == 3 && !memcmp(type, "x11", 3)) {
7331 char *addrstr;
5907ebda 7332 const char *x11err;
51df0ab5 7333
7334 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7335 addrstr = snewn(peeraddrlen+1, char);
7336 memcpy(addrstr, peeraddr, peeraddrlen);
7337 addrstr[peeraddrlen] = '\0';
7338 peerport = ssh_pkt_getuint32(pktin);
7339
7340 logeventf(ssh, "Received X11 connect request from %s:%d",
7341 addrstr, peerport);
7342
7343 if (!ssh->X11_fwd_enabled)
7344 error = "X11 forwarding is not enabled";
5907ebda 7345 else if ((x11err = x11_init(&c->u.x11.s, ssh->x11disp, c,
4a693cfc 7346 addrstr, peerport, ssh->conf)) != NULL) {
5907ebda 7347 logeventf(ssh, "Local X11 connection failed: %s", x11err);
51df0ab5 7348 error = "Unable to open an X11 connection";
7349 } else {
7350 logevent("Opening X11 forward connection succeeded");
7351 c->type = CHAN_X11;
7352 }
7353
7354 sfree(addrstr);
7355 } else if (typelen == 15 &&
7356 !memcmp(type, "forwarded-tcpip", 15)) {
7357 struct ssh_rportfwd pf, *realpf;
7358 char *dummy;
7359 int dummylen;
7360 ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
7361 pf.sport = ssh_pkt_getuint32(pktin);
7362 ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
7363 peerport = ssh_pkt_getuint32(pktin);
7364 realpf = find234(ssh->rportfwds, &pf, NULL);
7365 logeventf(ssh, "Received remote port %d open request "
7366 "from %s:%d", pf.sport, peeraddr, peerport);
7367 if (realpf == NULL) {
7368 error = "Remote port is not recognised";
7369 } else {
7370 const char *e = pfd_newconnect(&c->u.pfd.s,
7371 realpf->dhost,
7372 realpf->dport, c,
4a693cfc 7373 ssh->conf,
05581745 7374 realpf->pfrec->addressfamily);
51df0ab5 7375 logeventf(ssh, "Attempting to forward remote port to "
7376 "%s:%d", realpf->dhost, realpf->dport);
7377 if (e != NULL) {
7378 logeventf(ssh, "Port open failed: %s", e);
7379 error = "Port open failed";
7380 } else {
7381 logevent("Forwarded port opened successfully");
7382 c->type = CHAN_SOCKDATA;
7383 }
7384 }
7385 } else if (typelen == 22 &&
c49cf994 7386 !memcmp(type, "auth-agent@openssh.com", 22)) {
51df0ab5 7387 if (!ssh->agentfwd_enabled)
7388 error = "Agent forwarding is not enabled";
7389 else {
7390 c->type = CHAN_AGENT; /* identify channel type */
7391 c->u.a.lensofar = 0;
7392 }
7393 } else {
7394 error = "Unsupported channel type requested";
7395 }
7396
7397 c->remoteid = remid;
64d6ff88 7398 c->halfopen = FALSE;
51df0ab5 7399 if (error) {
7400 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
7401 ssh2_pkt_adduint32(pktout, c->remoteid);
7402 ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
7403 ssh2_pkt_addstring(pktout, error);
7404 ssh2_pkt_addstring(pktout, "en"); /* language tag */
7405 ssh2_pkt_send(ssh, pktout);
7406 logeventf(ssh, "Rejected channel open: %s", error);
7407 sfree(c);
7408 } else {
94bdfe40 7409 ssh2_channel_init(c);
51df0ab5 7410 c->v.v2.remwindow = winsize;
7411 c->v.v2.remmaxpkt = pktsize;
51df0ab5 7412 add234(ssh->channels, c);
7413 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
7414 ssh2_pkt_adduint32(pktout, c->remoteid);
7415 ssh2_pkt_adduint32(pktout, c->localid);
7416 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
954d5c5a 7417 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
51df0ab5 7418 ssh2_pkt_send(ssh, pktout);
7419 }
7420}
7421
6bbce591 7422/*
adb6167a 7423 * Buffer banner messages for later display at some convenient point,
7424 * if we're going to display them.
6bbce591 7425 */
7426static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
7427{
7428 /* Arbitrary limit to prevent unbounded inflation of buffer */
4a693cfc 7429 if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
adb6167a 7430 bufchain_size(&ssh->banner) <= 131072) {
6bbce591 7431 char *banner = NULL;
7432 int size = 0;
7433 ssh_pkt_getstring(pktin, &banner, &size);
7434 if (banner)
7435 bufchain_add(&ssh->banner, banner, size);
7436 }
7437}
7438
c6ccd5c2 7439/* Helper function to deal with sending tty modes for "pty-req" */
7440static void ssh2_send_ttymode(void *data, char *mode, char *val)
7441{
7442 struct Packet *pktout = (struct Packet *)data;
7443 int i = 0;
7444 unsigned int arg = 0;
7445 while (strcmp(mode, ssh_ttymodes[i].mode) != 0) i++;
7446 if (i == lenof(ssh_ttymodes)) return;
7447 switch (ssh_ttymodes[i].type) {
7448 case TTY_OP_CHAR:
7449 arg = ssh_tty_parse_specchar(val);
7450 break;
7451 case TTY_OP_BOOL:
7452 arg = ssh_tty_parse_boolean(val);
7453 break;
7454 }
7455 ssh2_pkt_addbyte(pktout, ssh_ttymodes[i].opcode);
7456 ssh2_pkt_adduint32(pktout, arg);
7457}
7458
783415f8 7459/*
2e85c969 7460 * Handle the SSH-2 userauth and connection layers.
7cca0d81 7461 */
ff3187f6 7462static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
7463 struct Packet *pktin)
7cca0d81 7464{
51470298 7465 struct do_ssh2_authconn_state {
7466 enum {
51470298 7467 AUTH_TYPE_NONE,
7468 AUTH_TYPE_PUBLICKEY,
7469 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
7470 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
7471 AUTH_TYPE_PASSWORD,
8221906d 7472 AUTH_TYPE_GSSAPI, /* always QUIET */
51470298 7473 AUTH_TYPE_KEYBOARD_INTERACTIVE,
7474 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
7475 } type;
a1a1fae4 7476 int done_service_req;
51470298 7477 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
94cd7c3a 7478 int tried_pubkey_config, done_agent;
bf84a03a 7479#ifndef NO_GSSAPI
42af6a67 7480 int can_gssapi;
7481 int tried_gssapi;
bf84a03a 7482#endif
edd0cb8a 7483 int kbd_inter_refused;
ab18ccff 7484 int we_are_in, userauth_success;
edd0cb8a 7485 prompts_t *cur_prompt;
7486 int num_prompts;
4a693cfc 7487 char *username;
e955d348 7488 char *password;
51470298 7489 int got_username;
51470298 7490 void *publickey_blob;
7491 int publickey_bloblen;
edd0cb8a 7492 int publickey_encrypted;
7493 char *publickey_algorithm;
7494 char *publickey_comment;
94cd7c3a 7495 unsigned char agent_request[5], *agent_response, *agentp;
7496 int agent_responselen;
7497 unsigned char *pkblob_in_agent;
51470298 7498 int keyi, nkeys;
51470298 7499 char *pkblob, *alg, *commentp;
7500 int pklen, alglen, commentlen;
7501 int siglen, retlen, len;
7502 char *q, *agentreq, *ret;
7503 int try_send;
73feed4f 7504 int num_env, env_left, env_ok;
ff3187f6 7505 struct Packet *pktout;
4a693cfc 7506 Filename *keyfile;
bf84a03a 7507#ifndef NO_GSSAPI
b3d375b2 7508 struct ssh_gss_library *gsslib;
42af6a67 7509 Ssh_gss_ctx gss_ctx;
7510 Ssh_gss_buf gss_buf;
7511 Ssh_gss_buf gss_rcvtok, gss_sndtok;
7512 Ssh_gss_name gss_srv_name;
7513 Ssh_gss_stat gss_stat;
bf84a03a 7514#endif
51470298 7515 };
7516 crState(do_ssh2_authconn_state);
7517
7518 crBegin(ssh->do_ssh2_authconn_crstate);
e5574168 7519
a1a1fae4 7520 s->done_service_req = FALSE;
ab18ccff 7521 s->we_are_in = s->userauth_success = FALSE;
bf84a03a 7522#ifndef NO_GSSAPI
42af6a67 7523 s->tried_gssapi = FALSE;
bf84a03a 7524#endif
42af6a67 7525
4a693cfc 7526 if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
a1a1fae4 7527 /*
7528 * Request userauth protocol, and await a response to it.
7529 */
7530 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7531 ssh2_pkt_addstring(s->pktout, "ssh-userauth");
7532 ssh2_pkt_send(ssh, s->pktout);
7533 crWaitUntilV(pktin);
7534 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
7535 s->done_service_req = TRUE;
7536 }
7537 if (!s->done_service_req) {
7538 /*
7539 * Request connection protocol directly, without authentication.
7540 */
7541 s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
7542 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7543 ssh2_pkt_send(ssh, s->pktout);
7544 crWaitUntilV(pktin);
7545 if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
7546 s->we_are_in = TRUE; /* no auth required */
7547 } else {
7548 bombout(("Server refused service request"));
7549 crStopV;
7550 }
8d5de777 7551 }
7cca0d81 7552
94cd7c3a 7553 /* Arrange to be able to deal with any BANNERs that come in.
7554 * (We do this now as packets may come in during the next bit.) */
7555 bufchain_init(&ssh->banner);
7556 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
7557 ssh2_msg_userauth_banner;
7558
7cca0d81 7559 /*
edd0cb8a 7560 * Misc one-time setup for authentication.
7561 */
7562 s->publickey_blob = NULL;
7563 if (!s->we_are_in) {
7564
7565 /*
7566 * Load the public half of any configured public key file
7567 * for later use.
7568 */
4a693cfc 7569 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
962468d4 7570 if (!filename_is_null(s->keyfile)) {
edd0cb8a 7571 int keytype;
7572 logeventf(ssh, "Reading private key file \"%.150s\"",
4a693cfc 7573 filename_to_str(s->keyfile));
7574 keytype = key_type(s->keyfile);
edd0cb8a 7575 if (keytype == SSH_KEYTYPE_SSH2) {
7576 const char *error;
7577 s->publickey_blob =
4a693cfc 7578 ssh2_userkey_loadpub(s->keyfile,
edd0cb8a 7579 &s->publickey_algorithm,
7580 &s->publickey_bloblen,
7581 &s->publickey_comment, &error);
7582 if (s->publickey_blob) {
7583 s->publickey_encrypted =
4a693cfc 7584 ssh2_userkey_encrypted(s->keyfile, NULL);
edd0cb8a 7585 } else {
7586 char *msgbuf;
7587 logeventf(ssh, "Unable to load private key (%s)",
7588 error);
7589 msgbuf = dupprintf("Unable to load private key file "
7590 "\"%.150s\" (%s)\r\n",
4a693cfc 7591 filename_to_str(s->keyfile),
edd0cb8a 7592 error);
7593 c_write_str(ssh, msgbuf);
7594 sfree(msgbuf);
7595 }
7596 } else {
7597 char *msgbuf;
7598 logeventf(ssh, "Unable to use this key file (%s)",
7599 key_type_to_str(keytype));
7600 msgbuf = dupprintf("Unable to use key file \"%.150s\""
7601 " (%s)\r\n",
4a693cfc 7602 filename_to_str(s->keyfile),
edd0cb8a 7603 key_type_to_str(keytype));
7604 c_write_str(ssh, msgbuf);
7605 sfree(msgbuf);
7606 s->publickey_blob = NULL;
7607 }
7608 }
7609
94cd7c3a 7610 /*
7611 * Find out about any keys Pageant has (but if there's a
7612 * public key configured, filter out all others).
7613 */
7614 s->nkeys = 0;
7615 s->agent_response = NULL;
7616 s->pkblob_in_agent = NULL;
4a693cfc 7617 if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
94cd7c3a 7618
7619 void *r;
7620
7621 logevent("Pageant is running. Requesting keys.");
7622
7623 /* Request the keys held by the agent. */
7624 PUT_32BIT(s->agent_request, 1);
7625 s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
7626 if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
7627 ssh_agent_callback, ssh)) {
7628 do {
7629 crReturnV;
7630 if (pktin) {
7631 bombout(("Unexpected data from server while"
7632 " waiting for agent response"));
7633 crStopV;
7634 }
7635 } while (pktin || inlen > 0);
7636 r = ssh->agent_response;
7637 s->agent_responselen = ssh->agent_response_len;
7638 }
7639 s->agent_response = (unsigned char *) r;
7640 if (s->agent_response && s->agent_responselen >= 5 &&
7641 s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
7642 int keyi;
7643 unsigned char *p;
7644 p = s->agent_response + 5;
7645 s->nkeys = GET_32BIT(p);
7646 p += 4;
7647 logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
7648 if (s->publickey_blob) {
7649 /* See if configured key is in agent. */
7650 for (keyi = 0; keyi < s->nkeys; keyi++) {
7651 s->pklen = GET_32BIT(p);
7652 if (s->pklen == s->publickey_bloblen &&
7653 !memcmp(p+4, s->publickey_blob,
7654 s->publickey_bloblen)) {
7655 logeventf(ssh, "Pageant key #%d matches "
7656 "configured key file", keyi);
7657 s->keyi = keyi;
7658 s->pkblob_in_agent = p;
7659 break;
7660 }
7661 p += 4 + s->pklen;
7662 p += GET_32BIT(p) + 4; /* comment */
7663 }
7664 if (!s->pkblob_in_agent) {
7665 logevent("Configured key file not in Pageant");
7666 s->nkeys = 0;
7667 }
7668 }
5ff99b8e 7669 } else {
7670 logevent("Failed to get reply from Pageant");
94cd7c3a 7671 }
7672 }
7673
edd0cb8a 7674 }
7675
7676 /*
1408a877 7677 * We repeat this whole loop, including the username prompt,
7678 * until we manage a successful authentication. If the user
51470298 7679 * types the wrong _password_, they can be sent back to the
7680 * beginning to try another username, if this is configured on.
7681 * (If they specify a username in the config, they are never
7682 * asked, even if they do give a wrong password.)
1408a877 7683 *
7684 * I think this best serves the needs of
7685 *
7686 * - the people who have no configuration, no keys, and just
7687 * want to try repeated (username,password) pairs until they
7688 * type both correctly
7689 *
7690 * - people who have keys and configuration but occasionally
7691 * need to fall back to passwords
7692 *
7693 * - people with a key held in Pageant, who might not have
7694 * logged in to a particular machine before; so they want to
7695 * type a username, and then _either_ their key will be
7696 * accepted, _or_ they will type a password. If they mistype
7697 * the username they will want to be able to get back and
7698 * retype it!
7cca0d81 7699 */
51470298 7700 s->got_username = FALSE;
a1a1fae4 7701 while (!s->we_are_in) {
1408a877 7702 /*
7703 * Get a username.
7704 */
4a693cfc 7705 if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
5bb641e1 7706 /*
7707 * We got a username last time round this loop, and
7708 * with change_username turned off we don't try to get
7709 * it again.
7710 */
4a693cfc 7711 } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
edd0cb8a 7712 int ret; /* need not be kept over crReturn */
7713 s->cur_prompt = new_prompts(ssh->frontend);
7714 s->cur_prompt->to_server = TRUE;
7715 s->cur_prompt->name = dupstr("SSH login name");
b61f81bc 7716 add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
edd0cb8a 7717 ret = get_userpass_input(s->cur_prompt, NULL, 0);
7718 while (ret < 0) {
51470298 7719 ssh->send_ok = 1;
edd0cb8a 7720 crWaitUntilV(!pktin);
7721 ret = get_userpass_input(s->cur_prompt, in, inlen);
7722 ssh->send_ok = 0;
32874aea 7723 }
edd0cb8a 7724 if (!ret) {
7725 /*
7726 * get_userpass_input() failed to get a username.
7727 * Terminate.
7728 */
7729 free_prompts(s->cur_prompt);
7730 ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
7731 crStopV;
7732 }
4a693cfc 7733 ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
edd0cb8a 7734 free_prompts(s->cur_prompt);
7cca0d81 7735 } else {
57356d63 7736 char *stuff;
65a22376 7737 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
4a693cfc 7738 stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
51470298 7739 c_write_str(ssh, stuff);
57356d63 7740 sfree(stuff);
7cca0d81 7741 }
7742 }
51470298 7743 s->got_username = TRUE;
7cca0d81 7744
65a22376 7745 /*
1408a877 7746 * Send an authentication request using method "none": (a)
7747 * just in case it succeeds, and (b) so that we know what
7748 * authentication methods we can usefully try next.
65a22376 7749 */
acab36bc 7750 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
51470298 7751
ff3187f6 7752 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4a693cfc 7753 ssh2_pkt_addstring(s->pktout, ssh->username);
ff3187f6 7754 ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
7755 ssh2_pkt_addstring(s->pktout, "none"); /* method */
7756 ssh2_pkt_send(ssh, s->pktout);
51470298 7757 s->type = AUTH_TYPE_NONE;
7758 s->gotit = FALSE;
7759 s->we_are_in = FALSE;
7760
7761 s->tried_pubkey_config = FALSE;
6ac3a551 7762 s->kbd_inter_refused = FALSE;
65a22376 7763
94cd7c3a 7764 /* Reset agent request state. */
7765 s->done_agent = FALSE;
7766 if (s->agent_response) {
7767 if (s->pkblob_in_agent) {
7768 s->agentp = s->pkblob_in_agent;
7769 } else {
7770 s->agentp = s->agent_response + 5 + 4;
7771 s->keyi = 0;
7772 }
7773 }
7774
1408a877 7775 while (1) {
854caca5 7776 char *methods = NULL;
7777 int methlen = 0;
7778
1408a877 7779 /*
7780 * Wait for the result of the last authentication request.
7781 */
51470298 7782 if (!s->gotit)
ff3187f6 7783 crWaitUntilV(pktin);
6bbce591 7784 /*
7785 * Now is a convenient point to spew any banner material
7786 * that we've accumulated. (This should ensure that when
7787 * we exit the auth loop, we haven't any left to deal
7788 * with.)
7789 */
7790 {
7791 int size = bufchain_size(&ssh->banner);
32874aea 7792 /*
7793 * Don't show the banner if we're operating in
7794 * non-verbose non-interactive mode. (It's probably
7795 * a script, which means nobody will read the
7796 * banner _anyway_, and moreover the printing of
7797 * the banner will screw up processing on the
7798 * output of (say) plink.)
7799 */
6bbce591 7800 if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
7801 char *banner = snewn(size, char);
7802 bufchain_fetch(&ssh->banner, banner, size);
7803 c_write_untrusted(ssh, banner, size);
7804 sfree(banner);
32874aea 7805 }
6bbce591 7806 bufchain_clear(&ssh->banner);
1408a877 7807 }
ff3187f6 7808 if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
1408a877 7809 logevent("Access granted");
ab18ccff 7810 s->we_are_in = s->userauth_success = TRUE;
1408a877 7811 break;
7812 }
65a22376 7813
42af6a67 7814 if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
e955d348 7815 bombout(("Strange packet received during authentication: "
7816 "type %d", pktin->type));
7ffdbc1a 7817 crStopV;
65a22376 7818 }
7819
51470298 7820 s->gotit = FALSE;
65a22376 7821
1408a877 7822 /*
7823 * OK, we're now sitting on a USERAUTH_FAILURE message, so
7824 * we can look at the string in it and know what we can
7825 * helpfully try next.
7826 */
ff3187f6 7827 if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
ff3187f6 7828 ssh_pkt_getstring(pktin, &methods, &methlen);
ff3187f6 7829 if (!ssh2_pkt_getbool(pktin)) {
1408a877 7830 /*
7831 * We have received an unequivocal Access
7832 * Denied. This can translate to a variety of
8221906d 7833 * messages, or no message at all.
7834 *
7835 * For forms of authentication which are attempted
7836 * implicitly, by which I mean without printing
7837 * anything in the window indicating that we're
7838 * trying them, we should never print 'Access
7839 * denied'.
7840 *
7841 * If we do print a message saying that we're
7842 * attempting some kind of authentication, it's OK
7843 * to print a followup message saying it failed -
7844 * but the message may sometimes be more specific
7845 * than simply 'Access denied'.
7846 *
1408a877 7847 * Additionally, if we'd just tried password
7848 * authentication, we should break out of this
7849 * whole loop so as to go back to the username
91f57d1f 7850 * prompt (iff we're configured to allow
7851 * username change attempts).
1408a877 7852 */
51470298 7853 if (s->type == AUTH_TYPE_NONE) {
1408a877 7854 /* do nothing */
51470298 7855 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
7856 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
7857 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
7858 c_write_str(ssh, "Server refused our key\r\n");
8221906d 7859 logevent("Server refused our key");
7860 } else if (s->type == AUTH_TYPE_PUBLICKEY) {
7861 /* This _shouldn't_ happen except by a
7862 * protocol bug causing client and server to
7863 * disagree on what is a correct signature. */
7864 c_write_str(ssh, "Server refused public-key signature"
7865 " despite accepting key!\r\n");
7866 logevent("Server refused public-key signature"
7867 " despite accepting key!");
51470298 7868 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
8221906d 7869 /* quiet, so no c_write */
7870 logevent("Server refused keyboard-interactive authentication");
7871 } else if (s->type==AUTH_TYPE_GSSAPI) {
7872 /* always quiet, so no c_write */
2af4fe8f 7873 /* also, the code down in the GSSAPI block has
7874 * already logged this in the Event Log */
8221906d 7875 } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
7876 logevent("Keyboard-interactive authentication failed");
7877 c_write_str(ssh, "Access denied\r\n");
7878 } else {
7879 assert(s->type == AUTH_TYPE_PASSWORD);
7880 logevent("Password authentication failed");
51470298 7881 c_write_str(ssh, "Access denied\r\n");
8221906d 7882
7883 if (conf_get_int(ssh->conf, CONF_change_username)) {
6c9dce7c 7884 /* XXX perhaps we should allow
7885 * keyboard-interactive to do this too? */
51470298 7886 s->we_are_in = FALSE;
1408a877 7887 break;
7888 }
7889 }
7890 } else {
51470298 7891 c_write_str(ssh, "Further authentication required\r\n");
1408a877 7892 logevent("Further authentication required");
7893 }
65a22376 7894
51470298 7895 s->can_pubkey =
32874aea 7896 in_commasep_string("publickey", methods, methlen);
51470298 7897 s->can_passwd =
32874aea 7898 in_commasep_string("password", methods, methlen);
4a693cfc 7899 s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
761187b6 7900 in_commasep_string("keyboard-interactive", methods, methlen);
1e00c92b 7901#ifndef NO_GSSAPI
7902 if (!ssh->gsslibs)
4a693cfc 7903 ssh->gsslibs = ssh_gss_setup(ssh->conf);
7904 s->can_gssapi = conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
b3d375b2 7905 in_commasep_string("gssapi-with-mic", methods, methlen) &&
1e00c92b 7906 ssh->gsslibs->nlibraries > 0;
42af6a67 7907#endif
1408a877 7908 }
65a22376 7909
acab36bc 7910 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
65a22376 7911
94cd7c3a 7912 if (s->can_pubkey && !s->done_agent && s->nkeys) {
0405e71f 7913
1983e559 7914 /*
94cd7c3a 7915 * Attempt public-key authentication using a key from Pageant.
1983e559 7916 */
1983e559 7917
acab36bc 7918 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
00db133f 7919
94cd7c3a 7920 logeventf(ssh, "Trying Pageant key #%d", s->keyi);
7921
7922 /* Unpack key from agent response */
7923 s->pklen = GET_32BIT(s->agentp);
7924 s->agentp += 4;
7925 s->pkblob = (char *)s->agentp;
7926 s->agentp += s->pklen;
7927 s->alglen = GET_32BIT(s->pkblob);
7928 s->alg = s->pkblob + 4;
7929 s->commentlen = GET_32BIT(s->agentp);
7930 s->agentp += 4;
7931 s->commentp = (char *)s->agentp;
7932 s->agentp += s->commentlen;
7933 /* s->agentp now points at next key, if any */
7934
7935 /* See if server will accept it */
7936 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4a693cfc 7937 ssh2_pkt_addstring(s->pktout, ssh->username);
94cd7c3a 7938 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7939 /* service requested */
7940 ssh2_pkt_addstring(s->pktout, "publickey");
7941 /* method */
7942 ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
7943 ssh2_pkt_addstring_start(s->pktout);
7944 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7945 ssh2_pkt_addstring_start(s->pktout);
7946 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7947 ssh2_pkt_send(ssh, s->pktout);
7948 s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
1983e559 7949
94cd7c3a 7950 crWaitUntilV(pktin);
7951 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
1983e559 7952
94cd7c3a 7953 /* Offer of key refused. */
7954 s->gotit = TRUE;
1983e559 7955
94cd7c3a 7956 } else {
7957
7958 void *vret;
1983e559 7959
94cd7c3a 7960 if (flags & FLAG_VERBOSE) {
7961 c_write_str(ssh, "Authenticating with "
7962 "public key \"");
7963 c_write(ssh, s->commentp, s->commentlen);
7964 c_write_str(ssh, "\" from agent\r\n");
7965 }
1983e559 7966
94cd7c3a 7967 /*
7968 * Server is willing to accept the key.
7969 * Construct a SIGN_REQUEST.
7970 */
7971 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4a693cfc 7972 ssh2_pkt_addstring(s->pktout, ssh->username);
94cd7c3a 7973 ssh2_pkt_addstring(s->pktout, "ssh-connection");
7974 /* service requested */
7975 ssh2_pkt_addstring(s->pktout, "publickey");
7976 /* method */
7977 ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
7978 ssh2_pkt_addstring_start(s->pktout);
7979 ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
7980 ssh2_pkt_addstring_start(s->pktout);
7981 ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
7982
7983 /* Ask agent for signature. */
7984 s->siglen = s->pktout->length - 5 + 4 +
7985 ssh->v2_session_id_len;
7986 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
7987 s->siglen -= 4;
7988 s->len = 1; /* message type */
7989 s->len += 4 + s->pklen; /* key blob */
7990 s->len += 4 + s->siglen; /* data to sign */
7991 s->len += 4; /* flags */
7992 s->agentreq = snewn(4 + s->len, char);
7993 PUT_32BIT(s->agentreq, s->len);
7994 s->q = s->agentreq + 4;
7995 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
7996 PUT_32BIT(s->q, s->pklen);
7997 s->q += 4;
7998 memcpy(s->q, s->pkblob, s->pklen);
7999 s->q += s->pklen;
8000 PUT_32BIT(s->q, s->siglen);
8001 s->q += 4;
8002 /* Now the data to be signed... */
8003 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8004 PUT_32BIT(s->q, ssh->v2_session_id_len);
51470298 8005 s->q += 4;
94cd7c3a 8006 }
8007 memcpy(s->q, ssh->v2_session_id,
8008 ssh->v2_session_id_len);
8009 s->q += ssh->v2_session_id_len;
8010 memcpy(s->q, s->pktout->data + 5,
8011 s->pktout->length - 5);
8012 s->q += s->pktout->length - 5;
8013 /* And finally the (zero) flags word. */
8014 PUT_32BIT(s->q, 0);
8015 if (!agent_query(s->agentreq, s->len + 4,
8016 &vret, &s->retlen,
8017 ssh_agent_callback, ssh)) {
8018 do {
8019 crReturnV;
8020 if (pktin) {
8021 bombout(("Unexpected data from server"
8022 " while waiting for agent"
8023 " response"));
8024 crStopV;
1983e559 8025 }
94cd7c3a 8026 } while (pktin || inlen > 0);
8027 vret = ssh->agent_response;
8028 s->retlen = ssh->agent_response_len;
8029 }
8030 s->ret = vret;
8031 sfree(s->agentreq);
8032 if (s->ret) {
8033 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
8034 logevent("Sending Pageant's response");
8035 ssh2_add_sigblob(ssh, s->pktout,
8036 s->pkblob, s->pklen,
8037 s->ret + 9,
8038 GET_32BIT(s->ret + 5));
8039 ssh2_pkt_send(ssh, s->pktout);
8040 s->type = AUTH_TYPE_PUBLICKEY;
8041 } else {
8042 /* FIXME: less drastic response */
8043 bombout(("Pageant failed to answer challenge"));
8044 crStopV;
1983e559 8045 }
8046 }
1983e559 8047 }
94cd7c3a 8048
8049 /* Do we have any keys left to try? */
8050 if (s->pkblob_in_agent) {
8051 s->done_agent = TRUE;
8052 s->tried_pubkey_config = TRUE;
8053 } else {
8054 s->keyi++;
8055 if (s->keyi >= s->nkeys)
8056 s->done_agent = TRUE;
8057 }
1983e559 8058
edd0cb8a 8059 } else if (s->can_pubkey && s->publickey_blob &&
8060 !s->tried_pubkey_config) {
65a22376 8061
edd0cb8a 8062 struct ssh2_userkey *key; /* not live over crReturn */
8063 char *passphrase; /* not live over crReturn */
65a22376 8064
acab36bc 8065 ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
00db133f 8066
edd0cb8a 8067 s->tried_pubkey_config = TRUE;
8068
65a22376 8069 /*
1408a877 8070 * Try the public key supplied in the configuration.
8071 *
8072 * First, offer the public blob to see if the server is
8073 * willing to accept it.
65a22376 8074 */
ff3187f6 8075 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4a693cfc 8076 ssh2_pkt_addstring(s->pktout, ssh->username);
edd0cb8a 8077 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8078 /* service requested */
8079 ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
8080 ssh2_pkt_addbool(s->pktout, FALSE);
8081 /* no signature included */
8082 ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
8083 ssh2_pkt_addstring_start(s->pktout);
8084 ssh2_pkt_addstring_data(s->pktout,
8085 (char *)s->publickey_blob,
8086 s->publickey_bloblen);
ff3187f6 8087 ssh2_pkt_send(ssh, s->pktout);
edd0cb8a 8088 logevent("Offered public key");
ff3187f6 8089
8090 crWaitUntilV(pktin);
edd0cb8a 8091 if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
8092 /* Key refused. Give up. */
8093 s->gotit = TRUE; /* reconsider message next loop */
8094 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
8095 continue; /* process this new message */
45068b27 8096 }
edd0cb8a 8097 logevent("Offer of public key accepted");
af659722 8098
45068b27 8099 /*
edd0cb8a 8100 * Actually attempt a serious authentication using
8101 * the key.
45068b27 8102 */
edd0cb8a 8103 if (flags & FLAG_VERBOSE) {
8104 c_write_str(ssh, "Authenticating with public key \"");
8105 c_write_str(ssh, s->publickey_comment);
8106 c_write_str(ssh, "\"\r\n");
8107 }
8108 key = NULL;
8109 while (!key) {
8110 const char *error; /* not live over crReturn */
8111 if (s->publickey_encrypted) {
8112 /*
8113 * Get a passphrase from the user.
8114 */
8115 int ret; /* need not be kept over crReturn */
8116 s->cur_prompt = new_prompts(ssh->frontend);
8117 s->cur_prompt->to_server = FALSE;
8118 s->cur_prompt->name = dupstr("SSH key passphrase");
8119 add_prompt(s->cur_prompt,
8120 dupprintf("Passphrase for key \"%.100s\": ",
8121 s->publickey_comment),
b61f81bc 8122 FALSE);
edd0cb8a 8123 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8124 while (ret < 0) {
8125 ssh->send_ok = 1;
8126 crWaitUntilV(!pktin);
8127 ret = get_userpass_input(s->cur_prompt,
8128 in, inlen);
8129 ssh->send_ok = 0;
8130 }
8131 if (!ret) {
8132 /* Failed to get a passphrase. Terminate. */
8133 free_prompts(s->cur_prompt);
8134 ssh_disconnect(ssh, NULL,
8135 "Unable to authenticate",
8136 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8137 TRUE);
8138 crStopV;
85fdbe25 8139 }
edd0cb8a 8140 passphrase =
8141 dupstr(s->cur_prompt->prompts[0]->result);
8142 free_prompts(s->cur_prompt);
45068b27 8143 } else {
edd0cb8a 8144 passphrase = NULL; /* no passphrase needed */
45068b27 8145 }
1408a877 8146
edd0cb8a 8147 /*
8148 * Try decrypting the key.
8149 */
4a693cfc 8150 s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
8151 key = ssh2_load_userkey(s->keyfile, passphrase, &error);
edd0cb8a 8152 if (passphrase) {
8153 /* burn the evidence */
dfb88efd 8154 smemclr(passphrase, strlen(passphrase));
edd0cb8a 8155 sfree(passphrase);
8156 }
8157 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
8158 if (passphrase &&
8159 (key == SSH2_WRONG_PASSPHRASE)) {
8160 c_write_str(ssh, "Wrong passphrase\r\n");
8161 key = NULL;
8162 /* and loop again */
8163 } else {
8164 c_write_str(ssh, "Unable to load private key (");
8165 c_write_str(ssh, error);
8166 c_write_str(ssh, ")\r\n");
8167 key = NULL;
8168 break; /* try something else */
8169 }
1408a877 8170 }
65a22376 8171 }
65a22376 8172
edd0cb8a 8173 if (key) {
1dd353b5 8174 unsigned char *pkblob, *sigblob, *sigdata;
8175 int pkblob_len, sigblob_len, sigdata_len;
edd0cb8a 8176 int p;
65a22376 8177
1408a877 8178 /*
8179 * We have loaded the private key and the server
8180 * has announced that it's willing to accept it.
8181 * Hallelujah. Generate a signature and send it.
8182 */
ff3187f6 8183 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4a693cfc 8184 ssh2_pkt_addstring(s->pktout, ssh->username);
edd0cb8a 8185 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8186 /* service requested */
8187 ssh2_pkt_addstring(s->pktout, "publickey");
8188 /* method */
ff3187f6 8189 ssh2_pkt_addbool(s->pktout, TRUE);
edd0cb8a 8190 /* signature follows */
ff3187f6 8191 ssh2_pkt_addstring(s->pktout, key->alg->name);
edd0cb8a 8192 pkblob = key->alg->public_blob(key->data,
8193 &pkblob_len);
ff3187f6 8194 ssh2_pkt_addstring_start(s->pktout);
edd0cb8a 8195 ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
8196 pkblob_len);
1408a877 8197
8198 /*
8199 * The data to be signed is:
8200 *
8201 * string session-id
8202 *
8203 * followed by everything so far placed in the
8204 * outgoing packet.
8205 */
b672f405 8206 sigdata_len = s->pktout->length - 5 + 4 +
8207 ssh->v2_session_id_len;
edd0cb8a 8208 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
8209 sigdata_len -= 4;
92d60585 8210 sigdata = snewn(sigdata_len, unsigned char);
edd0cb8a 8211 p = 0;
8212 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
8213 PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
8214 p += 4;
8215 }
b672f405 8216 memcpy(sigdata+p, ssh->v2_session_id,
8217 ssh->v2_session_id_len);
8218 p += ssh->v2_session_id_len;
ff3187f6 8219 memcpy(sigdata+p, s->pktout->data + 5,
8220 s->pktout->length - 5);
edd0cb8a 8221 p += s->pktout->length - 5;
8222 assert(p == sigdata_len);
d8baa528 8223 sigblob = key->alg->sign(key->data, (char *)sigdata,
1dd353b5 8224 sigdata_len, &sigblob_len);
ff3187f6 8225 ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
1dd353b5 8226 sigblob, sigblob_len);
8227 sfree(pkblob);
8228 sfree(sigblob);
1408a877 8229 sfree(sigdata);
8230
ff3187f6 8231 ssh2_pkt_send(ssh, s->pktout);
8221906d 8232 logevent("Sent public key signature");
51470298 8233 s->type = AUTH_TYPE_PUBLICKEY;
75374b2f 8234 key->alg->freekey(key->data);
1408a877 8235 }
edd0cb8a 8236
42af6a67 8237#ifndef NO_GSSAPI
8238 } else if (s->can_gssapi && !s->tried_gssapi) {
8239
8240 /* GSSAPI Authentication */
8241
86557057 8242 int micoffset, len;
8243 char *data;
42af6a67 8244 Ssh_gss_buf mic;
8245 s->type = AUTH_TYPE_GSSAPI;
8246 s->tried_gssapi = TRUE;
8247 s->gotit = TRUE;
8248 ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
8249
b3d375b2 8250 /*
8251 * Pick the highest GSS library on the preference
8252 * list.
8253 */
8254 {
8255 int i, j;
8256 s->gsslib = NULL;
8257 for (i = 0; i < ngsslibs; i++) {
4a693cfc 8258 int want_id = conf_get_int_int(ssh->conf,
8259 CONF_ssh_gsslist, i);
1e00c92b 8260 for (j = 0; j < ssh->gsslibs->nlibraries; j++)
8261 if (ssh->gsslibs->libraries[j].id == want_id) {
8262 s->gsslib = &ssh->gsslibs->libraries[j];
b3d375b2 8263 goto got_gsslib; /* double break */
8264 }
8265 }
8266 got_gsslib:
8267 /*
8268 * We always expect to have found something in
8269 * the above loop: we only came here if there
8270 * was at least one viable GSS library, and the
8271 * preference list should always mention
8272 * everything and only change the order.
8273 */
8274 assert(s->gsslib);
8275 }
8276
8277 if (s->gsslib->gsslogmsg)
8278 logevent(s->gsslib->gsslogmsg);
8279
42af6a67 8280 /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
8281 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4a693cfc 8282 ssh2_pkt_addstring(s->pktout, ssh->username);
42af6a67 8283 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8284 ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
8221906d 8285 logevent("Attempting GSSAPI authentication");
42af6a67 8286
8287 /* add mechanism info */
b3d375b2 8288 s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
42af6a67 8289
8290 /* number of GSSAPI mechanisms */
8291 ssh2_pkt_adduint32(s->pktout,1);
8292
8293 /* length of OID + 2 */
86557057 8294 ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
42af6a67 8295 ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
8296
8297 /* length of OID */
86557057 8298 ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
42af6a67 8299
86557057 8300 ssh_pkt_adddata(s->pktout, s->gss_buf.value,
8301 s->gss_buf.length);
42af6a67 8302 ssh2_pkt_send(ssh, s->pktout);
8303 crWaitUntilV(pktin);
8304 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
8305 logevent("GSSAPI authentication request refused");
8306 continue;
8307 }
8308
8309 /* check returned packet ... */
8310
86557057 8311 ssh_pkt_getstring(pktin, &data, &len);
8312 s->gss_rcvtok.value = data;
8313 s->gss_rcvtok.length = len;
8314 if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
8315 ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
8316 ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
8317 memcmp((char *)s->gss_rcvtok.value + 2,
8318 s->gss_buf.value,s->gss_buf.length) ) {
42af6a67 8319 logevent("GSSAPI authentication - wrong response from server");
8320 continue;
8321 }
8322
8323 /* now start running */
b3d375b2 8324 s->gss_stat = s->gsslib->import_name(s->gsslib,
8325 ssh->fullhostname,
8326 &s->gss_srv_name);
42af6a67 8327 if (s->gss_stat != SSH_GSS_OK) {
8328 if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
8329 logevent("GSSAPI import name failed - Bad service name");
8330 else
8331 logevent("GSSAPI import name failed");
8332 continue;
8333 }
8334
8335 /* fetch TGT into GSS engine */
b3d375b2 8336 s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
42af6a67 8337
8338 if (s->gss_stat != SSH_GSS_OK) {
8339 logevent("GSSAPI authentication failed to get credentials");
b3d375b2 8340 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
42af6a67 8341 continue;
8342 }
8343
8344 /* initial tokens are empty */
86557057 8345 SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
99a3b3c9 8346 SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
42af6a67 8347
8348 /* now enter the loop */
8349 do {
b3d375b2 8350 s->gss_stat = s->gsslib->init_sec_context
8351 (s->gsslib,
8352 &s->gss_ctx,
8353 s->gss_srv_name,
4a693cfc 8354 conf_get_int(ssh->conf, CONF_gssapifwd),
b3d375b2 8355 &s->gss_rcvtok,
8356 &s->gss_sndtok);
42af6a67 8357
8358 if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
8359 s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
8360 logevent("GSSAPI authentication initialisation failed");
8361
b3d375b2 8362 if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
8363 &s->gss_buf) == SSH_GSS_OK) {
86557057 8364 logevent(s->gss_buf.value);
8365 sfree(s->gss_buf.value);
42af6a67 8366 }
8367
8368 break;
8369 }
8370 logevent("GSSAPI authentication initialised");
8371
8372 /* Client and server now exchange tokens until GSSAPI
8373 * no longer says CONTINUE_NEEDED */
8374
86557057 8375 if (s->gss_sndtok.length != 0) {
42af6a67 8376 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
8377 ssh_pkt_addstring_start(s->pktout);
86557057 8378 ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
42af6a67 8379 ssh2_pkt_send(ssh, s->pktout);
b3d375b2 8380 s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
42af6a67 8381 }
8382
8383 if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
8384 crWaitUntilV(pktin);
8385 if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
8386 logevent("GSSAPI authentication - bad server response");
8387 s->gss_stat = SSH_GSS_FAILURE;
8388 break;
8389 }
86557057 8390 ssh_pkt_getstring(pktin, &data, &len);
8391 s->gss_rcvtok.value = data;
8392 s->gss_rcvtok.length = len;
42af6a67 8393 }
8394 } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
8395
8396 if (s->gss_stat != SSH_GSS_OK) {
b3d375b2 8397 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8398 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
42af6a67 8399 continue;
8400 }
8401 logevent("GSSAPI authentication loop finished OK");
8402
8403 /* Now send the MIC */
8404
8405 s->pktout = ssh2_pkt_init(0);
8406 micoffset = s->pktout->length;
8407 ssh_pkt_addstring_start(s->pktout);
8408 ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
8409 ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
4a693cfc 8410 ssh_pkt_addstring(s->pktout, ssh->username);
42af6a67 8411 ssh_pkt_addstring(s->pktout, "ssh-connection");
8412 ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
8413
86557057 8414 s->gss_buf.value = (char *)s->pktout->data + micoffset;
8415 s->gss_buf.length = s->pktout->length - micoffset;
42af6a67 8416
b3d375b2 8417 s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
42af6a67 8418 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
8419 ssh_pkt_addstring_start(s->pktout);
86557057 8420 ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
42af6a67 8421 ssh2_pkt_send(ssh, s->pktout);
b3d375b2 8422 s->gsslib->free_mic(s->gsslib, &mic);
42af6a67 8423
8424 s->gotit = FALSE;
8425
b3d375b2 8426 s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
8427 s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
42af6a67 8428 continue;
8429#endif
edd0cb8a 8430 } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
8431
8432 /*
8433 * Keyboard-interactive authentication.
8434 */
edd0cb8a 8435
edd0cb8a 8436 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
8437
acab36bc 8438 ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
edd0cb8a 8439
8440 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4a693cfc 8441 ssh2_pkt_addstring(s->pktout, ssh->username);
edd0cb8a 8442 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8443 /* service requested */
8444 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
8445 /* method */
8446 ssh2_pkt_addstring(s->pktout, ""); /* lang */
8447 ssh2_pkt_addstring(s->pktout, ""); /* submethods */
8448 ssh2_pkt_send(ssh, s->pktout);
8221906d 8449
8450 logevent("Attempting keyboard-interactive authentication");
edd0cb8a 8451
8452 crWaitUntilV(pktin);
8453 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
8454 /* Server is not willing to do keyboard-interactive
b8e3173d 8455 * at all (or, bizarrely but legally, accepts the
8456 * user without actually issuing any prompts).
8457 * Give up on it entirely. */
edd0cb8a 8458 s->gotit = TRUE;
edd0cb8a 8459 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
8460 s->kbd_inter_refused = TRUE; /* don't try it again */
8461 continue;
8462 }
8463
8464 /*
b8e3173d 8465 * Loop while the server continues to send INFO_REQUESTs.
edd0cb8a 8466 */
b8e3173d 8467 while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
edd0cb8a 8468
b8e3173d 8469 char *name, *inst, *lang;
8470 int name_len, inst_len, lang_len;
8471 int i;
8472
8473 /*
8474 * We've got a fresh USERAUTH_INFO_REQUEST.
8475 * Get the preamble and start building a prompt.
8476 */
8477 ssh_pkt_getstring(pktin, &name, &name_len);
8478 ssh_pkt_getstring(pktin, &inst, &inst_len);
8479 ssh_pkt_getstring(pktin, &lang, &lang_len);
8480 s->cur_prompt = new_prompts(ssh->frontend);
8481 s->cur_prompt->to_server = TRUE;
edd0cb8a 8482
b8e3173d 8483 /*
9ea10e78 8484 * Get any prompt(s) from the packet.
b8e3173d 8485 */
8486 s->num_prompts = ssh_pkt_getuint32(pktin);
8487 for (i = 0; i < s->num_prompts; i++) {
8488 char *prompt;
8489 int prompt_len;
8490 int echo;
8491 static char noprompt[] =
8492 "<server failed to send prompt>: ";
8493
8494 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8495 echo = ssh2_pkt_getbool(pktin);
8496 if (!prompt_len) {
8497 prompt = noprompt;
8498 prompt_len = lenof(noprompt)-1;
8499 }
8500 add_prompt(s->cur_prompt,
8501 dupprintf("%.*s", prompt_len, prompt),
b61f81bc 8502 echo);
edd0cb8a 8503 }
b8e3173d 8504
9874c9d7 8505 if (name_len) {
8506 /* FIXME: better prefix to distinguish from
8507 * local prompts? */
8508 s->cur_prompt->name =
8509 dupprintf("SSH server: %.*s", name_len, name);
8510 s->cur_prompt->name_reqd = TRUE;
8511 } else {
8512 s->cur_prompt->name =
8513 dupstr("SSH server authentication");
8514 s->cur_prompt->name_reqd = FALSE;
8515 }
8516 /* We add a prefix to try to make it clear that a prompt
8517 * has come from the server.
8518 * FIXME: ugly to print "Using..." in prompt _every_
8519 * time round. Can this be done more subtly? */
8520 /* Special case: for reasons best known to themselves,
8521 * some servers send k-i requests with no prompts and
8522 * nothing to display. Keep quiet in this case. */
8523 if (s->num_prompts || name_len || inst_len) {
8524 s->cur_prompt->instruction =
8525 dupprintf("Using keyboard-interactive authentication.%s%.*s",
8526 inst_len ? "\n" : "", inst_len, inst);
8527 s->cur_prompt->instr_reqd = TRUE;
8528 } else {
8529 s->cur_prompt->instr_reqd = FALSE;
8530 }
8531
b8e3173d 8532 /*
9ea10e78 8533 * Display any instructions, and get the user's
8534 * response(s).
b8e3173d 8535 */
9ea10e78 8536 {
b8e3173d 8537 int ret; /* not live over crReturn */
8538 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8539 while (ret < 0) {
8540 ssh->send_ok = 1;
8541 crWaitUntilV(!pktin);
8542 ret = get_userpass_input(s->cur_prompt, in, inlen);
8543 ssh->send_ok = 0;
8544 }
8545 if (!ret) {
8546 /*
8547 * Failed to get responses. Terminate.
8548 */
8549 free_prompts(s->cur_prompt);
8550 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8551 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8552 TRUE);
8553 crStopV;
8554 }
edd0cb8a 8555 }
b8e3173d 8556
8557 /*
9ea10e78 8558 * Send the response(s) to the server.
b8e3173d 8559 */
8560 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
b8e3173d 8561 ssh2_pkt_adduint32(s->pktout, s->num_prompts);
8562 for (i=0; i < s->num_prompts; i++) {
8563 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8564 ssh2_pkt_addstring(s->pktout,
8565 s->cur_prompt->prompts[i]->result);
8566 end_log_omission(ssh, s->pktout);
8567 }
18524056 8568 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
b8e3173d 8569
c69784c0 8570 /*
8571 * Free the prompts structure from this iteration.
8572 * If there's another, a new one will be allocated
8573 * when we return to the top of this while loop.
8574 */
8575 free_prompts(s->cur_prompt);
8576
b8e3173d 8577 /*
8578 * Get the next packet in case it's another
8579 * INFO_REQUEST.
8580 */
8581 crWaitUntilV(pktin);
8582
edd0cb8a 8583 }
8584
8585 /*
b8e3173d 8586 * We should have SUCCESS or FAILURE now.
edd0cb8a 8587 */
b8e3173d 8588 s->gotit = TRUE;
edd0cb8a 8589
8590 } else if (s->can_passwd) {
8591
8592 /*
8593 * Plain old password authentication.
8594 */
8595 int ret; /* not live over crReturn */
e955d348 8596 int changereq_first_time; /* not live over crReturn */
edd0cb8a 8597
acab36bc 8598 ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
edd0cb8a 8599
8600 s->cur_prompt = new_prompts(ssh->frontend);
8601 s->cur_prompt->to_server = TRUE;
8602 s->cur_prompt->name = dupstr("SSH password");
4a693cfc 8603 add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
8604 ssh->username,
edd0cb8a 8605 ssh->savedhost),
b61f81bc 8606 FALSE);
edd0cb8a 8607
8608 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8609 while (ret < 0) {
8610 ssh->send_ok = 1;
8611 crWaitUntilV(!pktin);
8612 ret = get_userpass_input(s->cur_prompt, in, inlen);
8613 ssh->send_ok = 0;
8614 }
8615 if (!ret) {
8616 /*
8617 * Failed to get responses. Terminate.
8618 */
8619 free_prompts(s->cur_prompt);
8620 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8621 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8622 TRUE);
8623 crStopV;
8624 }
e955d348 8625 /*
8626 * Squirrel away the password. (We may need it later if
8627 * asked to change it.)
8628 */
8629 s->password = dupstr(s->cur_prompt->prompts[0]->result);
8630 free_prompts(s->cur_prompt);
edd0cb8a 8631
8632 /*
8633 * Send the password packet.
8634 *
95d2d262 8635 * We pad out the password packet to 256 bytes to make
8636 * it harder for an attacker to find the length of the
8637 * user's password.
1408a877 8638 *
95d2d262 8639 * Anyone using a password longer than 256 bytes
8640 * probably doesn't have much to worry about from
1408a877 8641 * people who find out how long their password is!
65a22376 8642 */
ff3187f6 8643 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4a693cfc 8644 ssh2_pkt_addstring(s->pktout, ssh->username);
edd0cb8a 8645 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8646 /* service requested */
ff3187f6 8647 ssh2_pkt_addstring(s->pktout, "password");
8648 ssh2_pkt_addbool(s->pktout, FALSE);
8649 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
e955d348 8650 ssh2_pkt_addstring(s->pktout, s->password);
ff3187f6 8651 end_log_omission(ssh, s->pktout);
18524056 8652 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
0d43337a 8653 logevent("Sent password");
28f4d4f0 8654 s->type = AUTH_TYPE_PASSWORD;
edd0cb8a 8655
e955d348 8656 /*
8657 * Wait for next packet, in case it's a password change
8658 * request.
8659 */
8660 crWaitUntilV(pktin);
8661 changereq_first_time = TRUE;
8662
8663 while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
8664
8665 /*
8666 * We're being asked for a new password
8667 * (perhaps not for the first time).
8668 * Loop until the server accepts it.
8669 */
8670
8671 int got_new = FALSE; /* not live over crReturn */
8672 char *prompt; /* not live over crReturn */
8673 int prompt_len; /* not live over crReturn */
8674
8675 {
8676 char *msg;
8677 if (changereq_first_time)
8678 msg = "Server requested password change";
8679 else
8680 msg = "Server rejected new password";
8681 logevent(msg);
8682 c_write_str(ssh, msg);
8683 c_write_str(ssh, "\r\n");
8684 }
8685
8686 ssh_pkt_getstring(pktin, &prompt, &prompt_len);
8687
8688 s->cur_prompt = new_prompts(ssh->frontend);
8689 s->cur_prompt->to_server = TRUE;
8690 s->cur_prompt->name = dupstr("New SSH password");
8691 s->cur_prompt->instruction =
8692 dupprintf("%.*s", prompt_len, prompt);
8693 s->cur_prompt->instr_reqd = TRUE;
d9add7bc 8694 /*
8695 * There's no explicit requirement in the protocol
8696 * for the "old" passwords in the original and
8697 * password-change messages to be the same, and
8698 * apparently some Cisco kit supports password change
8699 * by the user entering a blank password originally
8700 * and the real password subsequently, so,
8701 * reluctantly, we prompt for the old password again.
8702 *
8703 * (On the other hand, some servers don't even bother
8704 * to check this field.)
8705 */
8706 add_prompt(s->cur_prompt,
8707 dupstr("Current password (blank for previously entered password): "),
b61f81bc 8708 FALSE);
e955d348 8709 add_prompt(s->cur_prompt, dupstr("Enter new password: "),
b61f81bc 8710 FALSE);
e955d348 8711 add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
b61f81bc 8712 FALSE);
e955d348 8713
8714 /*
8715 * Loop until the user manages to enter the same
8716 * password twice.
8717 */
8718 while (!got_new) {
8719
8720 ret = get_userpass_input(s->cur_prompt, NULL, 0);
8721 while (ret < 0) {
8722 ssh->send_ok = 1;
8723 crWaitUntilV(!pktin);
8724 ret = get_userpass_input(s->cur_prompt, in, inlen);
8725 ssh->send_ok = 0;
8726 }
8727 if (!ret) {
8728 /*
8729 * Failed to get responses. Terminate.
8730 */
8731 /* burn the evidence */
8732 free_prompts(s->cur_prompt);
dfb88efd 8733 smemclr(s->password, strlen(s->password));
e955d348 8734 sfree(s->password);
8735 ssh_disconnect(ssh, NULL, "Unable to authenticate",
8736 SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
8737 TRUE);
8738 crStopV;
8739 }
8740
8741 /*
d9add7bc 8742 * If the user specified a new original password
8743 * (IYSWIM), overwrite any previously specified
8744 * one.
8745 * (A side effect is that the user doesn't have to
8746 * re-enter it if they louse up the new password.)
8747 */
8748 if (s->cur_prompt->prompts[0]->result[0]) {
dfb88efd 8749 smemclr(s->password, strlen(s->password));
d9add7bc 8750 /* burn the evidence */
8751 sfree(s->password);
8752 s->password =
8753 dupstr(s->cur_prompt->prompts[0]->result);
8754 }
8755
8756 /*
8757 * Check the two new passwords match.
e955d348 8758 */
d9add7bc 8759 got_new = (strcmp(s->cur_prompt->prompts[1]->result,
8760 s->cur_prompt->prompts[2]->result)
e955d348 8761 == 0);
8762 if (!got_new)
8763 /* They don't. Silly user. */
8764 c_write_str(ssh, "Passwords do not match\r\n");
8765
8766 }
8767
8768 /*
8769 * Send the new password (along with the old one).
8770 * (see above for padding rationale)
8771 */
8772 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
4a693cfc 8773 ssh2_pkt_addstring(s->pktout, ssh->username);
e955d348 8774 ssh2_pkt_addstring(s->pktout, "ssh-connection");
8775 /* service requested */
8776 ssh2_pkt_addstring(s->pktout, "password");
8777 ssh2_pkt_addbool(s->pktout, TRUE);
8778 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8779 ssh2_pkt_addstring(s->pktout, s->password);
8780 ssh2_pkt_addstring(s->pktout,
d9add7bc 8781 s->cur_prompt->prompts[1]->result);
e955d348 8782 free_prompts(s->cur_prompt);
8783 end_log_omission(ssh, s->pktout);
18524056 8784 ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
e955d348 8785 logevent("Sent new password");
8786
8787 /*
8788 * Now see what the server has to say about it.
8789 * (If it's CHANGEREQ again, it's not happy with the
8790 * new password.)
8791 */
8792 crWaitUntilV(pktin);
8793 changereq_first_time = FALSE;
8794
8795 }
8796
8797 /*
8798 * We need to reexamine the current pktin at the top
8799 * of the loop. Either:
8800 * - we weren't asked to change password at all, in
8801 * which case it's a SUCCESS or FAILURE with the
8802 * usual meaning
8803 * - we sent a new password, and the server was
8804 * either OK with it (SUCCESS or FAILURE w/partial
8805 * success) or unhappy with the _old_ password
8806 * (FAILURE w/o partial success)
8807 * In any of these cases, we go back to the top of
8808 * the loop and start again.
8809 */
8810 s->gotit = TRUE;
8811
8812 /*
8813 * We don't need the old password any more, in any
8814 * case. Burn the evidence.
8815 */
dfb88efd 8816 smemclr(s->password, strlen(s->password));
e955d348 8817 sfree(s->password);
8818
1408a877 8819 } else {
854caca5 8820 char *str = dupprintf("No supported authentication methods available"
8821 " (server sent: %.*s)",
8822 methlen, methods);
edd0cb8a 8823
854caca5 8824 ssh_disconnect(ssh, str,
9e296bfa 8825 "No supported authentication methods available",
8826 SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
8827 FALSE);
854caca5 8828 sfree(str);
8829
7ffdbc1a 8830 crStopV;
edd0cb8a 8831
65a22376 8832 }
edd0cb8a 8833
65a22376 8834 }
a1a1fae4 8835 }
6bbce591 8836 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
7cca0d81 8837
edd0cb8a 8838 /* Clear up various bits and pieces from authentication. */
8839 if (s->publickey_blob) {
8840 sfree(s->publickey_blob);
8841 sfree(s->publickey_comment);
8842 }
94cd7c3a 8843 if (s->agent_response)
8844 sfree(s->agent_response);
edd0cb8a 8845
ab18ccff 8846 if (s->userauth_success) {
8847 /*
8848 * We've just received USERAUTH_SUCCESS, and we haven't sent any
8849 * packets since. Signal the transport layer to consider enacting
8850 * delayed compression.
8851 *
8852 * (Relying on we_are_in is not sufficient, as
8853 * draft-miller-secsh-compression-delayed is quite clear that it
8854 * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
8855 * become set for other reasons.)
8856 */
8857 do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
8858 }
8859
7cca0d81 8860 /*
a1a1fae4 8861 * Now the connection protocol has started, one way or another.
7cca0d81 8862 */
8863
0ed48730 8864 ssh->channels = newtree234(ssh_channelcmp);
8865
7cca0d81 8866 /*
b09eaa88 8867 * Set up handlers for some connection protocol messages, so we
8868 * don't have to handle them repeatedly in this coroutine.
8869 */
8870 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
8871 ssh2_msg_channel_window_adjust;
51df0ab5 8872 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
8873 ssh2_msg_global_request;
b09eaa88 8874
8875 /*
0ed48730 8876 * Create the main session channel.
7cca0d81 8877 */
4a693cfc 8878 if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
feb02b4e 8879 ssh->mainchan = NULL;
4a693cfc 8880 } else if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
feb02b4e 8881 /*
8882 * Just start a direct-tcpip channel and use it as the main
8883 * channel.
8884 */
8885 ssh->mainchan = snew(struct ssh_channel);
8886 ssh->mainchan->ssh = ssh;
94bdfe40 8887 ssh2_channel_init(ssh->mainchan);
23828b7e 8888 logeventf(ssh,
8889 "Opening direct-tcpip channel to %s:%d in place of session",
4a693cfc 8890 conf_get_str(ssh->conf, CONF_ssh_nc_host),
8891 conf_get_int(ssh->conf, CONF_ssh_nc_port));
feb02b4e 8892 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8893 ssh2_pkt_addstring(s->pktout, "direct-tcpip");
8894 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
feb02b4e 8895 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
8896 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
4a693cfc 8897 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_ssh_nc_host));
8898 ssh2_pkt_adduint32(s->pktout, conf_get_int(ssh->conf, CONF_ssh_nc_port));
feb02b4e 8899 /*
23828b7e 8900 * There's nothing meaningful to put in the originator
8901 * fields, but some servers insist on syntactically correct
8902 * information.
feb02b4e 8903 */
8904 ssh2_pkt_addstring(s->pktout, "0.0.0.0");
8905 ssh2_pkt_adduint32(s->pktout, 0);
8906 ssh2_pkt_send(ssh, s->pktout);
8907
8908 crWaitUntilV(pktin);
8909 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
8910 bombout(("Server refused to open a direct-tcpip channel"));
8911 crStopV;
8912 /* FIXME: error data comes back in FAILURE packet */
8913 }
8914 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
8915 bombout(("Server's channel confirmation cited wrong channel"));
8916 crStopV;
8917 }
8918 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
8919 ssh->mainchan->halfopen = FALSE;
8920 ssh->mainchan->type = CHAN_MAINSESSION;
feb02b4e 8921 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8922 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
feb02b4e 8923 add234(ssh->channels, ssh->mainchan);
8924 update_specials_menu(ssh->frontend);
23828b7e 8925 logevent("Opened direct-tcpip channel");
feb02b4e 8926 ssh->ncmode = TRUE;
8927 } else {
0ed48730 8928 ssh->mainchan = snew(struct ssh_channel);
8929 ssh->mainchan->ssh = ssh;
94bdfe40 8930 ssh2_channel_init(ssh->mainchan);
ff3187f6 8931 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8932 ssh2_pkt_addstring(s->pktout, "session");
8933 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
ff3187f6 8934 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
954d5c5a 8935 ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT); /* our max pkt size */
ff3187f6 8936 ssh2_pkt_send(ssh, s->pktout);
8937 crWaitUntilV(pktin);
8938 if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
0ed48730 8939 bombout(("Server refused to open a session"));
8940 crStopV;
8941 /* FIXME: error data comes back in FAILURE packet */
8942 }
ff3187f6 8943 if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
0ed48730 8944 bombout(("Server's channel confirmation cited wrong channel"));
8945 crStopV;
8946 }
ff3187f6 8947 ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
64d6ff88 8948 ssh->mainchan->halfopen = FALSE;
0ed48730 8949 ssh->mainchan->type = CHAN_MAINSESSION;
ff3187f6 8950 ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
8951 ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
0ed48730 8952 add234(ssh->channels, ssh->mainchan);
62638676 8953 update_specials_menu(ssh->frontend);
0ed48730 8954 logevent("Opened channel for session");
feb02b4e 8955 ssh->ncmode = FALSE;
8956 }
7cca0d81 8957
8958 /*
51df0ab5 8959 * Now we have a channel, make dispatch table entries for
8960 * general channel-based messages.
8961 */
8962 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
8963 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
8964 ssh2_msg_channel_data;
8965 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
8966 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
8967 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
8968 ssh2_msg_channel_open_confirmation;
8969 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
8970 ssh2_msg_channel_open_failure;
8971 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
8972 ssh2_msg_channel_request;
8973 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
8974 ssh2_msg_channel_open;
8975
4a693cfc 8976 if (ssh->mainchan && conf_get_int(ssh->conf, CONF_ssh_simple)) {
3361b80a 8977 /*
8978 * This message indicates to the server that we promise
8979 * not to try to run any other channel in parallel with
8980 * this one, so it's safe for it to advertise a very large
8981 * window and leave the flow control to TCP.
8982 */
8983 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8984 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8985 ssh2_pkt_addstring(s->pktout, "simple@putty.projects.tartarus.org");
8986 ssh2_pkt_addbool(s->pktout, 0); /* no reply */
8987 ssh2_pkt_send(ssh, s->pktout);
8988 }
8989
51df0ab5 8990 /*
783415f8 8991 * Potentially enable X11 forwarding.
8992 */
4a693cfc 8993 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_x11_forward) &&
8994 (ssh->x11disp = x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
8995 conf_get_int(ssh->conf, CONF_x11_auth), ssh->conf))) {
32874aea 8996 logevent("Requesting X11 forwarding");
ff3187f6 8997 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8998 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
8999 ssh2_pkt_addstring(s->pktout, "x11-req");
9000 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9001 ssh2_pkt_addbool(s->pktout, 0); /* many connections */
8def70c3 9002 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthprotoname);
f68353be 9003 /*
9004 * Note that while we blank the X authentication data here, we don't
9005 * take any special action to blank the start of an X11 channel,
9006 * so using MIT-MAGIC-COOKIE-1 and actually opening an X connection
9007 * without having session blanking enabled is likely to leak your
9008 * cookie into the log.
9009 */
178c3872 9010 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
8def70c3 9011 ssh2_pkt_addstring(s->pktout, ssh->x11disp->remoteauthdatastring);
178c3872 9012 end_log_omission(ssh, s->pktout);
8def70c3 9013 ssh2_pkt_adduint32(s->pktout, ssh->x11disp->screennum);
ff3187f6 9014 ssh2_pkt_send(ssh, s->pktout);
32874aea 9015
b09eaa88 9016 crWaitUntilV(pktin);
32874aea 9017
ff3187f6 9018 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9019 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6b5cf8b4 9020 bombout(("Unexpected response to X11 forwarding request:"
ff3187f6 9021 " packet type %d", pktin->type));
7ffdbc1a 9022 crStopV;
32874aea 9023 }
9024 logevent("X11 forwarding refused");
9025 } else {
9026 logevent("X11 forwarding enabled");
51470298 9027 ssh->X11_fwd_enabled = TRUE;
32874aea 9028 }
783415f8 9029 }
9030
9031 /*
bc240b21 9032 * Enable port forwardings.
9033 */
4a693cfc 9034 ssh_setup_portfwd(ssh, ssh->conf);
bc240b21 9035
9036 /*
36c2a3e9 9037 * Potentially enable agent forwarding.
9038 */
4a693cfc 9039 if (ssh->mainchan && !ssh->ncmode && conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists()) {
32874aea 9040 logevent("Requesting OpenSSH-style agent forwarding");
ff3187f6 9041 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9042 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9043 ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
9044 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9045 ssh2_pkt_send(ssh, s->pktout);
32874aea 9046
b09eaa88 9047 crWaitUntilV(pktin);
32874aea 9048
ff3187f6 9049 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9050 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6b5cf8b4 9051 bombout(("Unexpected response to agent forwarding request:"
ff3187f6 9052 " packet type %d", pktin->type));
7ffdbc1a 9053 crStopV;
32874aea 9054 }
9055 logevent("Agent forwarding refused");
9056 } else {
9057 logevent("Agent forwarding enabled");
51470298 9058 ssh->agentfwd_enabled = TRUE;
32874aea 9059 }
36c2a3e9 9060 }
9061
9062 /*
7cca0d81 9063 * Now allocate a pty for the session.
9064 */
4a693cfc 9065 if (ssh->mainchan && !ssh->ncmode && !conf_get_int(ssh->conf, CONF_nopty)) {
a5dd8467 9066 /* Unpick the terminal-speed string. */
9067 /* XXX perhaps we should allow no speeds to be sent. */
db219738 9068 ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
4a693cfc 9069 sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
a5dd8467 9070 /* Build the pty request. */
ff3187f6 9071 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9072 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
9073 ssh2_pkt_addstring(s->pktout, "pty-req");
9074 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
4a693cfc 9075 ssh2_pkt_addstring(s->pktout, conf_get_str(ssh->conf, CONF_termtype));
ff3187f6 9076 ssh2_pkt_adduint32(s->pktout, ssh->term_width);
9077 ssh2_pkt_adduint32(s->pktout, ssh->term_height);
9078 ssh2_pkt_adduint32(s->pktout, 0); /* pixel width */
9079 ssh2_pkt_adduint32(s->pktout, 0); /* pixel height */
9080 ssh2_pkt_addstring_start(s->pktout);
4a693cfc 9081 parse_ttymodes(ssh, ssh2_send_ttymode, (void *)s->pktout);
c6ccd5c2 9082 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_ISPEED);
ff3187f6 9083 ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
c6ccd5c2 9084 ssh2_pkt_addbyte(s->pktout, SSH2_TTY_OP_OSPEED);
ff3187f6 9085 ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
9086 ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
9087 ssh2_pkt_send(ssh, s->pktout);
51470298 9088 ssh->state = SSH_STATE_INTERMED;
32874aea 9089
b09eaa88 9090 crWaitUntilV(pktin);
32874aea 9091
ff3187f6 9092 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9093 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6b5cf8b4 9094 bombout(("Unexpected response to pty request:"
ff3187f6 9095 " packet type %d", pktin->type));
7ffdbc1a 9096 crStopV;
32874aea 9097 }
51470298 9098 c_write_str(ssh, "Server refused to allocate pty\r\n");
9099 ssh->editing = ssh->echoing = 1;
32874aea 9100 } else {
a5dd8467 9101 logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
db219738 9102 ssh->ospeed, ssh->ispeed);
4a202fc6 9103 ssh->got_pty = TRUE;
32874aea 9104 }
0965bee0 9105 } else {
51470298 9106 ssh->editing = ssh->echoing = 1;
7cca0d81 9107 }
9108
9109 /*
73feed4f 9110 * Send environment variables.
9111 *
9112 * Simplest thing here is to send all the requests at once, and
9113 * then wait for a whole bunch of successes or failures.
9114 */
4a693cfc 9115 if (ssh->mainchan && !ssh->ncmode) {
9116 char *key, *val;
73feed4f 9117
9118 s->num_env = 0;
9119
4a693cfc 9120 for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
9121 val != NULL;
9122 val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
ff3187f6 9123 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9124 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
9125 ssh2_pkt_addstring(s->pktout, "env");
9126 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
4a693cfc 9127 ssh2_pkt_addstring(s->pktout, key);
ff3187f6 9128 ssh2_pkt_addstring(s->pktout, val);
9129 ssh2_pkt_send(ssh, s->pktout);
73feed4f 9130
9131 s->num_env++;
9132 }
9133
4a693cfc 9134 if (s->num_env) {
9135 logeventf(ssh, "Sent %d environment variables", s->num_env);
73feed4f 9136
4a693cfc 9137 s->env_ok = 0;
9138 s->env_left = s->num_env;
73feed4f 9139
4a693cfc 9140 while (s->env_left > 0) {
9141 crWaitUntilV(pktin);
73feed4f 9142
4a693cfc 9143 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9144 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
9145 bombout(("Unexpected response to environment request:"
9146 " packet type %d", pktin->type));
9147 crStopV;
9148 }
9149 } else {
9150 s->env_ok++;
73feed4f 9151 }
73feed4f 9152
4a693cfc 9153 s->env_left--;
9154 }
73feed4f 9155
4a693cfc 9156 if (s->env_ok == s->num_env) {
9157 logevent("All environment variables successfully set");
9158 } else if (s->env_ok == 0) {
9159 logevent("All environment variables refused");
9160 c_write_str(ssh, "Server refused to set environment variables\r\n");
9161 } else {
9162 logeventf(ssh, "%d environment variables refused",
9163 s->num_env - s->env_ok);
9164 c_write_str(ssh, "Server refused to set all environment variables\r\n");
9165 }
73feed4f 9166 }
9167 }
9168
9169 /*
fd5e5847 9170 * Start a shell or a remote command. We may have to attempt
9171 * this twice if the config data has provided a second choice
9172 * of command.
7cca0d81 9173 */
feb02b4e 9174 if (ssh->mainchan && !ssh->ncmode) while (1) {
fd5e5847 9175 int subsys;
9176 char *cmd;
9177
51470298 9178 if (ssh->fallback_cmd) {
4a693cfc 9179 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
9180 cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
fd5e5847 9181 } else {
4a693cfc 9182 subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
9183 cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
fd5e5847 9184 }
9185
ff3187f6 9186 s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9187 ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
fd5e5847 9188 if (subsys) {
ff3187f6 9189 ssh2_pkt_addstring(s->pktout, "subsystem");
9190 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9191 ssh2_pkt_addstring(s->pktout, cmd);
fd5e5847 9192 } else if (*cmd) {
ff3187f6 9193 ssh2_pkt_addstring(s->pktout, "exec");
9194 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
9195 ssh2_pkt_addstring(s->pktout, cmd);
fd5e5847 9196 } else {
ff3187f6 9197 ssh2_pkt_addstring(s->pktout, "shell");
9198 ssh2_pkt_addbool(s->pktout, 1); /* want reply */
32874aea 9199 }
ff3187f6 9200 ssh2_pkt_send(ssh, s->pktout);
b09eaa88 9201
9202 crWaitUntilV(pktin);
9203
ff3187f6 9204 if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
9205 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
6b5cf8b4 9206 bombout(("Unexpected response to shell/command request:"
ff3187f6 9207 " packet type %d", pktin->type));
7ffdbc1a 9208 crStopV;
fd5e5847 9209 }
9210 /*
9211 * We failed to start the command. If this is the
9212 * fallback command, we really are finished; if it's
9213 * not, and if the fallback command exists, try falling
9214 * back to it before complaining.
9215 */
4a693cfc 9216 if (!ssh->fallback_cmd &&
9217 *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
fd5e5847 9218 logevent("Primary command failed; attempting fallback");
51470298 9219 ssh->fallback_cmd = TRUE;
fd5e5847 9220 continue;
9221 }
6b5cf8b4 9222 bombout(("Server refused to start a shell/command"));
7ffdbc1a 9223 crStopV;
fd5e5847 9224 } else {
9225 logevent("Started a shell/command");
32874aea 9226 }
fd5e5847 9227 break;
7cca0d81 9228 }
9229
51470298 9230 ssh->state = SSH_STATE_SESSION;
9231 if (ssh->size_needed)
9232 ssh_size(ssh, ssh->term_width, ssh->term_height);
9233 if (ssh->eof_needed)
9234 ssh_special(ssh, TS_EOF);
6e48c3fe 9235
7cca0d81 9236 /*
0e443c99 9237 * All the initial channel requests are done, so install the default
9238 * failure handler.
9239 */
837d6ba6 9240 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_success;
0e443c99 9241 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_failure;
9242
9243 /*
7cca0d81 9244 * Transfer data!
9245 */
b9d7bcad 9246 if (ssh->ldisc)
9247 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
0ed48730 9248 if (ssh->mainchan)
9249 ssh->send_ok = 1;
7cca0d81 9250 while (1) {
e5574168 9251 crReturnV;
51470298 9252 s->try_send = FALSE;
ff3187f6 9253 if (pktin) {
2b7540a7 9254
51df0ab5 9255 /*
9256 * _All_ the connection-layer packets we expect to
9257 * receive are now handled by the dispatch table.
9258 * Anything that reaches here must be bogus.
9259 */
32874aea 9260
51df0ab5 9261 bombout(("Strange packet received: type %d", pktin->type));
9262 crStopV;
0ed48730 9263 } else if (ssh->mainchan) {
32874aea 9264 /*
9265 * We have spare data. Add it to the channel buffer.
9266 */
d8baa528 9267 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
51470298 9268 s->try_send = TRUE;
32874aea 9269 }
51470298 9270 if (s->try_send) {
32874aea 9271 int i;
9272 struct ssh_channel *c;
9273 /*
9274 * Try to send data on all channels if we can.
9275 */
1bfc7e93 9276 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
78280721 9277 ssh2_try_send_and_unthrottle(ssh, c);
7cca0d81 9278 }
e5574168 9279 }
9280
9281 crFinishV;
9282}
9283
9284/*
2e85c969 9285 * Handlers for SSH-2 messages that might arrive at any moment.
b09eaa88 9286 */
409bfa77 9287static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
b09eaa88 9288{
9289 /* log reason code in disconnect message */
9290 char *buf, *msg;
60860bc3 9291 int reason, msglen;
b09eaa88 9292
9293 reason = ssh_pkt_getuint32(pktin);
9294 ssh_pkt_getstring(pktin, &msg, &msglen);
9295
9296 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
9297 buf = dupprintf("Received disconnect message (%s)",
9298 ssh2_disconnect_reasons[reason]);
9299 } else {
9300 buf = dupprintf("Received disconnect message (unknown"
9301 " type %d)", reason);
9302 }
9303 logevent(buf);
9304 sfree(buf);
60860bc3 9305 buf = dupprintf("Disconnection message text: %.*s",
9306 msglen, msg);
b09eaa88 9307 logevent(buf);
60860bc3 9308 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
b09eaa88 9309 reason,
9310 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
9311 ssh2_disconnect_reasons[reason] : "unknown",
60860bc3 9312 msglen, msg));
b09eaa88 9313 sfree(buf);
9314}
9315
409bfa77 9316static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
b09eaa88 9317{
9318 /* log the debug message */
fb983202 9319 char *msg;
b09eaa88 9320 int msglen;
b09eaa88 9321
3ab79841 9322 /* XXX maybe we should actually take notice of the return value */
9323 ssh2_pkt_getbool(pktin);
b09eaa88 9324 ssh_pkt_getstring(pktin, &msg, &msglen);
9325
fb983202 9326 logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
b09eaa88 9327}
9328
409bfa77 9329static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
b09eaa88 9330{
9331 struct Packet *pktout;
9332 pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
9333 ssh2_pkt_adduint32(pktout, pktin->sequence);
9334 /*
9335 * UNIMPLEMENTED messages MUST appear in the same order as the
9336 * messages they respond to. Hence, never queue them.
9337 */
9338 ssh2_pkt_send_noqueue(ssh, pktout);
9339}
9340
9341/*
2e85c969 9342 * Handle the top-level SSH-2 protocol.
7cca0d81 9343 */
b09eaa88 9344static void ssh2_protocol_setup(Ssh ssh)
9345{
9346 int i;
9347
9348 /*
9349 * Most messages cause SSH2_MSG_UNIMPLEMENTED.
9350 */
9351 for (i = 0; i < 256; i++)
9352 ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
9353
9354 /*
9355 * Any message we actually understand, we set to NULL so that
9356 * the coroutines will get it.
9357 */
9358 ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
9359 ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
9360 ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
9361 ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
9362 ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
9363 ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
9364 ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
9365 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
9366 /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
9367 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
9368 ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
9369 ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
9370 ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
9371 ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
9372 ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
9373 ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
9374 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
9375 /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
9376 ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
9377 ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
9378 ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
9379 ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
9380 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
9381 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
9382 ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
9383 ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
9384 ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
9385 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
9386 ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
9387 ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
9388 ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
9389 ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
9390 ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
9391
9392 /*
9393 * These special message types we install handlers for.
9394 */
9395 ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
2e85c969 9396 ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
b09eaa88 9397 ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
9398}
9399
9442dd57 9400static void ssh2_timer(void *ctx, long now)
9401{
9402 Ssh ssh = (Ssh)ctx;
9403
ecbb0000 9404 if (ssh->state == SSH_STATE_CLOSED)
9405 return;
9406
4a693cfc 9407 if (!ssh->kex_in_progress && conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
9442dd57 9408 now - ssh->next_rekey >= 0) {
f382c87d 9409 do_ssh2_transport(ssh, "timeout", -1, NULL);
9442dd57 9410 }
9411}
9412
1c1a7262 9413static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
ff3187f6 9414 struct Packet *pktin)
7cca0d81 9415{
1c1a7262 9416 unsigned char *in = (unsigned char *)vin;
b09eaa88 9417 if (ssh->state == SSH_STATE_CLOSED)
9418 return;
9419
9442dd57 9420 if (pktin) {
9421 ssh->incoming_data_size += pktin->encrypted_len;
9422 if (!ssh->kex_in_progress &&
d57f70af 9423 ssh->max_data_size != 0 &&
9424 ssh->incoming_data_size > ssh->max_data_size)
f382c87d 9425 do_ssh2_transport(ssh, "too much data received", -1, NULL);
9442dd57 9426 }
9427
b09eaa88 9428 if (pktin && ssh->packet_dispatch[pktin->type]) {
9429 ssh->packet_dispatch[pktin->type](ssh, pktin);
32874aea 9430 return;
b09eaa88 9431 }
9432
9433 if (!ssh->protocol_initial_phase_done ||
9434 (pktin && pktin->type >= 20 && pktin->type < 50)) {
9435 if (do_ssh2_transport(ssh, in, inlen, pktin) &&
9436 !ssh->protocol_initial_phase_done) {
9437 ssh->protocol_initial_phase_done = TRUE;
9438 /*
9439 * Allow authconn to initialise itself.
9440 */
9441 do_ssh2_authconn(ssh, NULL, 0, NULL);
9442 }
9443 } else {
9444 do_ssh2_authconn(ssh, in, inlen, pktin);
9445 }
7cca0d81 9446}
9447
4a693cfc 9448static void ssh_cache_conf_values(Ssh ssh)
9449{
9450 ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
9451}
9452
7cca0d81 9453/*
8df7a775 9454 * Called to set up the connection.
374330e2 9455 *
9456 * Returns an error message, or NULL on success.
374330e2 9457 */
cbe2d68f 9458static const char *ssh_init(void *frontend_handle, void **backend_handle,
4a693cfc 9459 Conf *conf, char *host, int port, char **realhost,
9460 int nodelay, int keepalive)
32874aea 9461{
cbe2d68f 9462 const char *p;
51470298 9463 Ssh ssh;
9464
3d88e64d 9465 ssh = snew(struct ssh_tag);
4a693cfc 9466 ssh->conf = conf_copy(conf);
9467 ssh_cache_conf_values(ssh);
125105d1 9468 ssh->version = 0; /* when not ready yet */
51470298 9469 ssh->s = NULL;
9470 ssh->cipher = NULL;
371e569c 9471 ssh->v1_cipher_ctx = NULL;
0183b242 9472 ssh->crcda_ctx = NULL;
51470298 9473 ssh->cscipher = NULL;
371e569c 9474 ssh->cs_cipher_ctx = NULL;
51470298 9475 ssh->sccipher = NULL;
371e569c 9476 ssh->sc_cipher_ctx = NULL;
51470298 9477 ssh->csmac = NULL;
a8327734 9478 ssh->cs_mac_ctx = NULL;
51470298 9479 ssh->scmac = NULL;
e0e1a00d 9480 ssh->sc_mac_ctx = NULL;
51470298 9481 ssh->cscomp = NULL;
5366aed8 9482 ssh->cs_comp_ctx = NULL;
51470298 9483 ssh->sccomp = NULL;
5366aed8 9484 ssh->sc_comp_ctx = NULL;
51470298 9485 ssh->kex = NULL;
389aa499 9486 ssh->kex_ctx = NULL;
51470298 9487 ssh->hostkey = NULL;
9488 ssh->exitcode = -1;
ac934965 9489 ssh->close_expected = FALSE;
9e296bfa 9490 ssh->clean_exit = FALSE;
51470298 9491 ssh->state = SSH_STATE_PREPACKET;
9492 ssh->size_needed = FALSE;
9493 ssh->eof_needed = FALSE;
b9d7bcad 9494 ssh->ldisc = NULL;
a8327734 9495 ssh->logctx = NULL;
51470298 9496 ssh->deferred_send_data = NULL;
9497 ssh->deferred_len = 0;
9498 ssh->deferred_size = 0;
9499 ssh->fallback_cmd = 0;
acab36bc 9500 ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
9501 ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
8def70c3 9502 ssh->x11disp = NULL;
be738459 9503 ssh->v1_compressing = FALSE;
51470298 9504 ssh->v2_outgoing_sequence = 0;
9505 ssh->ssh1_rdpkt_crstate = 0;
9506 ssh->ssh2_rdpkt_crstate = 0;
9507 ssh->do_ssh_init_crstate = 0;
9508 ssh->ssh_gotdata_crstate = 0;
b09eaa88 9509 ssh->do_ssh1_connection_crstate = 0;
51470298 9510 ssh->do_ssh1_login_crstate = 0;
9511 ssh->do_ssh2_transport_crstate = 0;
9512 ssh->do_ssh2_authconn_crstate = 0;
9513 ssh->do_ssh_init_state = NULL;
9514 ssh->do_ssh1_login_state = NULL;
9515 ssh->do_ssh2_transport_state = NULL;
9516 ssh->do_ssh2_authconn_state = NULL;
4320baf7 9517 ssh->v_c = NULL;
9518 ssh->v_s = NULL;
6571dbfd 9519 ssh->mainchan = NULL;
968d2d92 9520 ssh->throttled_all = 0;
9521 ssh->v1_stdout_throttling = 0;
590f6a5f 9522 ssh->queue = NULL;
9523 ssh->queuelen = ssh->queuesize = 0;
9524 ssh->queueing = FALSE;
06fadff5 9525 ssh->qhead = ssh->qtail = NULL;
e13bba36 9526 ssh->deferred_rekey_reason = NULL;
3d9449a1 9527 bufchain_init(&ssh->queued_incoming_data);
9528 ssh->frozen = FALSE;
4a693cfc 9529 ssh->username = NULL;
bc06669b 9530 ssh->sent_console_eof = FALSE;
4a202fc6 9531 ssh->got_pty = FALSE;
51470298 9532
9533 *backend_handle = ssh;
32874aea 9534
8f203108 9535#ifdef MSCRYPTOAPI
32874aea 9536 if (crypto_startup() == 0)
8f203108 9537 return "Microsoft high encryption pack not installed!";
9538#endif
374330e2 9539
51470298 9540 ssh->frontend = frontend_handle;
4a693cfc 9541 ssh->term_width = conf_get_int(ssh->conf, CONF_width);
9542 ssh->term_height = conf_get_int(ssh->conf, CONF_height);
887035a5 9543
fabd1805 9544 ssh->channels = NULL;
9545 ssh->rportfwds = NULL;
f47a5ffb 9546 ssh->portfwds = NULL;
fabd1805 9547
51470298 9548 ssh->send_ok = 0;
9549 ssh->editing = 0;
9550 ssh->echoing = 0;
ff68564b 9551 ssh->conn_throttle_count = 0;
51470298 9552 ssh->overall_bufsize = 0;
9553 ssh->fallback_cmd = 0;
8df7a775 9554
3648d4c5 9555 ssh->protocol = NULL;
9556
b09eaa88 9557 ssh->protocol_initial_phase_done = FALSE;
9558
39934deb 9559 ssh->pinger = NULL;
9560
9442dd57 9561 ssh->incoming_data_size = ssh->outgoing_data_size =
9562 ssh->deferred_data_size = 0L;
4a693cfc 9563 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9564 CONF_ssh_rekey_data));
9442dd57 9565 ssh->kex_in_progress = FALSE;
9566
1e00c92b 9567#ifndef NO_GSSAPI
9568 ssh->gsslibs = NULL;
9569#endif
9570
79bf227b 9571 p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
fb09bf1c 9572 if (p != NULL)
9573 return p;
374330e2 9574
5d17ccfc 9575 random_ref();
9576
374330e2 9577 return NULL;
9578}
9579
fabd1805 9580static void ssh_free(void *handle)
9581{
9582 Ssh ssh = (Ssh) handle;
9583 struct ssh_channel *c;
9584 struct ssh_rportfwd *pf;
9585
9586 if (ssh->v1_cipher_ctx)
9587 ssh->cipher->free_context(ssh->v1_cipher_ctx);
9588 if (ssh->cs_cipher_ctx)
9589 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
9590 if (ssh->sc_cipher_ctx)
9591 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
9592 if (ssh->cs_mac_ctx)
9593 ssh->csmac->free_context(ssh->cs_mac_ctx);
9594 if (ssh->sc_mac_ctx)
9595 ssh->scmac->free_context(ssh->sc_mac_ctx);
29b1d0b3 9596 if (ssh->cs_comp_ctx) {
9597 if (ssh->cscomp)
9598 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
9599 else
9600 zlib_compress_cleanup(ssh->cs_comp_ctx);
9601 }
9602 if (ssh->sc_comp_ctx) {
9603 if (ssh->sccomp)
9604 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
9605 else
9606 zlib_decompress_cleanup(ssh->sc_comp_ctx);
9607 }
fabd1805 9608 if (ssh->kex_ctx)
9609 dh_cleanup(ssh->kex_ctx);
9610 sfree(ssh->savedhost);
9611
590f6a5f 9612 while (ssh->queuelen-- > 0)
9613 ssh_free_packet(ssh->queue[ssh->queuelen]);
9614 sfree(ssh->queue);
9615
06fadff5 9616 while (ssh->qhead) {
9617 struct queued_handler *qh = ssh->qhead;
9618 ssh->qhead = qh->next;
9619 sfree(ssh->qhead);
9620 }
9621 ssh->qhead = ssh->qtail = NULL;
9622
fabd1805 9623 if (ssh->channels) {
9624 while ((c = delpos234(ssh->channels, 0)) != NULL) {
9625 switch (c->type) {
9626 case CHAN_X11:
9627 if (c->u.x11.s != NULL)
9628 x11_close(c->u.x11.s);
9629 break;
9630 case CHAN_SOCKDATA:
409eca86 9631 case CHAN_SOCKDATA_DORMANT:
fabd1805 9632 if (c->u.pfd.s != NULL)
9633 pfd_close(c->u.pfd.s);
9634 break;
9635 }
9636 sfree(c);
9637 }
9638 freetree234(ssh->channels);
cdb52705 9639 ssh->channels = NULL;
fabd1805 9640 }
9641
9642 if (ssh->rportfwds) {
9643 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
8aea57fd 9644 free_rportfwd(pf);
fabd1805 9645 freetree234(ssh->rportfwds);
cdb52705 9646 ssh->rportfwds = NULL;
fabd1805 9647 }
9648 sfree(ssh->deferred_send_data);
8def70c3 9649 if (ssh->x11disp)
9650 x11_free_display(ssh->x11disp);
fabd1805 9651 sfree(ssh->do_ssh_init_state);
9652 sfree(ssh->do_ssh1_login_state);
9653 sfree(ssh->do_ssh2_transport_state);
9654 sfree(ssh->do_ssh2_authconn_state);
4320baf7 9655 sfree(ssh->v_c);
9656 sfree(ssh->v_s);
42af6a67 9657 sfree(ssh->fullhostname);
679539d7 9658 if (ssh->crcda_ctx) {
9659 crcda_free_context(ssh->crcda_ctx);
9660 ssh->crcda_ctx = NULL;
9661 }
fabd1805 9662 if (ssh->s)
ac934965 9663 ssh_do_close(ssh, TRUE);
9442dd57 9664 expire_timer_context(ssh);
39934deb 9665 if (ssh->pinger)
9666 pinger_free(ssh->pinger);
3d9449a1 9667 bufchain_clear(&ssh->queued_incoming_data);
4a693cfc 9668 sfree(ssh->username);
9669 conf_free(ssh->conf);
1e00c92b 9670#ifndef NO_GSSAPI
9671 if (ssh->gsslibs)
9672 ssh_gss_cleanup(ssh->gsslibs);
9673#endif
ee50e8b6 9674 sfree(ssh);
5d17ccfc 9675
9676 random_unref();
fabd1805 9677}
9678
374330e2 9679/*
86916870 9680 * Reconfigure the SSH backend.
86916870 9681 */
4a693cfc 9682static void ssh_reconfig(void *handle, Conf *conf)
86916870 9683{
9684 Ssh ssh = (Ssh) handle;
e13bba36 9685 char *rekeying = NULL, rekey_mandatory = FALSE;
e6c1536e 9686 unsigned long old_max_data_size;
4a693cfc 9687 int i, rekey_time;
e6c1536e 9688
4a693cfc 9689 pinger_reconfig(ssh->pinger, ssh->conf, conf);
3b6606c7 9690 if (ssh->portfwds)
4a693cfc 9691 ssh_setup_portfwd(ssh, conf);
e6c1536e 9692
4a693cfc 9693 rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
9694 if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
9695 rekey_time != 0) {
9696 long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
e6c1536e 9697 long now = GETTICKCOUNT();
9698
9699 if (new_next - now < 0) {
f382c87d 9700 rekeying = "timeout shortened";
e6c1536e 9701 } else {
9702 ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
9703 }
9704 }
9705
9706 old_max_data_size = ssh->max_data_size;
4a693cfc 9707 ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
9708 CONF_ssh_rekey_data));
e6c1536e 9709 if (old_max_data_size != ssh->max_data_size &&
9710 ssh->max_data_size != 0) {
9711 if (ssh->outgoing_data_size > ssh->max_data_size ||
9712 ssh->incoming_data_size > ssh->max_data_size)
f382c87d 9713 rekeying = "data limit lowered";
e6c1536e 9714 }
9715
4a693cfc 9716 if (conf_get_int(ssh->conf, CONF_compression) !=
9717 conf_get_int(conf, CONF_compression)) {
f382c87d 9718 rekeying = "compression setting changed";
e13bba36 9719 rekey_mandatory = TRUE;
9720 }
9721
4a693cfc 9722 for (i = 0; i < CIPHER_MAX; i++)
9723 if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
9724 conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
9725 rekeying = "cipher settings changed";
9726 rekey_mandatory = TRUE;
9727 }
9728 if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
9729 conf_get_int(conf, CONF_ssh2_des_cbc)) {
f382c87d 9730 rekeying = "cipher settings changed";
e13bba36 9731 rekey_mandatory = TRUE;
e6c1536e 9732 }
9733
4a693cfc 9734 conf_free(ssh->conf);
9735 ssh->conf = conf_copy(conf);
9736 ssh_cache_conf_values(ssh);
e13bba36 9737
9738 if (rekeying) {
9739 if (!ssh->kex_in_progress) {
9740 do_ssh2_transport(ssh, rekeying, -1, NULL);
9741 } else if (rekey_mandatory) {
9742 ssh->deferred_rekey_reason = rekeying;
9743 }
9744 }
86916870 9745}
9746
9747/*
86dc445a 9748 * Called to send data down the SSH connection.
374330e2 9749 */
51470298 9750static int ssh_send(void *handle, char *buf, int len)
32874aea 9751{
51470298 9752 Ssh ssh = (Ssh) handle;
9753
9754 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5471d09a 9755 return 0;
374330e2 9756
d8baa528 9757 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
5471d09a 9758
51470298 9759 return ssh_sendbuffer(ssh);
5471d09a 9760}
9761
9762/*
9763 * Called to query the current amount of buffered stdin data.
9764 */
51470298 9765static int ssh_sendbuffer(void *handle)
5471d09a 9766{
51470298 9767 Ssh ssh = (Ssh) handle;
5471d09a 9768 int override_value;
9769
51470298 9770 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5471d09a 9771 return 0;
9772
9773 /*
9774 * If the SSH socket itself has backed up, add the total backup
9775 * size on that to any individual buffer on the stdin channel.
9776 */
9777 override_value = 0;
51470298 9778 if (ssh->throttled_all)
9779 override_value = ssh->overall_bufsize;
5471d09a 9780
51470298 9781 if (ssh->version == 1) {
5471d09a 9782 return override_value;
51470298 9783 } else if (ssh->version == 2) {
bc06669b 9784 if (!ssh->mainchan)
5471d09a 9785 return override_value;
9786 else
51470298 9787 return (override_value +
9788 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
5471d09a 9789 }
9790
9791 return 0;
374330e2 9792}
9793
9794/*
6e48c3fe 9795 * Called to set the size of the window from SSH's POV.
374330e2 9796 */
51470298 9797static void ssh_size(void *handle, int width, int height)
32874aea 9798{
51470298 9799 Ssh ssh = (Ssh) handle;
ff3187f6 9800 struct Packet *pktout;
51470298 9801
9802 ssh->term_width = width;
9803 ssh->term_height = height;
f278d6f8 9804
51470298 9805 switch (ssh->state) {
374330e2 9806 case SSH_STATE_BEFORE_SIZE:
3687d221 9807 case SSH_STATE_PREPACKET:
21248260 9808 case SSH_STATE_CLOSED:
374330e2 9809 break; /* do nothing */
9810 case SSH_STATE_INTERMED:
51470298 9811 ssh->size_needed = TRUE; /* buffer for later */
374330e2 9812 break;
9813 case SSH_STATE_SESSION:
4a693cfc 9814 if (!conf_get_int(ssh->conf, CONF_nopty)) {
51470298 9815 if (ssh->version == 1) {
9816 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
9817 PKT_INT, ssh->term_height,
9818 PKT_INT, ssh->term_width,
32874aea 9819 PKT_INT, 0, PKT_INT, 0, PKT_END);
0ed48730 9820 } else if (ssh->mainchan) {
ff3187f6 9821 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9822 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9823 ssh2_pkt_addstring(pktout, "window-change");
9824 ssh2_pkt_addbool(pktout, 0);
9825 ssh2_pkt_adduint32(pktout, ssh->term_width);
9826 ssh2_pkt_adduint32(pktout, ssh->term_height);
9827 ssh2_pkt_adduint32(pktout, 0);
9828 ssh2_pkt_adduint32(pktout, 0);
9829 ssh2_pkt_send(ssh, pktout);
32874aea 9830 }
9831 }
9832 break;
374330e2 9833 }
9834}
9835
9836/*
125105d1 9837 * Return a list of the special codes that make sense in this
9838 * protocol.
9839 */
9840static const struct telnet_special *ssh_get_specials(void *handle)
9841{
786ba75e 9842 static const struct telnet_special ssh1_ignore_special[] = {
9843 {"IGNORE message", TS_NOP}
9844 };
cf6ddb95 9845 static const struct telnet_special ssh2_ignore_special[] = {
62638676 9846 {"IGNORE message", TS_NOP},
cf6ddb95 9847 };
9848 static const struct telnet_special ssh2_rekey_special[] = {
9442dd57 9849 {"Repeat key exchange", TS_REKEY},
62638676 9850 };
9851 static const struct telnet_special ssh2_session_specials[] = {
6f2d0cde 9852 {NULL, TS_SEP},
9853 {"Break", TS_BRK},
bccbeb71 9854 /* These are the signal names defined by RFC 4254.
6f2d0cde 9855 * They include all the ISO C signals, but are a subset of the POSIX
9856 * required signals. */
9857 {"SIGINT (Interrupt)", TS_SIGINT},
9858 {"SIGTERM (Terminate)", TS_SIGTERM},
9859 {"SIGKILL (Kill)", TS_SIGKILL},
9860 {"SIGQUIT (Quit)", TS_SIGQUIT},
9861 {"SIGHUP (Hangup)", TS_SIGHUP},
9862 {"More signals", TS_SUBMENU},
9863 {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
9864 {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
9865 {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
9866 {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
9867 {NULL, TS_EXITMENU}
62638676 9868 };
9869 static const struct telnet_special specials_end[] = {
6f2d0cde 9870 {NULL, TS_EXITMENU}
62638676 9871 };
786ba75e 9872 /* XXX review this length for any changes: */
cf6ddb95 9873 static struct telnet_special ssh_specials[lenof(ssh2_ignore_special) +
9874 lenof(ssh2_rekey_special) +
62638676 9875 lenof(ssh2_session_specials) +
9876 lenof(specials_end)];
125105d1 9877 Ssh ssh = (Ssh) handle;
62638676 9878 int i = 0;
9879#define ADD_SPECIALS(name) \
9880 do { \
9881 assert((i + lenof(name)) <= lenof(ssh_specials)); \
9882 memcpy(&ssh_specials[i], name, sizeof name); \
9883 i += lenof(name); \
9884 } while(0)
125105d1 9885
9886 if (ssh->version == 1) {
62638676 9887 /* Don't bother offering IGNORE if we've decided the remote
9888 * won't cope with it, since we wouldn't bother sending it if
9889 * asked anyway. */
9890 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
786ba75e 9891 ADD_SPECIALS(ssh1_ignore_special);
125105d1 9892 } else if (ssh->version == 2) {
cf6ddb95 9893 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
9894 ADD_SPECIALS(ssh2_ignore_special);
9895 if (!(ssh->remote_bugs & BUG_SSH2_REKEY))
9896 ADD_SPECIALS(ssh2_rekey_special);
62638676 9897 if (ssh->mainchan)
9898 ADD_SPECIALS(ssh2_session_specials);
9899 } /* else we're not ready yet */
9900
9901 if (i) {
9902 ADD_SPECIALS(specials_end);
9903 return ssh_specials;
9904 } else {
125105d1 9905 return NULL;
62638676 9906 }
9907#undef ADD_SPECIALS
125105d1 9908}
9909
9910/*
86dc445a 9911 * Send special codes. TS_EOF is useful for `plink', so you
6abbf9e3 9912 * can send an EOF and collect resulting output (e.g. `plink
9913 * hostname sort').
374330e2 9914 */
51470298 9915static void ssh_special(void *handle, Telnet_Special code)
32874aea 9916{
51470298 9917 Ssh ssh = (Ssh) handle;
ff3187f6 9918 struct Packet *pktout;
51470298 9919
6abbf9e3 9920 if (code == TS_EOF) {
51470298 9921 if (ssh->state != SSH_STATE_SESSION) {
32874aea 9922 /*
9923 * Buffer the EOF in case we are pre-SESSION, so we can
9924 * send it as soon as we reach SESSION.
9925 */
9926 if (code == TS_EOF)
51470298 9927 ssh->eof_needed = TRUE;
32874aea 9928 return;
9929 }
51470298 9930 if (ssh->version == 1) {
9931 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
0ed48730 9932 } else if (ssh->mainchan) {
bc06669b 9933 sshfwd_write_eof(ssh->mainchan);
00a0b113 9934 ssh->send_ok = 0; /* now stop trying to read from stdin */
32874aea 9935 }
9936 logevent("Sent EOF message");
125105d1 9937 } else if (code == TS_PING || code == TS_NOP) {
51470298 9938 if (ssh->state == SSH_STATE_CLOSED
9939 || ssh->state == SSH_STATE_PREPACKET) return;
9940 if (ssh->version == 1) {
9941 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
9942 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
32874aea 9943 } else {
cf6ddb95 9944 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
9945 pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
9946 ssh2_pkt_addstring_start(pktout);
9947 ssh2_pkt_send_noqueue(ssh, pktout);
9948 }
32874aea 9949 }
9442dd57 9950 } else if (code == TS_REKEY) {
9951 if (!ssh->kex_in_progress && ssh->version == 2) {
f382c87d 9952 do_ssh2_transport(ssh, "at user request", -1, NULL);
9442dd57 9953 }
125105d1 9954 } else if (code == TS_BRK) {
9955 if (ssh->state == SSH_STATE_CLOSED
9956 || ssh->state == SSH_STATE_PREPACKET) return;
9957 if (ssh->version == 1) {
2e85c969 9958 logevent("Unable to send BREAK signal in SSH-1");
0ed48730 9959 } else if (ssh->mainchan) {
ff3187f6 9960 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9961 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9962 ssh2_pkt_addstring(pktout, "break");
9963 ssh2_pkt_addbool(pktout, 0);
9964 ssh2_pkt_adduint32(pktout, 0); /* default break length */
9965 ssh2_pkt_send(ssh, pktout);
125105d1 9966 }
6abbf9e3 9967 } else {
6f2d0cde 9968 /* Is is a POSIX signal? */
9969 char *signame = NULL;
9970 if (code == TS_SIGABRT) signame = "ABRT";
9971 if (code == TS_SIGALRM) signame = "ALRM";
9972 if (code == TS_SIGFPE) signame = "FPE";
9973 if (code == TS_SIGHUP) signame = "HUP";
9974 if (code == TS_SIGILL) signame = "ILL";
9975 if (code == TS_SIGINT) signame = "INT";
9976 if (code == TS_SIGKILL) signame = "KILL";
9977 if (code == TS_SIGPIPE) signame = "PIPE";
9978 if (code == TS_SIGQUIT) signame = "QUIT";
9979 if (code == TS_SIGSEGV) signame = "SEGV";
9980 if (code == TS_SIGTERM) signame = "TERM";
9981 if (code == TS_SIGUSR1) signame = "USR1";
9982 if (code == TS_SIGUSR2) signame = "USR2";
9983 /* The SSH-2 protocol does in principle support arbitrary named
9984 * signals, including signame@domain, but we don't support those. */
9985 if (signame) {
9986 /* It's a signal. */
9987 if (ssh->version == 2 && ssh->mainchan) {
ff3187f6 9988 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
9989 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
9990 ssh2_pkt_addstring(pktout, "signal");
9991 ssh2_pkt_addbool(pktout, 0);
9992 ssh2_pkt_addstring(pktout, signame);
9993 ssh2_pkt_send(ssh, pktout);
6f2d0cde 9994 logeventf(ssh, "Sent signal SIG%s", signame);
9995 }
9996 } else {
9997 /* Never heard of it. Do nothing */
9998 }
6abbf9e3 9999 }
374330e2 10000}
10001
51470298 10002void *new_sock_channel(void *handle, Socket s)
d74d141c 10003{
51470298 10004 Ssh ssh = (Ssh) handle;
d74d141c 10005 struct ssh_channel *c;
3d88e64d 10006 c = snew(struct ssh_channel);
d74d141c 10007
70c0cbe1 10008 c->ssh = ssh;
10009 ssh2_channel_init(c);
10010 c->halfopen = TRUE;
10011 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
10012 c->u.pfd.s = s;
10013 add234(ssh->channels, c);
d74d141c 10014 return c;
10015}
10016
5471d09a 10017/*
10018 * This is called when stdout/stderr (the entity to which
10019 * from_backend sends data) manages to clear some backlog.
10020 */
ae9ae89f 10021static void ssh_unthrottle(void *handle, int bufsize)
5471d09a 10022{
51470298 10023 Ssh ssh = (Ssh) handle;
ff68564b 10024 int buflimit;
10025
51470298 10026 if (ssh->version == 1) {
10027 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
10028 ssh->v1_stdout_throttling = 0;
ff68564b 10029 ssh_throttle_conn(ssh, -1);
5471d09a 10030 }
10031 } else {
ff68564b 10032 if (ssh->mainchan) {
ab87bf1d 10033 ssh2_set_window(ssh->mainchan,
ff68564b 10034 bufsize < ssh->mainchan->v.v2.locmaxwin ?
10035 ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
4a693cfc 10036 if (conf_get_int(ssh->conf, CONF_ssh_simple))
ff68564b 10037 buflimit = 0;
10038 else
10039 buflimit = ssh->mainchan->v.v2.locmaxwin;
10040 if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
10041 ssh->mainchan->throttling_conn = 0;
10042 ssh_throttle_conn(ssh, -1);
10043 }
10044 }
5471d09a 10045 }
78e71de1 10046
10047 /*
10048 * Now process any SSH connection data that was stashed in our
10049 * queue while we were frozen.
10050 */
10051 ssh_process_queued_incoming_data(ssh);
5471d09a 10052}
10053
6b78788a 10054void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
d74d141c 10055{
10056 struct ssh_channel *c = (struct ssh_channel *)channel;
6b78788a 10057 Ssh ssh = c->ssh;
ff3187f6 10058 struct Packet *pktout;
d74d141c 10059
57356d63 10060 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
d74d141c 10061
51470298 10062 if (ssh->version == 1) {
10063 send_packet(ssh, SSH1_MSG_PORT_OPEN,
bc240b21 10064 PKT_INT, c->localid,
10065 PKT_STR, hostname,
10066 PKT_INT, port,
31fb1866 10067 /* PKT_STR, <org:orgport>, */
bc240b21 10068 PKT_END);
10069 } else {
ff3187f6 10070 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
10071 ssh2_pkt_addstring(pktout, "direct-tcpip");
10072 ssh2_pkt_adduint32(pktout, c->localid);
ff3187f6 10073 ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
954d5c5a 10074 ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
ff3187f6 10075 ssh2_pkt_addstring(pktout, hostname);
10076 ssh2_pkt_adduint32(pktout, port);
bc240b21 10077 /*
10078 * We make up values for the originator data; partly it's
10079 * too much hassle to keep track, and partly I'm not
10080 * convinced the server should be told details like that
10081 * about my local network configuration.
1f182589 10082 * The "originator IP address" is syntactically a numeric
10083 * IP address, and some servers (e.g., Tectia) get upset
10084 * if it doesn't match this syntax.
bc240b21 10085 */
1f182589 10086 ssh2_pkt_addstring(pktout, "0.0.0.0");
ff3187f6 10087 ssh2_pkt_adduint32(pktout, 0);
10088 ssh2_pkt_send(ssh, pktout);
bc240b21 10089 }
d74d141c 10090}
10091
6226c939 10092static int ssh_connected(void *handle)
32874aea 10093{
51470298 10094 Ssh ssh = (Ssh) handle;
6226c939 10095 return ssh->s != NULL;
32874aea 10096}
8ccc75b0 10097
51470298 10098static int ssh_sendok(void *handle)
32874aea 10099{
51470298 10100 Ssh ssh = (Ssh) handle;
10101 return ssh->send_ok;
32874aea 10102}
fb09bf1c 10103
51470298 10104static int ssh_ldisc(void *handle, int option)
32874aea 10105{
51470298 10106 Ssh ssh = (Ssh) handle;
32874aea 10107 if (option == LD_ECHO)
51470298 10108 return ssh->echoing;
32874aea 10109 if (option == LD_EDIT)
51470298 10110 return ssh->editing;
0965bee0 10111 return FALSE;
10112}
10113
b9d7bcad 10114static void ssh_provide_ldisc(void *handle, void *ldisc)
10115{
10116 Ssh ssh = (Ssh) handle;
10117 ssh->ldisc = ldisc;
10118}
10119
a8327734 10120static void ssh_provide_logctx(void *handle, void *logctx)
10121{
10122 Ssh ssh = (Ssh) handle;
10123 ssh->logctx = logctx;
10124}
10125
51470298 10126static int ssh_return_exitcode(void *handle)
10127{
10128 Ssh ssh = (Ssh) handle;
3bb2f322 10129 if (ssh->s != NULL)
10130 return -1;
10131 else
3c112d53 10132 return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
51470298 10133}
10134
10135/*
f89c3294 10136 * cfg_info for SSH is the currently running version of the
10137 * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
10138 */
10139static int ssh_cfg_info(void *handle)
10140{
10141 Ssh ssh = (Ssh) handle;
10142 return ssh->version;
10143}
10144
10145/*
51470298 10146 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
10147 * that fails. This variable is the means by which scp.c can reach
10148 * into the SSH code and find out which one it got.
10149 */
10150extern int ssh_fallback_cmd(void *handle)
d8d6c7e5 10151{
51470298 10152 Ssh ssh = (Ssh) handle;
10153 return ssh->fallback_cmd;
d8d6c7e5 10154}
10155
374330e2 10156Backend ssh_backend = {
10157 ssh_init,
fabd1805 10158 ssh_free,
86916870 10159 ssh_reconfig,
374330e2 10160 ssh_send,
5471d09a 10161 ssh_sendbuffer,
374330e2 10162 ssh_size,
4017be6d 10163 ssh_special,
125105d1 10164 ssh_get_specials,
6226c939 10165 ssh_connected,
d8d6c7e5 10166 ssh_return_exitcode,
97db3be4 10167 ssh_sendok,
0965bee0 10168 ssh_ldisc,
b9d7bcad 10169 ssh_provide_ldisc,
a8327734 10170 ssh_provide_logctx,
5471d09a 10171 ssh_unthrottle,
f89c3294 10172 ssh_cfg_info,
9e164d82 10173 "ssh",
10174 PROT_SSH,
97db3be4 10175 22
bc240b21 10176};