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