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