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