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