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