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