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