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