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