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