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