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