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