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