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