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