Turned the old `Telnet Command' System-submenu into a more general
[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 */
107#define SSH2_PKTCTX_DHGROUP1 0x0001
108#define SSH2_PKTCTX_DHGEX 0x0002
109#define SSH2_PKTCTX_PUBLICKEY 0x0010
110#define SSH2_PKTCTX_PASSWORD 0x0020
111#define SSH2_PKTCTX_KBDINTER 0x0040
112#define SSH2_PKTCTX_AUTH_MASK 0x00F0
113
32874aea 114#define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
115#define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
116#define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
117#define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
118#define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
119#define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
120#define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
121#define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
122#define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
123#define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
124#define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
125#define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
126#define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
127#define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
128#define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
38c4a8da 129
130static const char *const ssh2_disconnect_reasons[] = {
131 NULL,
132 "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
133 "SSH_DISCONNECT_PROTOCOL_ERROR",
134 "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
135 "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
136 "SSH_DISCONNECT_MAC_ERROR",
137 "SSH_DISCONNECT_COMPRESSION_ERROR",
138 "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
139 "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
140 "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
141 "SSH_DISCONNECT_CONNECTION_LOST",
142 "SSH_DISCONNECT_BY_APPLICATION",
143 "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
144 "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
145 "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
146 "SSH_DISCONNECT_ILLEGAL_USER_NAME",
147};
9005f3ba 148
32874aea 149#define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
150#define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
151#define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
152#define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
d211621f 153
32874aea 154#define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
fb09bf1c 155
7d503c31 156/*
157 * Various remote-bug flags.
158 */
159#define BUG_CHOKES_ON_SSH1_IGNORE 1
160#define BUG_SSH2_HMAC 2
bd358db1 161#define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
0df73905 162#define BUG_CHOKES_ON_RSA 8
1dd353b5 163#define BUG_SSH2_RSA_PADDING 16
088bde77 164#define BUG_SSH2_DERIVEKEY 32
8e975795 165#define BUG_SSH2_DH_GEX 64
dda87a28 166#define BUG_SSH2_PK_SESSIONID 128
bd358db1 167
00db133f 168#define translate(x) if (type == x) return #x
51470298 169#define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
ae9ae89f 170static char *ssh1_pkt_type(int type)
00db133f 171{
172 translate(SSH1_MSG_DISCONNECT);
173 translate(SSH1_SMSG_PUBLIC_KEY);
174 translate(SSH1_CMSG_SESSION_KEY);
175 translate(SSH1_CMSG_USER);
176 translate(SSH1_CMSG_AUTH_RSA);
177 translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
178 translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
179 translate(SSH1_CMSG_AUTH_PASSWORD);
180 translate(SSH1_CMSG_REQUEST_PTY);
181 translate(SSH1_CMSG_WINDOW_SIZE);
182 translate(SSH1_CMSG_EXEC_SHELL);
183 translate(SSH1_CMSG_EXEC_CMD);
184 translate(SSH1_SMSG_SUCCESS);
185 translate(SSH1_SMSG_FAILURE);
186 translate(SSH1_CMSG_STDIN_DATA);
187 translate(SSH1_SMSG_STDOUT_DATA);
188 translate(SSH1_SMSG_STDERR_DATA);
189 translate(SSH1_CMSG_EOF);
190 translate(SSH1_SMSG_EXIT_STATUS);
191 translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
192 translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
193 translate(SSH1_MSG_CHANNEL_DATA);
194 translate(SSH1_MSG_CHANNEL_CLOSE);
195 translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
196 translate(SSH1_SMSG_X11_OPEN);
197 translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
198 translate(SSH1_MSG_PORT_OPEN);
199 translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
200 translate(SSH1_SMSG_AGENT_OPEN);
201 translate(SSH1_MSG_IGNORE);
202 translate(SSH1_CMSG_EXIT_CONFIRMATION);
203 translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
204 translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
205 translate(SSH1_MSG_DEBUG);
206 translate(SSH1_CMSG_REQUEST_COMPRESSION);
207 translate(SSH1_CMSG_AUTH_TIS);
208 translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
209 translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
210 translate(SSH1_CMSG_AUTH_CCARD);
211 translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
212 translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
213 return "unknown";
214}
ae9ae89f 215static char *ssh2_pkt_type(int pkt_ctx, int type)
00db133f 216{
217 translate(SSH2_MSG_DISCONNECT);
218 translate(SSH2_MSG_IGNORE);
219 translate(SSH2_MSG_UNIMPLEMENTED);
220 translate(SSH2_MSG_DEBUG);
221 translate(SSH2_MSG_SERVICE_REQUEST);
222 translate(SSH2_MSG_SERVICE_ACCEPT);
223 translate(SSH2_MSG_KEXINIT);
224 translate(SSH2_MSG_NEWKEYS);
225 translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
226 translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
227 translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
228 translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
229 translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
230 translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
231 translate(SSH2_MSG_USERAUTH_REQUEST);
232 translate(SSH2_MSG_USERAUTH_FAILURE);
233 translate(SSH2_MSG_USERAUTH_SUCCESS);
234 translate(SSH2_MSG_USERAUTH_BANNER);
235 translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
236 translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
237 translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
238 translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
239 translate(SSH2_MSG_GLOBAL_REQUEST);
240 translate(SSH2_MSG_REQUEST_SUCCESS);
241 translate(SSH2_MSG_REQUEST_FAILURE);
242 translate(SSH2_MSG_CHANNEL_OPEN);
243 translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
244 translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
245 translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
246 translate(SSH2_MSG_CHANNEL_DATA);
247 translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
248 translate(SSH2_MSG_CHANNEL_EOF);
249 translate(SSH2_MSG_CHANNEL_CLOSE);
250 translate(SSH2_MSG_CHANNEL_REQUEST);
251 translate(SSH2_MSG_CHANNEL_SUCCESS);
252 translate(SSH2_MSG_CHANNEL_FAILURE);
253 return "unknown";
254}
255#undef translate
256#undef translatec
7d503c31 257
fb09bf1c 258#define GET_32BIT(cp) \
259 (((unsigned long)(unsigned char)(cp)[0] << 24) | \
260 ((unsigned long)(unsigned char)(cp)[1] << 16) | \
261 ((unsigned long)(unsigned char)(cp)[2] << 8) | \
262 ((unsigned long)(unsigned char)(cp)[3]))
263
264#define PUT_32BIT(cp, value) { \
265 (cp)[0] = (unsigned char)((value) >> 24); \
266 (cp)[1] = (unsigned char)((value) >> 16); \
267 (cp)[2] = (unsigned char)((value) >> 8); \
268 (cp)[3] = (unsigned char)(value); }
269
7cca0d81 270enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
972a41c8 271
acddebd9 272/*
273 * Coroutine mechanics for the sillier bits of the code. If these
274 * macros look impenetrable to you, you might find it helpful to
275 * read
276 *
277 * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
278 *
279 * which explains the theory behind these macros.
b624d1e6 280 *
281 * In particular, if you are getting `case expression not constant'
282 * errors when building with MS Visual Studio, this is because MS's
283 * Edit and Continue debugging feature causes their compiler to
284 * violate ANSI C. To disable Edit and Continue debugging:
285 *
286 * - right-click ssh.c in the FileView
287 * - click Settings
288 * - select the C/C++ tab and the General category
289 * - under `Debug info:', select anything _other_ than `Program
290 * Database for Edit and Continue'.
acddebd9 291 */
51470298 292#define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
293#define crState(t) \
294 struct t *s; \
3d88e64d 295 if (!ssh->t) ssh->t = snew(struct t); \
51470298 296 s = ssh->t;
297#define crFinish(z) } *crLine = 0; return (z); }
298#define crFinishV } *crLine = 0; return; }
374330e2 299#define crReturn(z) \
300 do {\
51470298 301 *crLine =__LINE__; return (z); case __LINE__:;\
374330e2 302 } while (0)
303#define crReturnV \
304 do {\
51470298 305 *crLine=__LINE__; return; case __LINE__:;\
374330e2 306 } while (0)
51470298 307#define crStop(z) do{ *crLine = 0; return (z); }while(0)
308#define crStopV do{ *crLine = 0; return; }while(0)
fb09bf1c 309#define crWaitUntil(c) do { crReturn(0); } while (!(c))
7cca0d81 310#define crWaitUntilV(c) do { crReturnV; } while (!(c))
374330e2 311
51470298 312typedef struct ssh_tag *Ssh;
313
51470298 314static void ssh2_pkt_init(Ssh, int pkt_type);
315static void ssh2_pkt_addbool(Ssh, unsigned char value);
316static void ssh2_pkt_adduint32(Ssh, unsigned long value);
317static void ssh2_pkt_addstring_start(Ssh);
318static void ssh2_pkt_addstring_str(Ssh, char *data);
319static void ssh2_pkt_addstring_data(Ssh, char *data, int len);
320static void ssh2_pkt_addstring(Ssh, char *data);
d8baa528 321static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
51470298 322static void ssh2_pkt_addmp(Ssh, Bignum b);
323static int ssh2_pkt_construct(Ssh);
324static void ssh2_pkt_send(Ssh);
3d63ca2e 325
5471d09a 326/*
327 * Buffer management constants. There are several of these for
328 * various different purposes:
329 *
330 * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
331 * on a local data stream before we throttle the whole SSH
332 * connection (in SSH1 only). Throttling the whole connection is
333 * pretty drastic so we set this high in the hope it won't
334 * happen very often.
335 *
336 * - SSH_MAX_BACKLOG is the amount of backlog that must build up
337 * on the SSH connection itself before we defensively throttle
338 * _all_ local data streams. This is pretty drastic too (though
339 * thankfully unlikely in SSH2 since the window mechanism should
340 * ensure that the server never has any need to throttle its end
341 * of the connection), so we set this high as well.
342 *
343 * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
344 * channels.
345 */
346
347#define SSH1_BUFFER_LIMIT 32768
348#define SSH_MAX_BACKLOG 32768
349#define OUR_V2_WINSIZE 16384
d74d141c 350
a92dd380 351const static struct ssh_kex *kex_algs[] = {
a92dd380 352 &ssh_diffiehellman_gex,
32874aea 353 &ssh_diffiehellman
354};
e5574168 355
85cc02bb 356const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
e5574168 357
e0e1a00d 358static void *nullmac_make_context(void)
359{
360 return NULL;
361}
362static void nullmac_free_context(void *handle)
363{
364}
365static void nullmac_key(void *handle, unsigned char *key)
32874aea 366{
367}
e0e1a00d 368static void nullmac_generate(void *handle, unsigned char *blk, int len,
32874aea 369 unsigned long seq)
370{
371}
e0e1a00d 372static int nullmac_verify(void *handle, unsigned char *blk, int len,
373 unsigned long seq)
32874aea 374{
375 return 1;
376}
57476f6b 377const static struct ssh_mac ssh_mac_none = {
e0e1a00d 378 nullmac_make_context, nullmac_free_context, nullmac_key,
379 nullmac_generate, nullmac_verify, "none", 0
e5574168 380};
8b2715b2 381const static struct ssh_mac *macs[] = {
32874aea 382 &ssh_sha1, &ssh_md5, &ssh_mac_none
383};
8b2715b2 384const static struct ssh_mac *buggymacs[] = {
32874aea 385 &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
386};
e5574168 387
5366aed8 388static void *ssh_comp_none_init(void)
389{
390 return NULL;
391}
392static void ssh_comp_none_cleanup(void *handle)
32874aea 393{
394}
5366aed8 395static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
32874aea 396 unsigned char **outblock, int *outlen)
397{
398 return 0;
399}
5366aed8 400static int ssh_comp_none_disable(void *handle)
32874aea 401{
4ba9b64b 402 return 0;
403}
57476f6b 404const static struct ssh_compress ssh_comp_none = {
4ba9b64b 405 "none",
5366aed8 406 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
407 ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
408 ssh_comp_none_disable, NULL
e5574168 409};
4ba9b64b 410extern const struct ssh_compress ssh_zlib;
411const static struct ssh_compress *compressions[] = {
32874aea 412 &ssh_zlib, &ssh_comp_none
413};
374330e2 414
32874aea 415enum { /* channel types */
783415f8 416 CHAN_MAINSESSION,
417 CHAN_X11,
418 CHAN_AGENT,
bc240b21 419 CHAN_SOCKDATA,
420 CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
783415f8 421};
422
dacbd0e8 423/*
424 * 2-3-4 tree storing channels.
425 */
426struct ssh_channel {
51470298 427 Ssh ssh; /* pointer back to main context */
d211621f 428 unsigned remoteid, localid;
dacbd0e8 429 int type;
0357890f 430 /*
431 * In SSH1, this value contains four bits:
432 *
433 * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
434 * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
435 * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
436 * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
437 *
438 * A channel is completely finished with when all four bits are set.
439 */
dacbd0e8 440 int closes;
5471d09a 441 union {
442 struct ssh1_data_channel {
443 int throttling;
444 } v1;
445 struct ssh2_data_channel {
446 bufchain outbuffer;
447 unsigned remwindow, remmaxpkt;
448 unsigned locwindow;
449 } v2;
450 } v;
dacbd0e8 451 union {
32874aea 452 struct ssh_agent_channel {
453 unsigned char *message;
454 unsigned char msglen[4];
455 int lensofar, totallen;
456 } a;
457 struct ssh_x11_channel {
458 Socket s;
459 } x11;
d74d141c 460 struct ssh_pfd_channel {
461 Socket s;
462 } pfd;
dacbd0e8 463 } u;
464};
57476f6b 465
d74d141c 466/*
bc240b21 467 * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
468 * 2 use this structure in different ways, reflecting SSH 2's
469 * altogether saner approach to port forwarding.
470 *
471 * In SSH 1, you arrange a remote forwarding by sending the server
472 * the remote port number, and the local destination host:port.
473 * When a connection comes in, the server sends you back that
474 * host:port pair, and you connect to it. This is a ready-made
475 * security hole if you're not on the ball: a malicious server
476 * could send you back _any_ host:port pair, so if you trustingly
477 * connect to the address it gives you then you've just opened the
478 * entire inside of your corporate network just by connecting
479 * through it to a dodgy SSH server. Hence, we must store a list of
480 * host:port pairs we _are_ trying to forward to, and reject a
481 * connection request from the server if it's not in the list.
482 *
483 * In SSH 2, each side of the connection minds its own business and
484 * doesn't send unnecessary information to the other. You arrange a
485 * remote forwarding by sending the server just the remote port
486 * number. When a connection comes in, the server tells you which
487 * of its ports was connected to; and _you_ have to remember what
488 * local host:port pair went with that port number.
489 *
490 * Hence: in SSH 1 this structure stores host:port pairs we intend
491 * to allow connections to, and is indexed by those host:port
492 * pairs. In SSH 2 it stores a mapping from source port to
493 * destination host:port pair, and is indexed by source port.
d74d141c 494 */
495struct ssh_rportfwd {
bc240b21 496 unsigned sport, dport;
497 char dhost[256];
d74d141c 498};
499
57476f6b 500struct Packet {
501 long length;
502 int type;
503 unsigned char *data;
504 unsigned char *body;
505 long savedpos;
506 long maxlen;
507};
508
51470298 509static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
510static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
511static void ssh_size(void *handle, int width, int height);
512static void ssh_special(void *handle, Telnet_Special);
5471d09a 513static int ssh2_try_send(struct ssh_channel *c);
51470298 514static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
515static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
5471d09a 516static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
51470298 517static int ssh_sendbuffer(void *handle);
57476f6b 518
51470298 519struct rdpkt1_state_tag {
57476f6b 520 long len, pad, biglen, to_read;
521 unsigned long realcrc, gotcrc;
522 unsigned char *p;
523 int i;
524 int chunk;
51470298 525};
57476f6b 526
51470298 527struct rdpkt2_state_tag {
960e736a 528 long len, pad, payload, packetlen, maclen;
529 int i;
530 int cipherblk;
531 unsigned long incoming_sequence;
51470298 532};
533
534struct ssh_tag {
535 const struct plug_function_table *fn;
536 /* the above field _must_ be first in the structure */
537
538 SHA_State exhash, exhashbase;
539
540 Socket s;
541
b9d7bcad 542 void *ldisc;
a8327734 543 void *logctx;
b9d7bcad 544
51470298 545 unsigned char session_key[32];
546 int v1_compressing;
547 int v1_remote_protoflags;
548 int v1_local_protoflags;
549 int agentfwd_enabled;
550 int X11_fwd_enabled;
551 int remote_bugs;
552 const struct ssh_cipher *cipher;
371e569c 553 void *v1_cipher_ctx;
0183b242 554 void *crcda_ctx;
51470298 555 const struct ssh2_cipher *cscipher, *sccipher;
371e569c 556 void *cs_cipher_ctx, *sc_cipher_ctx;
51470298 557 const struct ssh_mac *csmac, *scmac;
e0e1a00d 558 void *cs_mac_ctx, *sc_mac_ctx;
51470298 559 const struct ssh_compress *cscomp, *sccomp;
5366aed8 560 void *cs_comp_ctx, *sc_comp_ctx;
51470298 561 const struct ssh_kex *kex;
562 const struct ssh_signkey *hostkey;
563 unsigned char v2_session_id[20];
27cd7fc2 564 void *kex_ctx;
51470298 565
566 char *savedhost;
567 int savedport;
568 int send_ok;
569 int echoing, editing;
570
571 void *frontend;
572
573 int term_width, term_height;
574
575 tree234 *channels; /* indexed by local id */
576 struct ssh_channel *mainchan; /* primary session channel */
577 int exitcode;
578
579 tree234 *rportfwds;
580
581 enum {
582 SSH_STATE_PREPACKET,
583 SSH_STATE_BEFORE_SIZE,
584 SSH_STATE_INTERMED,
585 SSH_STATE_SESSION,
586 SSH_STATE_CLOSED
587 } state;
588
589 int size_needed, eof_needed;
590
591 struct Packet pktin;
592 struct Packet pktout;
593 unsigned char *deferred_send_data;
594 int deferred_len, deferred_size;
595
596 /*
597 * Gross hack: pscp will try to start SFTP but fall back to
598 * scp1 if that fails. This variable is the means by which
599 * scp.c can reach into the SSH code and find out which one it
600 * got.
601 */
602 int fallback_cmd;
603
604 /*
605 * Used for username and password input.
606 */
607 char *userpass_input_buffer;
608 int userpass_input_buflen;
609 int userpass_input_bufpos;
610 int userpass_input_echo;
611
612 char *portfwd_strptr;
613 int pkt_ctx;
614
302121de 615 void *x11auth;
616
51470298 617 int version;
618 int v1_throttle_count;
619 int overall_bufsize;
620 int throttled_all;
621 int v1_stdout_throttling;
622 int v2_outgoing_sequence;
623
624 int ssh1_rdpkt_crstate;
625 int ssh2_rdpkt_crstate;
626 int do_ssh_init_crstate;
627 int ssh_gotdata_crstate;
628 int ssh1_protocol_crstate;
629 int do_ssh1_login_crstate;
630 int do_ssh2_transport_crstate;
631 int do_ssh2_authconn_crstate;
632
633 void *do_ssh_init_state;
634 void *do_ssh1_login_state;
635 void *do_ssh2_transport_state;
636 void *do_ssh2_authconn_state;
637
638 struct rdpkt1_state_tag rdpkt1_state;
639 struct rdpkt2_state_tag rdpkt2_state;
640
641 void (*protocol) (Ssh ssh, unsigned char *in, int inlen, int ispkt);
642 int (*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
86916870 643
644 /*
645 * We maintain a full _copy_ of a Config structure here, not
646 * merely a pointer to it. That way, when we're passed a new
647 * one for reconfiguration, we can check the differences and
648 * potentially reconfigure port forwardings etc in mid-session.
649 */
650 Config cfg;
51470298 651};
960e736a 652
382908ad 653#define logevent(s) logevent(ssh->frontend, s)
a8327734 654
655/* logevent, only printf-formatted. */
ae9ae89f 656static void logeventf(Ssh ssh, char *fmt, ...)
a8327734 657{
658 va_list ap;
57356d63 659 char *buf;
a8327734 660
661 va_start(ap, fmt);
57356d63 662 buf = dupvprintf(fmt, ap);
a8327734 663 va_end(ap);
57356d63 664 logevent(buf);
57356d63 665 sfree(buf);
a8327734 666}
667
6b5cf8b4 668#define bombout(msg) \
669 do { \
670 char *text = dupprintf msg; \
671 ssh->state = SSH_STATE_CLOSED; \
672 if (ssh->s) { sk_close(ssh->s); ssh->s = NULL; } \
673 logevent(text); \
674 connection_fatal(ssh->frontend, "%s", text); \
675 sfree(text); \
676 } while (0)
a8327734 677
32874aea 678static int ssh_channelcmp(void *av, void *bv)
679{
680 struct ssh_channel *a = (struct ssh_channel *) av;
681 struct ssh_channel *b = (struct ssh_channel *) bv;
682 if (a->localid < b->localid)
683 return -1;
684 if (a->localid > b->localid)
685 return +1;
dacbd0e8 686 return 0;
687}
32874aea 688static int ssh_channelfind(void *av, void *bv)
689{
690 unsigned *a = (unsigned *) av;
691 struct ssh_channel *b = (struct ssh_channel *) bv;
692 if (*a < b->localid)
693 return -1;
694 if (*a > b->localid)
695 return +1;
dacbd0e8 696 return 0;
697}
698
bc240b21 699static int ssh_rportcmp_ssh1(void *av, void *bv)
d74d141c 700{
701 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
702 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
703 int i;
bc240b21 704 if ( (i = strcmp(a->dhost, b->dhost)) != 0)
d74d141c 705 return i < 0 ? -1 : +1;
bc240b21 706 if (a->dport > b->dport)
707 return +1;
708 if (a->dport < b->dport)
709 return -1;
710 return 0;
711}
712
713static int ssh_rportcmp_ssh2(void *av, void *bv)
714{
715 struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
716 struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
cdcbdf3b 717
bc240b21 718 if (a->sport > b->sport)
d74d141c 719 return +1;
bc240b21 720 if (a->sport < b->sport)
721 return -1;
d74d141c 722 return 0;
723}
724
51470298 725static int alloc_channel_id(Ssh ssh)
32874aea 726{
260f3dec 727 const unsigned CHANNEL_NUMBER_OFFSET = 256;
728 unsigned low, high, mid;
d2371c81 729 int tsize;
730 struct ssh_channel *c;
731
732 /*
733 * First-fit allocation of channel numbers: always pick the
734 * lowest unused one. To do this, binary-search using the
735 * counted B-tree to find the largest channel ID which is in a
736 * contiguous sequence from the beginning. (Precisely
737 * everything in that sequence must have ID equal to its tree
738 * index plus CHANNEL_NUMBER_OFFSET.)
739 */
51470298 740 tsize = count234(ssh->channels);
d2371c81 741
32874aea 742 low = -1;
743 high = tsize;
d2371c81 744 while (high - low > 1) {
745 mid = (high + low) / 2;
51470298 746 c = index234(ssh->channels, mid);
d2371c81 747 if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
748 low = mid; /* this one is fine */
749 else
750 high = mid; /* this one is past it */
751 }
752 /*
753 * Now low points to either -1, or the tree index of the
754 * largest ID in the initial sequence.
755 */
756 {
757 unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
51470298 758 assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
d2371c81 759 }
760 return low + 1 + CHANNEL_NUMBER_OFFSET;
761}
762
9fab77dc 763static void c_write(Ssh ssh, const char *buf, int len)
32874aea 764{
67779be7 765 if ((flags & FLAG_STDERR)) {
32874aea 766 int i;
767 for (i = 0; i < len; i++)
768 if (buf[i] != '\r')
769 fputc(buf[i], stderr);
fb09bf1c 770 return;
771 }
51470298 772 from_backend(ssh->frontend, 1, buf, len);
3bdaf79d 773}
774
9fab77dc 775static void c_write_untrusted(Ssh ssh, const char *buf, int len)
32874aea 776{
a209e957 777 int i;
778 for (i = 0; i < len; i++) {
32874aea 779 if (buf[i] == '\n')
51470298 780 c_write(ssh, "\r\n", 2);
32874aea 781 else if ((buf[i] & 0x60) || (buf[i] == '\r'))
51470298 782 c_write(ssh, buf + i, 1);
a209e957 783 }
784}
785
9fab77dc 786static void c_write_str(Ssh ssh, const char *buf)
32874aea 787{
51470298 788 c_write(ssh, buf, strlen(buf));
1408a877 789}
790
fb09bf1c 791/*
792 * Collect incoming data in the incoming packet buffer.
e5574168 793 * Decipher and verify the packet when it is completely read.
794 * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
fb09bf1c 795 * Update the *data and *datalen variables.
796 * Return the additional nr of bytes needed, or 0 when
797 * a complete packet is available.
798 */
51470298 799static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
fb09bf1c 800{
51470298 801 struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
374330e2 802
51470298 803 crBegin(ssh->ssh1_rdpkt_crstate);
374330e2 804
32874aea 805 next_packet:
37508af4 806
51470298 807 ssh->pktin.type = 0;
808 ssh->pktin.length = 0;
374330e2 809
57476f6b 810 for (st->i = st->len = 0; st->i < 4; st->i++) {
fb09bf1c 811 while ((*datalen) == 0)
32874aea 812 crReturn(4 - st->i);
57476f6b 813 st->len = (st->len << 8) + **data;
fb09bf1c 814 (*data)++, (*datalen)--;
815 }
374330e2 816
57476f6b 817 st->pad = 8 - (st->len % 8);
818 st->biglen = st->len + st->pad;
51470298 819 ssh->pktin.length = st->len - 5;
fb09bf1c 820
51470298 821 if (ssh->pktin.maxlen < st->biglen) {
822 ssh->pktin.maxlen = st->biglen;
3d88e64d 823 ssh->pktin.data = sresize(ssh->pktin.data, st->biglen + APIEXTRA,
824 unsigned char);
fb09bf1c 825 }
374330e2 826
57476f6b 827 st->to_read = st->biglen;
51470298 828 st->p = ssh->pktin.data;
57476f6b 829 while (st->to_read > 0) {
32874aea 830 st->chunk = st->to_read;
fb09bf1c 831 while ((*datalen) == 0)
57476f6b 832 crReturn(st->to_read);
833 if (st->chunk > (*datalen))
834 st->chunk = (*datalen);
835 memcpy(st->p, *data, st->chunk);
836 *data += st->chunk;
837 *datalen -= st->chunk;
838 st->p += st->chunk;
839 st->to_read -= st->chunk;
fb09bf1c 840 }
374330e2 841
0183b242 842 if (ssh->cipher && detect_attack(ssh->crcda_ctx, ssh->pktin.data,
843 st->biglen, NULL)) {
6b5cf8b4 844 bombout(("Network attack (CRC compensation) detected!"));
9a3a93a5 845 crReturn(0);
846 }
847
51470298 848 if (ssh->cipher)
371e569c 849 ssh->cipher->decrypt(ssh->v1_cipher_ctx, ssh->pktin.data, st->biglen);
374330e2 850
51470298 851 st->realcrc = crc32(ssh->pktin.data, st->biglen - 4);
852 st->gotcrc = GET_32BIT(ssh->pktin.data + st->biglen - 4);
57476f6b 853 if (st->gotcrc != st->realcrc) {
6b5cf8b4 854 bombout(("Incorrect CRC received on packet"));
32874aea 855 crReturn(0);
fb09bf1c 856 }
572f871e 857
51470298 858 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
4ba9b64b 859
51470298 860 if (ssh->v1_compressing) {
4ba9b64b 861 unsigned char *decompblk;
862 int decomplen;
5366aed8 863 zlib_decompress_block(ssh->sc_comp_ctx,
864 ssh->pktin.body - 1, ssh->pktin.length + 1,
4ba9b64b 865 &decompblk, &decomplen);
866
51470298 867 if (ssh->pktin.maxlen < st->pad + decomplen) {
868 ssh->pktin.maxlen = st->pad + decomplen;
3d88e64d 869 ssh->pktin.data = sresize(ssh->pktin.data,
870 ssh->pktin.maxlen + APIEXTRA,
871 unsigned char);
51470298 872 ssh->pktin.body = ssh->pktin.data + st->pad + 1;
4ba9b64b 873 }
874
51470298 875 memcpy(ssh->pktin.body - 1, decompblk, decomplen);
dcbde236 876 sfree(decompblk);
51470298 877 ssh->pktin.length = decomplen - 1;
4ba9b64b 878 }
879
51470298 880 ssh->pktin.type = ssh->pktin.body[-1];
00db133f 881
a8327734 882 if (ssh->logctx)
883 log_packet(ssh->logctx,
884 PKT_INCOMING, ssh->pktin.type,
885 ssh1_pkt_type(ssh->pktin.type),
886 ssh->pktin.body, ssh->pktin.length);
00db133f 887
51470298 888 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
889 ssh->pktin.type == SSH1_SMSG_STDERR_DATA ||
890 ssh->pktin.type == SSH1_MSG_DEBUG ||
891 ssh->pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
892 ssh->pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
893 long stringlen = GET_32BIT(ssh->pktin.body);
894 if (stringlen + 4 != ssh->pktin.length) {
6b5cf8b4 895 bombout(("Received data packet with bogus string length"));
32874aea 896 crReturn(0);
897 }
fb09bf1c 898 }
899
51470298 900 if (ssh->pktin.type == SSH1_MSG_DEBUG) {
fb09bf1c 901 /* log debug message */
eb4504cc 902 char buf[512];
51470298 903 int stringlen = GET_32BIT(ssh->pktin.body);
eb4504cc 904 strcpy(buf, "Remote debug message: ");
905 if (stringlen > 480)
906 stringlen = 480;
51470298 907 memcpy(buf + 8, ssh->pktin.body + 4, stringlen);
3d63ca2e 908 buf[8 + stringlen] = '\0';
fb09bf1c 909 logevent(buf);
910 goto next_packet;
51470298 911 } else if (ssh->pktin.type == SSH1_MSG_IGNORE) {
fb09bf1c 912 /* do nothing */
913 goto next_packet;
914 }
915
51470298 916 if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
38c4a8da 917 /* log reason code in disconnect message */
918 char buf[256];
51470298 919 unsigned msglen = GET_32BIT(ssh->pktin.body);
260f3dec 920 unsigned nowlen;
38c4a8da 921 strcpy(buf, "Remote sent disconnect: ");
922 nowlen = strlen(buf);
32874aea 923 if (msglen > sizeof(buf) - nowlen - 1)
924 msglen = sizeof(buf) - nowlen - 1;
51470298 925 memcpy(buf + nowlen, ssh->pktin.body + 4, msglen);
32874aea 926 buf[nowlen + msglen] = '\0';
247308b5 927 /* logevent(buf); (this is now done within the bombout macro) */
6b5cf8b4 928 bombout(("Server sent disconnect message:\n\"%s\"", buf+nowlen));
e14d0f19 929 crReturn(0);
38c4a8da 930 }
931
fb09bf1c 932 crFinish(0);
933}
934
51470298 935static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
e5574168 936{
51470298 937 struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
e5574168 938
51470298 939 crBegin(ssh->ssh2_rdpkt_crstate);
e5574168 940
32874aea 941 next_packet:
51470298 942 ssh->pktin.type = 0;
943 ssh->pktin.length = 0;
944 if (ssh->sccipher)
945 st->cipherblk = ssh->sccipher->blksize;
e5574168 946 else
32874aea 947 st->cipherblk = 8;
960e736a 948 if (st->cipherblk < 8)
32874aea 949 st->cipherblk = 8;
960e736a 950
51470298 951 if (ssh->pktin.maxlen < st->cipherblk) {
952 ssh->pktin.maxlen = st->cipherblk;
3d88e64d 953 ssh->pktin.data = sresize(ssh->pktin.data, st->cipherblk + APIEXTRA,
954 unsigned char);
e5574168 955 }
956
957 /*
958 * Acquire and decrypt the first block of the packet. This will
959 * contain the length and padding details.
960 */
32874aea 961 for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
e5574168 962 while ((*datalen) == 0)
32874aea 963 crReturn(st->cipherblk - st->i);
51470298 964 ssh->pktin.data[st->i] = *(*data)++;
32874aea 965 (*datalen)--;
e5574168 966 }
4252c9cc 967
51470298 968 if (ssh->sccipher)
371e569c 969 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
970 ssh->pktin.data, st->cipherblk);
e5574168 971
972 /*
973 * Now get the length and padding figures.
974 */
51470298 975 st->len = GET_32BIT(ssh->pktin.data);
976 st->pad = ssh->pktin.data[4];
e5574168 977
978 /*
717dc483 979 * _Completely_ silly lengths should be stomped on before they
980 * do us any more damage.
981 */
982 if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
6b5cf8b4 983 bombout(("Incoming packet was garbled on decryption"));
717dc483 984 crReturn(0);
985 }
986
987 /*
e5574168 988 * This enables us to deduce the payload length.
989 */
960e736a 990 st->payload = st->len - st->pad - 1;
e5574168 991
51470298 992 ssh->pktin.length = st->payload + 5;
e5574168 993
994 /*
995 * So now we can work out the total packet length.
996 */
960e736a 997 st->packetlen = st->len + 4;
51470298 998 st->maclen = ssh->scmac ? ssh->scmac->len : 0;
e5574168 999
1000 /*
1001 * Adjust memory allocation if packet is too big.
1002 */
51470298 1003 if (ssh->pktin.maxlen < st->packetlen + st->maclen) {
1004 ssh->pktin.maxlen = st->packetlen + st->maclen;
3d88e64d 1005 ssh->pktin.data = sresize(ssh->pktin.data,
1006 ssh->pktin.maxlen + APIEXTRA,
1007 unsigned char);
e5574168 1008 }
1009
1010 /*
1011 * Read and decrypt the remainder of the packet.
1012 */
32874aea 1013 for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
1014 st->i++) {
e5574168 1015 while ((*datalen) == 0)
960e736a 1016 crReturn(st->packetlen + st->maclen - st->i);
51470298 1017 ssh->pktin.data[st->i] = *(*data)++;
32874aea 1018 (*datalen)--;
e5574168 1019 }
1020 /* Decrypt everything _except_ the MAC. */
51470298 1021 if (ssh->sccipher)
371e569c 1022 ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
1023 ssh->pktin.data + st->cipherblk,
51470298 1024 st->packetlen - st->cipherblk);
e5574168 1025
1026 /*
1027 * Check the MAC.
1028 */
51470298 1029 if (ssh->scmac
e0e1a00d 1030 && !ssh->scmac->verify(ssh->sc_mac_ctx, ssh->pktin.data, st->len + 4,
51470298 1031 st->incoming_sequence)) {
6b5cf8b4 1032 bombout(("Incorrect MAC received on packet"));
32874aea 1033 crReturn(0);
8d5de777 1034 }
32874aea 1035 st->incoming_sequence++; /* whether or not we MACed */
e5574168 1036
4ba9b64b 1037 /*
1038 * Decompress packet payload.
1039 */
1040 {
1041 unsigned char *newpayload;
1042 int newlen;
51470298 1043 if (ssh->sccomp &&
5366aed8 1044 ssh->sccomp->decompress(ssh->sc_comp_ctx,
1045 ssh->pktin.data + 5, ssh->pktin.length - 5,
51470298 1046 &newpayload, &newlen)) {
1047 if (ssh->pktin.maxlen < newlen + 5) {
1048 ssh->pktin.maxlen = newlen + 5;
3d88e64d 1049 ssh->pktin.data = sresize(ssh->pktin.data,
1050 ssh->pktin.maxlen + APIEXTRA,
1051 unsigned char);
4ba9b64b 1052 }
51470298 1053 ssh->pktin.length = 5 + newlen;
1054 memcpy(ssh->pktin.data + 5, newpayload, newlen);
dcbde236 1055 sfree(newpayload);
4ba9b64b 1056 }
1057 }
1058
51470298 1059 ssh->pktin.savedpos = 6;
1060 ssh->pktin.type = ssh->pktin.data[5];
e5574168 1061
a8327734 1062 if (ssh->logctx)
1063 log_packet(ssh->logctx, PKT_INCOMING, ssh->pktin.type,
1064 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktin.type),
1065 ssh->pktin.data+6, ssh->pktin.length-6);
00db133f 1066
51470298 1067 switch (ssh->pktin.type) {
3d63ca2e 1068 /*
1069 * These packets we must handle instantly.
1070 */
1071 case SSH2_MSG_DISCONNECT:
1072 {
1073 /* log reason code in disconnect message */
57356d63 1074 char *buf;
1075 int nowlen;
51470298 1076 int reason = GET_32BIT(ssh->pktin.data + 6);
1077 unsigned msglen = GET_32BIT(ssh->pktin.data + 10);
57356d63 1078
3d63ca2e 1079 if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
57356d63 1080 buf = dupprintf("Received disconnect message (%s)",
1081 ssh2_disconnect_reasons[reason]);
3d63ca2e 1082 } else {
57356d63 1083 buf = dupprintf("Received disconnect message (unknown"
1084 " type %d)", reason);
3d63ca2e 1085 }
1086 logevent(buf);
57356d63 1087 sfree(buf);
1088 buf = dupprintf("Disconnection message text: %n%.*s",
33b82b22 1089 &nowlen, msglen, ssh->pktin.data + 14);
3d63ca2e 1090 logevent(buf);
6b5cf8b4 1091 bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
3d63ca2e 1092 reason,
1093 (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
1094 ssh2_disconnect_reasons[reason] : "unknown",
1095 buf+nowlen));
57356d63 1096 sfree(buf);
3d63ca2e 1097 crReturn(0);
1098 }
1099 break;
1100 case SSH2_MSG_IGNORE:
1101 goto next_packet;
1102 case SSH2_MSG_DEBUG:
1103 {
1104 /* log the debug message */
1105 char buf[512];
51470298 1106 /* int display = ssh->pktin.body[6]; */
1107 int stringlen = GET_32BIT(ssh->pktin.data+7);
3d63ca2e 1108 int prefix;
1109 strcpy(buf, "Remote debug message: ");
1110 prefix = strlen(buf);
51470298 1111 if (stringlen > (int)(sizeof(buf)-prefix-1))
3d63ca2e 1112 stringlen = sizeof(buf)-prefix-1;
51470298 1113 memcpy(buf + prefix, ssh->pktin.data + 11, stringlen);
3d63ca2e 1114 buf[prefix + stringlen] = '\0';
1115 logevent(buf);
38c4a8da 1116 }
3d63ca2e 1117 goto next_packet; /* FIXME: print the debug message */
1118
1119 /*
1120 * These packets we need do nothing about here.
1121 */
1122 case SSH2_MSG_UNIMPLEMENTED:
1123 case SSH2_MSG_SERVICE_REQUEST:
1124 case SSH2_MSG_SERVICE_ACCEPT:
1125 case SSH2_MSG_KEXINIT:
1126 case SSH2_MSG_NEWKEYS:
1127 case SSH2_MSG_KEXDH_INIT:
1128 case SSH2_MSG_KEXDH_REPLY:
1129 /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
1130 /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
1131 case SSH2_MSG_KEX_DH_GEX_INIT:
1132 case SSH2_MSG_KEX_DH_GEX_REPLY:
1133 case SSH2_MSG_USERAUTH_REQUEST:
1134 case SSH2_MSG_USERAUTH_FAILURE:
1135 case SSH2_MSG_USERAUTH_SUCCESS:
1136 case SSH2_MSG_USERAUTH_BANNER:
1137 case SSH2_MSG_USERAUTH_PK_OK:
1138 /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
1139 /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
1140 case SSH2_MSG_USERAUTH_INFO_RESPONSE:
1141 case SSH2_MSG_GLOBAL_REQUEST:
1142 case SSH2_MSG_REQUEST_SUCCESS:
1143 case SSH2_MSG_REQUEST_FAILURE:
1144 case SSH2_MSG_CHANNEL_OPEN:
1145 case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
1146 case SSH2_MSG_CHANNEL_OPEN_FAILURE:
1147 case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
1148 case SSH2_MSG_CHANNEL_DATA:
1149 case SSH2_MSG_CHANNEL_EXTENDED_DATA:
1150 case SSH2_MSG_CHANNEL_EOF:
1151 case SSH2_MSG_CHANNEL_CLOSE:
1152 case SSH2_MSG_CHANNEL_REQUEST:
1153 case SSH2_MSG_CHANNEL_SUCCESS:
1154 case SSH2_MSG_CHANNEL_FAILURE:
1155 break;
1156
1157 /*
1158 * For anything else we send SSH2_MSG_UNIMPLEMENTED.
1159 */
1160 default:
51470298 1161 ssh2_pkt_init(ssh, SSH2_MSG_UNIMPLEMENTED);
1162 ssh2_pkt_adduint32(ssh, st->incoming_sequence - 1);
1163 ssh2_pkt_send(ssh);
3d63ca2e 1164 break;
38c4a8da 1165 }
1166
e5574168 1167 crFinish(0);
1168}
1169
51470298 1170static void ssh1_pktout_size(Ssh ssh, int len)
32874aea 1171{
374330e2 1172 int pad, biglen;
1173
1174 len += 5; /* type and CRC */
32874aea 1175 pad = 8 - (len % 8);
374330e2 1176 biglen = len + pad;
1177
51470298 1178 ssh->pktout.length = len - 5;
1179 if (ssh->pktout.maxlen < biglen) {
1180 ssh->pktout.maxlen = biglen;
8f203108 1181#ifdef MSCRYPTOAPI
fb09bf1c 1182 /* Allocate enough buffer space for extra block
8f203108 1183 * for MS CryptEncrypt() */
3d88e64d 1184 ssh->pktout.data = sresize(ssh->pktout.data, biglen + 12,
1185 unsigned char);
8f203108 1186#else
3d88e64d 1187 ssh->pktout.data = sresize(ssh->pktout.data, biglen + 4,
1188 unsigned char);
8f203108 1189#endif
374330e2 1190 }
51470298 1191 ssh->pktout.body = ssh->pktout.data + 4 + pad + 1;
4ba9b64b 1192}
374330e2 1193
51470298 1194static void s_wrpkt_start(Ssh ssh, int type, int len)
32874aea 1195{
51470298 1196 ssh1_pktout_size(ssh, len);
1197 ssh->pktout.type = type;
374330e2 1198}
1199
51470298 1200static int s_wrpkt_prepare(Ssh ssh)
32874aea 1201{
fd7a4aad 1202 int pad, biglen, i;
374330e2 1203 unsigned long crc;
fd7a4aad 1204#ifdef __SC__
1205 /*
1206 * XXX various versions of SC (including 8.8.4) screw up the
1207 * register allocation in this function and use the same register
1208 * (D6) for len and as a temporary, with predictable results. The
1209 * following sledgehammer prevents this.
1210 */
1211 volatile
1212#endif
1213 int len;
374330e2 1214
51470298 1215 ssh->pktout.body[-1] = ssh->pktout.type;
4ba9b64b 1216
a8327734 1217 if (ssh->logctx)
1218 log_packet(ssh->logctx, PKT_OUTGOING, ssh->pktout.type,
1219 ssh1_pkt_type(ssh->pktout.type),
1220 ssh->pktout.body, ssh->pktout.length);
00db133f 1221
51470298 1222 if (ssh->v1_compressing) {
4ba9b64b 1223 unsigned char *compblk;
1224 int complen;
5366aed8 1225 zlib_compress_block(ssh->cs_comp_ctx,
1226 ssh->pktout.body - 1, ssh->pktout.length + 1,
4ba9b64b 1227 &compblk, &complen);
51470298 1228 ssh1_pktout_size(ssh, complen - 1);
1229 memcpy(ssh->pktout.body - 1, compblk, complen);
dcbde236 1230 sfree(compblk);
4ba9b64b 1231 }
1232
51470298 1233 len = ssh->pktout.length + 5; /* type and CRC */
32874aea 1234 pad = 8 - (len % 8);
374330e2 1235 biglen = len + pad;
1236
32874aea 1237 for (i = 0; i < pad; i++)
51470298 1238 ssh->pktout.data[i + 4] = random_byte();
1239 crc = crc32(ssh->pktout.data + 4, biglen - 4);
1240 PUT_32BIT(ssh->pktout.data + biglen, crc);
1241 PUT_32BIT(ssh->pktout.data, len);
374330e2 1242
51470298 1243 if (ssh->cipher)
371e569c 1244 ssh->cipher->encrypt(ssh->v1_cipher_ctx, ssh->pktout.data + 4, biglen);
374330e2 1245
32874aea 1246 return biglen + 4;
39065bed 1247}
1248
51470298 1249static void s_wrpkt(Ssh ssh)
32874aea 1250{
5471d09a 1251 int len, backlog;
51470298 1252 len = s_wrpkt_prepare(ssh);
d8baa528 1253 backlog = sk_write(ssh->s, (char *)ssh->pktout.data, len);
5471d09a 1254 if (backlog > SSH_MAX_BACKLOG)
51470298 1255 ssh_throttle_all(ssh, 1, backlog);
39065bed 1256}
1257
51470298 1258static void s_wrpkt_defer(Ssh ssh)
32874aea 1259{
39065bed 1260 int len;
51470298 1261 len = s_wrpkt_prepare(ssh);
1262 if (ssh->deferred_len + len > ssh->deferred_size) {
1263 ssh->deferred_size = ssh->deferred_len + len + 128;
3d88e64d 1264 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1265 ssh->deferred_size,
1266 unsigned char);
39065bed 1267 }
51470298 1268 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1269 ssh->deferred_len += len;
374330e2 1270}
1271
fb09bf1c 1272/*
39065bed 1273 * Construct a packet with the specified contents.
fb09bf1c 1274 */
51470298 1275static void construct_packet(Ssh ssh, int pkttype, va_list ap1, va_list ap2)
fb09bf1c 1276{
fb09bf1c 1277 unsigned char *p, *argp, argchar;
1278 unsigned long argint;
1279 int pktlen, argtype, arglen;
7cca0d81 1280 Bignum bn;
fb09bf1c 1281
1282 pktlen = 0;
39065bed 1283 while ((argtype = va_arg(ap1, int)) != PKT_END) {
fb09bf1c 1284 switch (argtype) {
1285 case PKT_INT:
39065bed 1286 (void) va_arg(ap1, int);
fb09bf1c 1287 pktlen += 4;
1288 break;
1289 case PKT_CHAR:
1ec39246 1290 (void) va_arg(ap1, int);
fb09bf1c 1291 pktlen++;
1292 break;
1293 case PKT_DATA:
39065bed 1294 (void) va_arg(ap1, unsigned char *);
1295 arglen = va_arg(ap1, int);
fb09bf1c 1296 pktlen += arglen;
1297 break;
1298 case PKT_STR:
39065bed 1299 argp = va_arg(ap1, unsigned char *);
d8baa528 1300 arglen = strlen((char *)argp);
fb09bf1c 1301 pktlen += 4 + arglen;
1302 break;
7cca0d81 1303 case PKT_BIGNUM:
39065bed 1304 bn = va_arg(ap1, Bignum);
32874aea 1305 pktlen += ssh1_bignum_length(bn);
7cca0d81 1306 break;
fb09bf1c 1307 default:
1308 assert(0);
1309 }
1310 }
fb09bf1c 1311
51470298 1312 s_wrpkt_start(ssh, pkttype, pktlen);
1313 p = ssh->pktout.body;
fb09bf1c 1314
39065bed 1315 while ((argtype = va_arg(ap2, int)) != PKT_END) {
fb09bf1c 1316 switch (argtype) {
1317 case PKT_INT:
39065bed 1318 argint = va_arg(ap2, int);
fb09bf1c 1319 PUT_32BIT(p, argint);
1320 p += 4;
1321 break;
1322 case PKT_CHAR:
1ec39246 1323 argchar = (unsigned char) va_arg(ap2, int);
fb09bf1c 1324 *p = argchar;
1325 p++;
1326 break;
1327 case PKT_DATA:
39065bed 1328 argp = va_arg(ap2, unsigned char *);
1329 arglen = va_arg(ap2, int);
fb09bf1c 1330 memcpy(p, argp, arglen);
1331 p += arglen;
1332 break;
1333 case PKT_STR:
39065bed 1334 argp = va_arg(ap2, unsigned char *);
d8baa528 1335 arglen = strlen((char *)argp);
fb09bf1c 1336 PUT_32BIT(p, arglen);
1337 memcpy(p + 4, argp, arglen);
1338 p += 4 + arglen;
1339 break;
7cca0d81 1340 case PKT_BIGNUM:
39065bed 1341 bn = va_arg(ap2, Bignum);
32874aea 1342 p += ssh1_write_bignum(p, bn);
7cca0d81 1343 break;
fb09bf1c 1344 }
1345 }
39065bed 1346}
fb09bf1c 1347
51470298 1348static void send_packet(Ssh ssh, int pkttype, ...)
32874aea 1349{
39065bed 1350 va_list ap1, ap2;
1351 va_start(ap1, pkttype);
1352 va_start(ap2, pkttype);
51470298 1353 construct_packet(ssh, pkttype, ap1, ap2);
1354 s_wrpkt(ssh);
fb09bf1c 1355}
1356
51470298 1357static void defer_packet(Ssh ssh, int pkttype, ...)
32874aea 1358{
39065bed 1359 va_list ap1, ap2;
1360 va_start(ap1, pkttype);
1361 va_start(ap2, pkttype);
51470298 1362 construct_packet(ssh, pkttype, ap1, ap2);
1363 s_wrpkt_defer(ssh);
39065bed 1364}
1365
32874aea 1366static int ssh_versioncmp(char *a, char *b)
1367{
9697bfd2 1368 char *ae, *be;
1369 unsigned long av, bv;
1370
43aa02a7 1371 av = strtoul(a, &ae, 10);
1372 bv = strtoul(b, &be, 10);
32874aea 1373 if (av != bv)
1374 return (av < bv ? -1 : +1);
1375 if (*ae == '.')
1376 ae++;
1377 if (*be == '.')
1378 be++;
43aa02a7 1379 av = strtoul(ae, &ae, 10);
1380 bv = strtoul(be, &be, 10);
32874aea 1381 if (av != bv)
1382 return (av < bv ? -1 : +1);
9697bfd2 1383 return 0;
1384}
1385
e5574168 1386/*
a92dd380 1387 * Utility routines for putting an SSH-protocol `string' and
1388 * `uint32' into a SHA state.
e5574168 1389 */
1390#include <stdio.h>
32874aea 1391static void sha_string(SHA_State * s, void *str, int len)
1392{
e5574168 1393 unsigned char lenblk[4];
e5574168 1394 PUT_32BIT(lenblk, len);
e5574168 1395 SHA_Bytes(s, lenblk, 4);
e5574168 1396 SHA_Bytes(s, str, len);
1397}
1398
32874aea 1399static void sha_uint32(SHA_State * s, unsigned i)
1400{
a92dd380 1401 unsigned char intblk[4];
1402 PUT_32BIT(intblk, i);
1403 SHA_Bytes(s, intblk, 4);
1404}
1405
7cca0d81 1406/*
1407 * SSH2 packet construction functions.
1408 */
51470298 1409static void ssh2_pkt_ensure(Ssh ssh, int length)
32874aea 1410{
51470298 1411 if (ssh->pktout.maxlen < length) {
1412 ssh->pktout.maxlen = length + 256;
3d88e64d 1413 ssh->pktout.data = sresize(ssh->pktout.data,
1414 ssh->pktout.maxlen + APIEXTRA,
1415 unsigned char);
51470298 1416 if (!ssh->pktout.data)
32874aea 1417 fatalbox("Out of memory");
7cca0d81 1418 }
783415f8 1419}
51470298 1420static void ssh2_pkt_adddata(Ssh ssh, void *data, int len)
32874aea 1421{
51470298 1422 ssh->pktout.length += len;
1423 ssh2_pkt_ensure(ssh, ssh->pktout.length);
1424 memcpy(ssh->pktout.data + ssh->pktout.length - len, data, len);
7cca0d81 1425}
51470298 1426static void ssh2_pkt_addbyte(Ssh ssh, unsigned char byte)
32874aea 1427{
51470298 1428 ssh2_pkt_adddata(ssh, &byte, 1);
7cca0d81 1429}
51470298 1430static void ssh2_pkt_init(Ssh ssh, int pkt_type)
32874aea 1431{
51470298 1432 ssh->pktout.length = 5;
1433 ssh2_pkt_addbyte(ssh, (unsigned char) pkt_type);
7cca0d81 1434}
51470298 1435static void ssh2_pkt_addbool(Ssh ssh, unsigned char value)
32874aea 1436{
51470298 1437 ssh2_pkt_adddata(ssh, &value, 1);
7cca0d81 1438}
51470298 1439static void ssh2_pkt_adduint32(Ssh ssh, unsigned long value)
32874aea 1440{
7cca0d81 1441 unsigned char x[4];
1442 PUT_32BIT(x, value);
51470298 1443 ssh2_pkt_adddata(ssh, x, 4);
7cca0d81 1444}
51470298 1445static void ssh2_pkt_addstring_start(Ssh ssh)
32874aea 1446{
51470298 1447 ssh2_pkt_adduint32(ssh, 0);
1448 ssh->pktout.savedpos = ssh->pktout.length;
7cca0d81 1449}
51470298 1450static void ssh2_pkt_addstring_str(Ssh ssh, char *data)
32874aea 1451{
51470298 1452 ssh2_pkt_adddata(ssh, data, strlen(data));
1453 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1454 ssh->pktout.length - ssh->pktout.savedpos);
7cca0d81 1455}
51470298 1456static void ssh2_pkt_addstring_data(Ssh ssh, char *data, int len)
32874aea 1457{
51470298 1458 ssh2_pkt_adddata(ssh, data, len);
1459 PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
1460 ssh->pktout.length - ssh->pktout.savedpos);
7cca0d81 1461}
51470298 1462static void ssh2_pkt_addstring(Ssh ssh, char *data)
32874aea 1463{
51470298 1464 ssh2_pkt_addstring_start(ssh);
1465 ssh2_pkt_addstring_str(ssh, data);
7cca0d81 1466}
d8baa528 1467static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
32874aea 1468{
7cca0d81 1469 unsigned char *p;
32874aea 1470 int i, n = (bignum_bitcount(b) + 7) / 8;
3d88e64d 1471 p = snewn(n + 1, unsigned char);
7cca0d81 1472 if (!p)
32874aea 1473 fatalbox("out of memory");
7cca0d81 1474 p[0] = 0;
3709bfe9 1475 for (i = 1; i <= n; i++)
32874aea 1476 p[i] = bignum_byte(b, n - i);
7cca0d81 1477 i = 0;
32874aea 1478 while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
1479 i++;
1480 memmove(p, p + i, n + 1 - i);
1481 *len = n + 1 - i;
7cca0d81 1482 return p;
1483}
51470298 1484static void ssh2_pkt_addmp(Ssh ssh, Bignum b)
32874aea 1485{
7cca0d81 1486 unsigned char *p;
1487 int len;
1488 p = ssh2_mpint_fmt(b, &len);
51470298 1489 ssh2_pkt_addstring_start(ssh);
d8baa528 1490 ssh2_pkt_addstring_data(ssh, (char *)p, len);
dcbde236 1491 sfree(p);
7cca0d81 1492}
b185170a 1493
1494/*
1495 * Construct an SSH2 final-form packet: compress it, encrypt it,
1496 * put the MAC on it. Final packet, ready to be sent, is stored in
51470298 1497 * ssh->pktout.data. Total length is returned.
b185170a 1498 */
51470298 1499static int ssh2_pkt_construct(Ssh ssh)
32874aea 1500{
7cca0d81 1501 int cipherblk, maclen, padding, i;
7cca0d81 1502
a8327734 1503 if (ssh->logctx)
1504 log_packet(ssh->logctx, PKT_OUTGOING, ssh->pktout.data[5],
1505 ssh2_pkt_type(ssh->pkt_ctx, ssh->pktout.data[5]),
1506 ssh->pktout.data + 6, ssh->pktout.length - 6);
00db133f 1507
7cca0d81 1508 /*
4ba9b64b 1509 * Compress packet payload.
1510 */
4ba9b64b 1511 {
1512 unsigned char *newpayload;
1513 int newlen;
51470298 1514 if (ssh->cscomp &&
5366aed8 1515 ssh->cscomp->compress(ssh->cs_comp_ctx, ssh->pktout.data + 5,
1516 ssh->pktout.length - 5,
51470298 1517 &newpayload, &newlen)) {
1518 ssh->pktout.length = 5;
1519 ssh2_pkt_adddata(ssh, newpayload, newlen);
dcbde236 1520 sfree(newpayload);
4ba9b64b 1521 }
1522 }
1523
1524 /*
7cca0d81 1525 * Add padding. At least four bytes, and must also bring total
1526 * length (minus MAC) up to a multiple of the block size.
1527 */
51470298 1528 cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
32874aea 1529 cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
7cca0d81 1530 padding = 4;
32874aea 1531 padding +=
51470298 1532 (cipherblk - (ssh->pktout.length + padding) % cipherblk) % cipherblk;
1533 maclen = ssh->csmac ? ssh->csmac->len : 0;
1534 ssh2_pkt_ensure(ssh, ssh->pktout.length + padding + maclen);
1535 ssh->pktout.data[4] = padding;
7cca0d81 1536 for (i = 0; i < padding; i++)
51470298 1537 ssh->pktout.data[ssh->pktout.length + i] = random_byte();
1538 PUT_32BIT(ssh->pktout.data, ssh->pktout.length + padding - 4);
1539 if (ssh->csmac)
e0e1a00d 1540 ssh->csmac->generate(ssh->cs_mac_ctx, ssh->pktout.data,
1541 ssh->pktout.length + padding,
51470298 1542 ssh->v2_outgoing_sequence);
1543 ssh->v2_outgoing_sequence++; /* whether or not we MACed */
1544
1545 if (ssh->cscipher)
371e569c 1546 ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
1547 ssh->pktout.data, ssh->pktout.length + padding);
51470298 1548
1549 /* Ready-to-send packet starts at ssh->pktout.data. We return length. */
1550 return ssh->pktout.length + padding + maclen;
b185170a 1551}
1552
1553/*
1554 * Construct and send an SSH2 packet immediately.
1555 */
51470298 1556static void ssh2_pkt_send(Ssh ssh)
32874aea 1557{
5471d09a 1558 int len;
1559 int backlog;
51470298 1560 len = ssh2_pkt_construct(ssh);
d8baa528 1561 backlog = sk_write(ssh->s, (char *)ssh->pktout.data, len);
5471d09a 1562 if (backlog > SSH_MAX_BACKLOG)
51470298 1563 ssh_throttle_all(ssh, 1, backlog);
b185170a 1564}
1565
1566/*
1567 * Construct an SSH2 packet and add it to a deferred data block.
1568 * Useful for sending multiple packets in a single sk_write() call,
1569 * to prevent a traffic-analysing listener from being able to work
1570 * out the length of any particular packet (such as the password
1571 * packet).
1572 *
1573 * Note that because SSH2 sequence-numbers its packets, this can
1574 * NOT be used as an m4-style `defer' allowing packets to be
1575 * constructed in one order and sent in another.
1576 */
51470298 1577static void ssh2_pkt_defer(Ssh ssh)
32874aea 1578{
51470298 1579 int len = ssh2_pkt_construct(ssh);
1580 if (ssh->deferred_len + len > ssh->deferred_size) {
1581 ssh->deferred_size = ssh->deferred_len + len + 128;
3d88e64d 1582 ssh->deferred_send_data = sresize(ssh->deferred_send_data,
1583 ssh->deferred_size,
1584 unsigned char);
b185170a 1585 }
51470298 1586 memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
1587 ssh->deferred_len += len;
b185170a 1588}
1589
1590/*
1591 * Send the whole deferred data block constructed by
39065bed 1592 * ssh2_pkt_defer() or SSH1's defer_packet().
b185170a 1593 */
51470298 1594static void ssh_pkt_defersend(Ssh ssh)
32874aea 1595{
5471d09a 1596 int backlog;
d8baa528 1597 backlog = sk_write(ssh->s, (char *)ssh->deferred_send_data,
1598 ssh->deferred_len);
51470298 1599 ssh->deferred_len = ssh->deferred_size = 0;
1600 sfree(ssh->deferred_send_data);
1601 ssh->deferred_send_data = NULL;
5471d09a 1602 if (backlog > SSH_MAX_BACKLOG)
51470298 1603 ssh_throttle_all(ssh, 1, backlog);
7cca0d81 1604}
1605
1606#if 0
32874aea 1607void bndebug(char *string, Bignum b)
1608{
7cca0d81 1609 unsigned char *p;
1610 int i, len;
1611 p = ssh2_mpint_fmt(b, &len);
1612 debug(("%s", string));
1613 for (i = 0; i < len; i++)
32874aea 1614 debug((" %02x", p[i]));
765c4200 1615 debug(("\n"));
dcbde236 1616 sfree(p);
7cca0d81 1617}
1618#endif
1619
32874aea 1620static void sha_mpint(SHA_State * s, Bignum b)
1621{
7cca0d81 1622 unsigned char *p;
1623 int len;
1624 p = ssh2_mpint_fmt(b, &len);
1625 sha_string(s, p, len);
dcbde236 1626 sfree(p);
7cca0d81 1627}
1628
1629/*
1630 * SSH2 packet decode functions.
1631 */
51470298 1632static unsigned long ssh2_pkt_getuint32(Ssh ssh)
32874aea 1633{
7cca0d81 1634 unsigned long value;
51470298 1635 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
32874aea 1636 return 0; /* arrgh, no way to decline (FIXME?) */
51470298 1637 value = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1638 ssh->pktin.savedpos += 4;
7cca0d81 1639 return value;
1640}
51470298 1641static int ssh2_pkt_getbool(Ssh ssh)
32874aea 1642{
65a22376 1643 unsigned long value;
51470298 1644 if (ssh->pktin.length - ssh->pktin.savedpos < 1)
32874aea 1645 return 0; /* arrgh, no way to decline (FIXME?) */
51470298 1646 value = ssh->pktin.data[ssh->pktin.savedpos] != 0;
1647 ssh->pktin.savedpos++;
65a22376 1648 return value;
1649}
51470298 1650static void ssh2_pkt_getstring(Ssh ssh, char **p, int *length)
32874aea 1651{
57356d63 1652 int len;
7cca0d81 1653 *p = NULL;
45068b27 1654 *length = 0;
51470298 1655 if (ssh->pktin.length - ssh->pktin.savedpos < 4)
32874aea 1656 return;
57356d63 1657 len = GET_32BIT(ssh->pktin.data + ssh->pktin.savedpos);
1658 if (len < 0)
1659 return;
1660 *length = len;
51470298 1661 ssh->pktin.savedpos += 4;
1662 if (ssh->pktin.length - ssh->pktin.savedpos < *length)
32874aea 1663 return;
d8baa528 1664 *p = (char *)(ssh->pktin.data + ssh->pktin.savedpos);
51470298 1665 ssh->pktin.savedpos += *length;
7cca0d81 1666}
51470298 1667static Bignum ssh2_pkt_getmp(Ssh ssh)
32874aea 1668{
7cca0d81 1669 char *p;
3709bfe9 1670 int length;
7cca0d81 1671 Bignum b;
1672
51470298 1673 ssh2_pkt_getstring(ssh, &p, &length);
7cca0d81 1674 if (!p)
32874aea 1675 return NULL;
8d5de777 1676 if (p[0] & 0x80) {
6b5cf8b4 1677 bombout(("internal error: Can't handle negative mpints"));
32874aea 1678 return NULL;
8d5de777 1679 }
d8baa528 1680 b = bignum_from_bytes((unsigned char *)p, length);
7cca0d81 1681 return b;
1682}
1683
7d503c31 1684/*
1dd353b5 1685 * Helper function to add an SSH2 signature blob to a packet.
1686 * Expects to be shown the public key blob as well as the signature
1687 * blob. Normally works just like ssh2_pkt_addstring, but will
1688 * fiddle with the signature packet if necessary for
1689 * BUG_SSH2_RSA_PADDING.
1690 */
51470298 1691static void ssh2_add_sigblob(Ssh ssh, void *pkblob_v, int pkblob_len,
1dd353b5 1692 void *sigblob_v, int sigblob_len)
1693{
1694 unsigned char *pkblob = (unsigned char *)pkblob_v;
1695 unsigned char *sigblob = (unsigned char *)sigblob_v;
1696
1697 /* dmemdump(pkblob, pkblob_len); */
1698 /* dmemdump(sigblob, sigblob_len); */
1699
1700 /*
1701 * See if this is in fact an ssh-rsa signature and a buggy
1702 * server; otherwise we can just do this the easy way.
1703 */
51470298 1704 if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
1dd353b5 1705 (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
1706 int pos, len, siglen;
1707
1708 /*
1709 * Find the byte length of the modulus.
1710 */
1711
1712 pos = 4+7; /* skip over "ssh-rsa" */
1713 pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
1714 len = GET_32BIT(pkblob+pos); /* find length of modulus */
1715 pos += 4; /* find modulus itself */
1716 while (len > 0 && pkblob[pos] == 0)
1717 len--, pos++;
1718 /* debug(("modulus length is %d\n", len)); */
1719
1720 /*
1721 * Now find the signature integer.
1722 */
1723 pos = 4+7; /* skip over "ssh-rsa" */
1724 siglen = GET_32BIT(sigblob+pos);
1725 /* debug(("signature length is %d\n", siglen)); */
1726
1727 if (len != siglen) {
1728 unsigned char newlen[4];
51470298 1729 ssh2_pkt_addstring_start(ssh);
d8baa528 1730 ssh2_pkt_addstring_data(ssh, (char *)sigblob, pos);
1dd353b5 1731 /* dmemdump(sigblob, pos); */
1732 pos += 4; /* point to start of actual sig */
1733 PUT_32BIT(newlen, len);
d8baa528 1734 ssh2_pkt_addstring_data(ssh, (char *)newlen, 4);
1dd353b5 1735 /* dmemdump(newlen, 4); */
1736 newlen[0] = 0;
1737 while (len-- > siglen) {
d8baa528 1738 ssh2_pkt_addstring_data(ssh, (char *)newlen, 1);
1dd353b5 1739 /* dmemdump(newlen, 1); */
1740 }
d8baa528 1741 ssh2_pkt_addstring_data(ssh, (char *)(sigblob+pos), siglen);
1dd353b5 1742 /* dmemdump(sigblob+pos, siglen); */
1743 return;
1744 }
1745
1746 /* Otherwise fall through and do it the easy way. */
1747 }
1748
51470298 1749 ssh2_pkt_addstring_start(ssh);
d8baa528 1750 ssh2_pkt_addstring_data(ssh, (char *)sigblob, sigblob_len);
1dd353b5 1751}
1752
1753/*
7d503c31 1754 * Examine the remote side's version string and compare it against
1755 * a list of known buggy implementations.
1756 */
51470298 1757static void ssh_detect_bugs(Ssh ssh, char *vstring)
32874aea 1758{
1759 char *imp; /* pointer to implementation part */
7d503c31 1760 imp = vstring;
1761 imp += strcspn(imp, "-");
bd358db1 1762 if (*imp) imp++;
7d503c31 1763 imp += strcspn(imp, "-");
bd358db1 1764 if (*imp) imp++;
7d503c31 1765
51470298 1766 ssh->remote_bugs = 0;
7d503c31 1767
5ecd7ad0 1768 if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
1769 (ssh->cfg.sshbug_ignore1 == AUTO &&
2c9c6388 1770 (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
1771 !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
1772 !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25")))) {
32874aea 1773 /*
1774 * These versions don't support SSH1_MSG_IGNORE, so we have
1775 * to use a different defence against password length
1776 * sniffing.
1777 */
51470298 1778 ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
32874aea 1779 logevent("We believe remote version has SSH1 ignore bug");
7d503c31 1780 }
1781
5ecd7ad0 1782 if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
1783 (ssh->cfg.sshbug_plainpw1 == AUTO &&
2c9c6388 1784 (!strcmp(imp, "Cisco-1.25")))) {
bd358db1 1785 /*
1786 * These versions need a plain password sent; they can't
1787 * handle having a null and a random length of data after
1788 * the password.
1789 */
51470298 1790 ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
bd358db1 1791 logevent("We believe remote version needs a plain SSH1 password");
1792 }
1793
5ecd7ad0 1794 if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
1795 (ssh->cfg.sshbug_rsa1 == AUTO &&
2c9c6388 1796 (!strcmp(imp, "Cisco-1.25")))) {
0df73905 1797 /*
1798 * These versions apparently have no clue whatever about
1799 * RSA authentication and will panic and die if they see
1800 * an AUTH_RSA message.
1801 */
51470298 1802 ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
0df73905 1803 logevent("We believe remote version can't handle RSA authentication");
1804 }
1805
5ecd7ad0 1806 if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
1807 (ssh->cfg.sshbug_hmac2 == AUTO &&
831301f6 1808 (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
1809 wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
1810 wc_match("2.1 *", imp)))) {
32874aea 1811 /*
1812 * These versions have the HMAC bug.
1813 */
51470298 1814 ssh->remote_bugs |= BUG_SSH2_HMAC;
32874aea 1815 logevent("We believe remote version has SSH2 HMAC bug");
7d503c31 1816 }
1dd353b5 1817
5ecd7ad0 1818 if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
1819 (ssh->cfg.sshbug_derivekey2 == AUTO &&
2856a1b9 1820 (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
088bde77 1821 /*
1822 * These versions have the key-derivation bug (failing to
1823 * include the literal shared secret in the hashes that
1824 * generate the keys).
1825 */
51470298 1826 ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
088bde77 1827 logevent("We believe remote version has SSH2 key-derivation bug");
1828 }
1829
5ecd7ad0 1830 if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
1831 (ssh->cfg.sshbug_rsapad2 == AUTO &&
831301f6 1832 (wc_match("OpenSSH_2.[5-9]*", imp) ||
1833 wc_match("OpenSSH_3.[0-2]*", imp)))) {
1dd353b5 1834 /*
1835 * These versions have the SSH2 RSA padding bug.
1836 */
51470298 1837 ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
1dd353b5 1838 logevent("We believe remote version has SSH2 RSA padding bug");
1839 }
8e975795 1840
dda87a28 1841 if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
1842 (ssh->cfg.sshbug_pksessid2 == AUTO &&
1843 wc_match("OpenSSH_2.[0-2]*", imp))) {
1844 /*
1845 * These versions have the SSH2 session-ID bug in
1846 * public-key authentication.
1847 */
1848 ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
1849 logevent("We believe remote version has SSH2 public-key-session-ID bug");
1850 }
1851
5ecd7ad0 1852 if (ssh->cfg.sshbug_dhgex2 == FORCE_ON) {
8e975795 1853 /*
831301f6 1854 * User specified the SSH2 DH GEX bug.
8e975795 1855 */
51470298 1856 ssh->remote_bugs |= BUG_SSH2_DH_GEX;
8e975795 1857 logevent("We believe remote version has SSH2 DH group exchange bug");
1858 }
7d503c31 1859}
1860
51470298 1861static int do_ssh_init(Ssh ssh, unsigned char c)
32874aea 1862{
51470298 1863 struct do_ssh_init_state {
1864 int vslen;
1865 char version[10];
1866 char *vstring;
1867 int vstrsize;
1868 int i;
1869 int proto1, proto2;
1870 };
1871 crState(do_ssh_init_state);
374330e2 1872
51470298 1873 crBegin(ssh->do_ssh_init_crstate);
8df7a775 1874
1875 /* Search for the string "SSH-" in the input. */
51470298 1876 s->i = 0;
8df7a775 1877 while (1) {
1878 static const int transS[] = { 1, 2, 2, 1 };
1879 static const int transH[] = { 0, 0, 3, 0 };
1880 static const int transminus[] = { 0, 0, 0, -1 };
32874aea 1881 if (c == 'S')
51470298 1882 s->i = transS[s->i];
32874aea 1883 else if (c == 'H')
51470298 1884 s->i = transH[s->i];
32874aea 1885 else if (c == '-')
51470298 1886 s->i = transminus[s->i];
32874aea 1887 else
51470298 1888 s->i = 0;
1889 if (s->i < 0)
8df7a775 1890 break;
1891 crReturn(1); /* get another character */
374330e2 1892 }
8df7a775 1893
51470298 1894 s->vstrsize = 16;
3d88e64d 1895 s->vstring = snewn(s->vstrsize, char);
51470298 1896 strcpy(s->vstring, "SSH-");
1897 s->vslen = 4;
1898 s->i = 0;
374330e2 1899 while (1) {
8df7a775 1900 crReturn(1); /* get another char */
51470298 1901 if (s->vslen >= s->vstrsize - 1) {
1902 s->vstrsize += 16;
3d88e64d 1903 s->vstring = sresize(s->vstring, s->vstrsize, char);
32874aea 1904 }
51470298 1905 s->vstring[s->vslen++] = c;
1906 if (s->i >= 0) {
374330e2 1907 if (c == '-') {
51470298 1908 s->version[s->i] = '\0';
1909 s->i = -1;
1910 } else if (s->i < sizeof(s->version) - 1)
1911 s->version[s->i++] = c;
c4ffc4d0 1912 } else if (c == '\012')
374330e2 1913 break;
1914 }
1915
51470298 1916 ssh->agentfwd_enabled = FALSE;
1917 ssh->rdpkt2_state.incoming_sequence = 0;
960e736a 1918
51470298 1919 s->vstring[s->vslen] = 0;
1920 s->vstring[strcspn(s->vstring, "\r\n")] = '\0';/* remove EOL chars */
1921 {
1922 char *vlog;
3d88e64d 1923 vlog = snewn(20 + s->vslen, char);
51470298 1924 sprintf(vlog, "Server version: %s", s->vstring);
1925 logevent(vlog);
1926 sfree(vlog);
1927 }
1928 ssh_detect_bugs(ssh, s->vstring);
c5e9c988 1929
adf799dd 1930 /*
38d228a2 1931 * Decide which SSH protocol version to support.
adf799dd 1932 */
38d228a2 1933
1934 /* Anything strictly below "2.0" means protocol 1 is supported. */
51470298 1935 s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
38d228a2 1936 /* Anything greater or equal to "1.99" means protocol 2 is supported. */
51470298 1937 s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
38d228a2 1938
86916870 1939 if (ssh->cfg.sshprot == 0 && !s->proto1) {
6b5cf8b4 1940 bombout(("SSH protocol version 1 required by user but not provided by server"));
38d228a2 1941 crReturn(0);
1942 }
86916870 1943 if (ssh->cfg.sshprot == 3 && !s->proto2) {
6b5cf8b4 1944 bombout(("SSH protocol version 2 required by user but not provided by server"));
38d228a2 1945 crReturn(0);
1946 }
1947
86916870 1948 if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1)) {
32874aea 1949 /*
38d228a2 1950 * Use v2 protocol.
32874aea 1951 */
1952 char verstring[80], vlog[100];
1953 sprintf(verstring, "SSH-2.0-%s", sshver);
51470298 1954 SHA_Init(&ssh->exhashbase);
32874aea 1955 /*
1956 * Hash our version string and their version string.
1957 */
51470298 1958 sha_string(&ssh->exhashbase, verstring, strlen(verstring));
1959 sha_string(&ssh->exhashbase, s->vstring, strcspn(s->vstring, "\r\n"));
32874aea 1960 sprintf(vlog, "We claim version: %s", verstring);
1961 logevent(vlog);
c4ffc4d0 1962 strcat(verstring, "\012");
32874aea 1963 logevent("Using SSH protocol version 2");
51470298 1964 sk_write(ssh->s, verstring, strlen(verstring));
1965 ssh->protocol = ssh2_protocol;
1966 ssh->version = 2;
1967 ssh->s_rdpkt = ssh2_rdpkt;
e5574168 1968 } else {
32874aea 1969 /*
38d228a2 1970 * Use v1 protocol.
32874aea 1971 */
1972 char verstring[80], vlog[100];
1973 sprintf(verstring, "SSH-%s-%s",
51470298 1974 (ssh_versioncmp(s->version, "1.5") <= 0 ? s->version : "1.5"),
32874aea 1975 sshver);
1976 sprintf(vlog, "We claim version: %s", verstring);
1977 logevent(vlog);
c4ffc4d0 1978 strcat(verstring, "\012");
759712a6 1979
32874aea 1980 logevent("Using SSH protocol version 1");
51470298 1981 sk_write(ssh->s, verstring, strlen(verstring));
1982 ssh->protocol = ssh1_protocol;
1983 ssh->version = 1;
1984 ssh->s_rdpkt = ssh1_rdpkt;
e5574168 1985 }
125105d1 1986 update_specials_menu(ssh->frontend);
51470298 1987 ssh->state = SSH_STATE_BEFORE_SIZE;
8df7a775 1988
51470298 1989 sfree(s->vstring);
50526e47 1990
8df7a775 1991 crFinish(0);
1992}
1993
51470298 1994static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
8df7a775 1995{
51470298 1996 crBegin(ssh->ssh_gotdata_crstate);
8df7a775 1997
1998 /*
1999 * To begin with, feed the characters one by one to the
2000 * protocol initialisation / selection function do_ssh_init().
2001 * When that returns 0, we're done with the initial greeting
2002 * exchange and can move on to packet discipline.
2003 */
2004 while (1) {
51470298 2005 int ret; /* need not be kept across crReturn */
8df7a775 2006 if (datalen == 0)
2007 crReturnV; /* more data please */
51470298 2008 ret = do_ssh_init(ssh, *data);
32874aea 2009 data++;
2010 datalen--;
8df7a775 2011 if (ret == 0)
2012 break;
2013 }
2014
2015 /*
2016 * We emerge from that loop when the initial negotiation is
2017 * over and we have selected an s_rdpkt function. Now pass
2018 * everything to s_rdpkt, and then pass the resulting packets
2019 * to the proper protocol handler.
2020 */
2021 if (datalen == 0)
2022 crReturnV;
2023 while (1) {
2024 while (datalen > 0) {
51470298 2025 if (ssh->s_rdpkt(ssh, &data, &datalen) == 0) {
2026 if (ssh->state == SSH_STATE_CLOSED) {
e14d0f19 2027 return;
2028 }
51470298 2029 ssh->protocol(ssh, NULL, 0, 1);
2030 if (ssh->state == SSH_STATE_CLOSED) {
8df7a775 2031 return;
2032 }
2033 }
2034 }
2035 crReturnV;
2036 }
2037 crFinishV;
2038}
2039
32874aea 2040static int ssh_closing(Plug plug, char *error_msg, int error_code,
2041 int calling_back)
2042{
51470298 2043 Ssh ssh = (Ssh) plug;
2044 ssh->state = SSH_STATE_CLOSED;
2045 if (ssh->s) {
2046 sk_close(ssh->s);
2047 ssh->s = NULL;
f3ab576e 2048 }
7e78000d 2049 if (error_msg) {
32874aea 2050 /* A socket error has occurred. */
247308b5 2051 logevent(error_msg);
a8327734 2052 connection_fatal(ssh->frontend, error_msg);
7e78000d 2053 } else {
2054 /* Otherwise, the remote side closed the connection normally. */
8df7a775 2055 }
7e78000d 2056 return 0;
2057}
2058
32874aea 2059static int ssh_receive(Plug plug, int urgent, char *data, int len)
2060{
51470298 2061 Ssh ssh = (Ssh) plug;
d8baa528 2062 ssh_gotdata(ssh, (unsigned char *)data, len);
51470298 2063 if (ssh->state == SSH_STATE_CLOSED) {
2064 if (ssh->s) {
2065 sk_close(ssh->s);
2066 ssh->s = NULL;
32874aea 2067 }
2068 return 0;
3257deae 2069 }
fef97f43 2070 return 1;
374330e2 2071}
2072
5471d09a 2073static void ssh_sent(Plug plug, int bufsize)
2074{
51470298 2075 Ssh ssh = (Ssh) plug;
5471d09a 2076 /*
2077 * If the send backlog on the SSH socket itself clears, we
2078 * should unthrottle the whole world if it was throttled.
2079 */
2080 if (bufsize < SSH_MAX_BACKLOG)
51470298 2081 ssh_throttle_all(ssh, 0, bufsize);
5471d09a 2082}
2083
fb09bf1c 2084/*
8df7a775 2085 * Connect to specified host and port.
2086 * Returns an error message, or NULL on success.
6e1ebb76 2087 * Also places the canonical host name into `realhost'. It must be
2088 * freed by the caller.
8df7a775 2089 */
51470298 2090static char *connect_to_host(Ssh ssh, char *host, int port,
2091 char **realhost, int nodelay)
8df7a775 2092{
51470298 2093 static const struct plug_function_table fn_table = {
7e78000d 2094 ssh_closing,
5471d09a 2095 ssh_receive,
2096 ssh_sent,
2097 NULL
51470298 2098 };
7e78000d 2099
8df7a775 2100 SockAddr addr;
2101 char *err;
8df7a775 2102
3d88e64d 2103 ssh->savedhost = snewn(1 + strlen(host), char);
51470298 2104 if (!ssh->savedhost)
8df7a775 2105 fatalbox("Out of memory");
51470298 2106 strcpy(ssh->savedhost, host);
8df7a775 2107
2108 if (port < 0)
2109 port = 22; /* default ssh port */
51470298 2110 ssh->savedport = port;
8df7a775 2111
2112 /*
2113 * Try to find host.
2114 */
57356d63 2115 logeventf(ssh, "Looking up host \"%s\"", host);
e8fa8f62 2116 addr = name_lookup(host, port, realhost, &ssh->cfg);
70e5d0fd 2117 if ((err = sk_addr_error(addr)) != NULL)
8df7a775 2118 return err;
2119
8df7a775 2120 /*
2121 * Open socket.
2122 */
3ad9d396 2123 {
57356d63 2124 char addrbuf[100];
3ad9d396 2125 sk_getaddr(addr, addrbuf, 100);
57356d63 2126 logeventf(ssh, "Connecting to %s port %d", addrbuf, port);
3ad9d396 2127 }
51470298 2128 ssh->fn = &fn_table;
e8fa8f62 2129 ssh->s = new_connection(addr, *realhost, port,
2130 0, 1, nodelay, (Plug) ssh, &ssh->cfg);
70e5d0fd 2131 if ((err = sk_socket_error(ssh->s)) != NULL) {
51470298 2132 ssh->s = NULL;
8df7a775 2133 return err;
67c4ba2e 2134 }
8df7a775 2135
8df7a775 2136 return NULL;
2137}
2138
2139/*
5471d09a 2140 * Throttle or unthrottle the SSH connection.
2141 */
51470298 2142static void ssh1_throttle(Ssh ssh, int adjust)
5471d09a 2143{
51470298 2144 int old_count = ssh->v1_throttle_count;
2145 ssh->v1_throttle_count += adjust;
2146 assert(ssh->v1_throttle_count >= 0);
2147 if (ssh->v1_throttle_count && !old_count) {
2148 sk_set_frozen(ssh->s, 1);
2149 } else if (!ssh->v1_throttle_count && old_count) {
2150 sk_set_frozen(ssh->s, 0);
5471d09a 2151 }
2152}
2153
2154/*
2155 * Throttle or unthrottle _all_ local data streams (for when sends
2156 * on the SSH connection itself back up).
2157 */
51470298 2158static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
5471d09a 2159{
2160 int i;
2161 struct ssh_channel *c;
2162
51470298 2163 if (enable == ssh->throttled_all)
5471d09a 2164 return;
51470298 2165 ssh->throttled_all = enable;
2166 ssh->overall_bufsize = bufsize;
2167 if (!ssh->channels)
5471d09a 2168 return;
51470298 2169 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
5471d09a 2170 switch (c->type) {
2171 case CHAN_MAINSESSION:
2172 /*
2173 * This is treated separately, outside the switch.
2174 */
2175 break;
2176 case CHAN_X11:
2177 x11_override_throttle(c->u.x11.s, enable);
2178 break;
2179 case CHAN_AGENT:
2180 /* Agent channels require no buffer management. */
2181 break;
2182 case CHAN_SOCKDATA:
2183 pfd_override_throttle(c->u.x11.s, enable);
2184 break;
2185 }
2186 }
2187}
2188
2189/*
51470298 2190 * Username and password input, abstracted off into routines
2191 * reusable in several places - even between SSH1 and SSH2.
0405e71f 2192 */
0405e71f 2193
2194/* Set up a username or password input loop on a given buffer. */
ae9ae89f 2195static void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
0405e71f 2196{
51470298 2197 ssh->userpass_input_buffer = buffer;
2198 ssh->userpass_input_buflen = buflen;
2199 ssh->userpass_input_bufpos = 0;
2200 ssh->userpass_input_echo = echo;
0405e71f 2201}
2202
2203/*
2204 * Process some terminal data in the course of username/password
2205 * input. Returns >0 for success (line of input returned in
2206 * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
2207 * for inconclusive (keep waiting for more input please).
2208 */
ae9ae89f 2209static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
0405e71f 2210{
2211 char c;
2212
2213 while (inlen--) {
2214 switch (c = *in++) {
2215 case 10:
2216 case 13:
51470298 2217 ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
2218 ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
0405e71f 2219 return +1;
2220 break;
2221 case 8:
2222 case 127:
51470298 2223 if (ssh->userpass_input_bufpos > 0) {
2224 if (ssh->userpass_input_echo)
2225 c_write_str(ssh, "\b \b");
2226 ssh->userpass_input_bufpos--;
0405e71f 2227 }
2228 break;
2229 case 21:
2230 case 27:
51470298 2231 while (ssh->userpass_input_bufpos > 0) {
2232 if (ssh->userpass_input_echo)
2233 c_write_str(ssh, "\b \b");
2234 ssh->userpass_input_bufpos--;
0405e71f 2235 }
2236 break;
2237 case 3:
2238 case 4:
2239 return -1;
2240 break;
2241 default:
4692a14a 2242 /*
2243 * This simplistic check for printability is disabled
2244 * when we're doing password input, because some people
2245 * have control characters in their passwords.o
2246 */
2247 if ((!ssh->userpass_input_echo ||
2248 (c >= ' ' && c <= '~') ||
0405e71f 2249 ((unsigned char) c >= 160))
51470298 2250 && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
2251 ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
2252 if (ssh->userpass_input_echo)
2253 c_write(ssh, &c, 1);
0405e71f 2254 }
2255 break;
2256 }
2257 }
2258 return 0;
2259}
2260
2261/*
fb09bf1c 2262 * Handle the key exchange and user authentication phases.
2263 */
51470298 2264static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
fb09bf1c 2265{
2d466ffd 2266 int i, j;
374330e2 2267 unsigned char cookie[8];
2268 struct RSAKey servkey, hostkey;
2269 struct MD5Context md5c;
51470298 2270 struct do_ssh1_login_state {
2271 int len;
2272 unsigned char *rsabuf, *keystr1, *keystr2;
2273 unsigned long supported_ciphers_mask, supported_auths_mask;
2274 int tried_publickey, tried_agent;
2275 int tis_auth_refused, ccard_auth_refused;
2276 unsigned char session_id[16];
2277 int cipher_type;
2278 char username[100];
2279 void *publickey_blob;
2280 int publickey_bloblen;
2281 char password[100];
2282 char prompt[200];
2283 int pos;
2284 char c;
2285 int pwpkt_type;
2286 unsigned char request[5], *response, *p;
2287 int responselen;
2288 int keyi, nkeys;
2289 int authed;
2290 struct RSAKey key;
2291 Bignum challenge;
2292 char *commentp;
2293 int commentlen;
2294 };
2295 crState(do_ssh1_login_state);
2296
2297 crBegin(ssh->do_ssh1_login_crstate);
374330e2 2298
32874aea 2299 if (!ispkt)
2300 crWaitUntil(ispkt);
374330e2 2301
51470298 2302 if (ssh->pktin.type != SSH1_SMSG_PUBLIC_KEY) {
6b5cf8b4 2303 bombout(("Public key packet not received"));
32874aea 2304 crReturn(0);
8d5de777 2305 }
374330e2 2306
c5e9c988 2307 logevent("Received public keys");
374330e2 2308
51470298 2309 memcpy(cookie, ssh->pktin.body, 8);
374330e2 2310
51470298 2311 i = makekey(ssh->pktin.body + 8, &servkey, &s->keystr1, 0);
2312 j = makekey(ssh->pktin.body + 8 + i, &hostkey, &s->keystr2, 0);
374330e2 2313
c5e9c988 2314 /*
1c2a93c4 2315 * Log the host key fingerprint.
c5e9c988 2316 */
c5e9c988 2317 {
2318 char logmsg[80];
1c2a93c4 2319 logevent("Host key fingerprint is:");
c5e9c988 2320 strcpy(logmsg, " ");
32874aea 2321 hostkey.comment = NULL;
2322 rsa_fingerprint(logmsg + strlen(logmsg),
2323 sizeof(logmsg) - strlen(logmsg), &hostkey);
c5e9c988 2324 logevent(logmsg);
2325 }
2326
51470298 2327 ssh->v1_remote_protoflags = GET_32BIT(ssh->pktin.body + 8 + i + j);
2328 s->supported_ciphers_mask = GET_32BIT(ssh->pktin.body + 12 + i + j);
2329 s->supported_auths_mask = GET_32BIT(ssh->pktin.body + 16 + i + j);
bea1ef5f 2330
51470298 2331 ssh->v1_local_protoflags =
2332 ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
2333 ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
b96dc54c 2334
c5e9c988 2335 MD5Init(&md5c);
51470298 2336 MD5Update(&md5c, s->keystr2, hostkey.bytes);
2337 MD5Update(&md5c, s->keystr1, servkey.bytes);
2338 MD5Update(&md5c, ssh->pktin.body, 8);
2339 MD5Final(s->session_id, &md5c);
374330e2 2340
32874aea 2341 for (i = 0; i < 32; i++)
51470298 2342 ssh->session_key[i] = random_byte();
374330e2 2343
51470298 2344 s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
374330e2 2345
3d88e64d 2346 s->rsabuf = snewn(s->len, unsigned char);
51470298 2347 if (!s->rsabuf)
374330e2 2348 fatalbox("Out of memory");
2349
89ee5268 2350 /*
2351 * Verify the host key.
2352 */
2353 {
32874aea 2354 /*
2355 * First format the key into a string.
2356 */
2357 int len = rsastr_len(&hostkey);
2358 char fingerprint[100];
3d88e64d 2359 char *keystr = snewn(len, char);
32874aea 2360 if (!keystr)
2361 fatalbox("Out of memory");
2362 rsastr_fmt(keystr, &hostkey);
2363 rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
a8327734 2364 verify_ssh_host_key(ssh->frontend,
2365 ssh->savedhost, ssh->savedport, "rsa", keystr,
32874aea 2366 fingerprint);
2367 sfree(keystr);
2368 }
2369
2370 for (i = 0; i < 32; i++) {
51470298 2371 s->rsabuf[i] = ssh->session_key[i];
374330e2 2372 if (i < 16)
51470298 2373 s->rsabuf[i] ^= s->session_id[i];
374330e2 2374 }
2375
2376 if (hostkey.bytes > servkey.bytes) {
51470298 2377 rsaencrypt(s->rsabuf, 32, &servkey);
2378 rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
374330e2 2379 } else {
51470298 2380 rsaencrypt(s->rsabuf, 32, &hostkey);
2381 rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
374330e2 2382 }
2383
c5e9c988 2384 logevent("Encrypted session key");
2385
ca20bfcf 2386 {
2387 int cipher_chosen = 0, warn = 0;
2388 char *cipher_string = NULL;
51470298 2389 int i;
ca20bfcf 2390 for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
86916870 2391 int next_cipher = ssh->cfg.ssh_cipherlist[i];
ca20bfcf 2392 if (next_cipher == CIPHER_WARN) {
2393 /* If/when we choose a cipher, warn about it */
2394 warn = 1;
2395 } else if (next_cipher == CIPHER_AES) {
2396 /* XXX Probably don't need to mention this. */
2397 logevent("AES not supported in SSH1, skipping");
2398 } else {
2399 switch (next_cipher) {
51470298 2400 case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
ca20bfcf 2401 cipher_string = "3DES"; break;
51470298 2402 case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
ca20bfcf 2403 cipher_string = "Blowfish"; break;
51470298 2404 case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
ca20bfcf 2405 cipher_string = "single-DES"; break;
2406 }
51470298 2407 if (s->supported_ciphers_mask & (1 << s->cipher_type))
ca20bfcf 2408 cipher_chosen = 1;
2409 }
2410 }
2411 if (!cipher_chosen) {
51470298 2412 if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
6b5cf8b4 2413 bombout(("Server violates SSH 1 protocol by not "
ca20bfcf 2414 "supporting 3DES encryption"));
2415 else
2416 /* shouldn't happen */
6b5cf8b4 2417 bombout(("No supported ciphers found"));
a99a05c0 2418 crReturn(0);
2419 }
ca20bfcf 2420
2421 /* Warn about chosen cipher if necessary. */
2422 if (warn)
a8327734 2423 askcipher(ssh->frontend, cipher_string, 0);
bea1ef5f 2424 }
ca20bfcf 2425
51470298 2426 switch (s->cipher_type) {
32874aea 2427 case SSH_CIPHER_3DES:
2428 logevent("Using 3DES encryption");
2429 break;
2430 case SSH_CIPHER_DES:
2431 logevent("Using single-DES encryption");
2432 break;
2433 case SSH_CIPHER_BLOWFISH:
2434 logevent("Using Blowfish encryption");
2435 break;
c5e9c988 2436 }
bea1ef5f 2437
51470298 2438 send_packet(ssh, SSH1_CMSG_SESSION_KEY,
2439 PKT_CHAR, s->cipher_type,
32874aea 2440 PKT_DATA, cookie, 8,
51470298 2441 PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
2442 PKT_DATA, s->rsabuf, s->len,
2443 PKT_INT, ssh->v1_local_protoflags, PKT_END);
fb09bf1c 2444
c5e9c988 2445 logevent("Trying to enable encryption...");
374330e2 2446
51470298 2447 sfree(s->rsabuf);
374330e2 2448
51470298 2449 ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
2450 s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
2451 &ssh_3des);
371e569c 2452 ssh->v1_cipher_ctx = ssh->cipher->make_context();
2453 ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
57356d63 2454 logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
374330e2 2455
0183b242 2456 ssh->crcda_ctx = crcda_make_context();
2457 logevent("Installing CRC compensation attack detector");
2458
fb09bf1c 2459 crWaitUntil(ispkt);
374330e2 2460
51470298 2461 if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
6b5cf8b4 2462 bombout(("Encryption not successfully enabled"));
32874aea 2463 crReturn(0);
8d5de777 2464 }
374330e2 2465
c5e9c988 2466 logevent("Successfully started encryption");
2467
374330e2 2468 fflush(stdout);
2469 {
86916870 2470 if ((flags & FLAG_INTERACTIVE) && !*ssh->cfg.username) {
c0a81592 2471 if (ssh_get_line && !ssh_getline_pw_only) {
32874aea 2472 if (!ssh_get_line("login as: ",
51470298 2473 s->username, sizeof(s->username), FALSE)) {
32874aea 2474 /*
2475 * get_line failed to get a username.
2476 * Terminate.
2477 */
2478 logevent("No username provided. Abandoning session.");
3bb2f322 2479 ssh_closing((Plug)ssh, NULL, 0, 0);
32874aea 2480 crReturn(1);
2481 }
2482 } else {
51470298 2483 int ret; /* need not be kept over crReturn */
2484 c_write_str(ssh, "login as: ");
2485 ssh->send_ok = 1;
0405e71f 2486
51470298 2487 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
0405e71f 2488 do {
32874aea 2489 crWaitUntil(!ispkt);
51470298 2490 ret = process_userpass_input(ssh, in, inlen);
0405e71f 2491 } while (ret == 0);
2492 if (ret < 0)
2493 cleanup_exit(0);
51470298 2494 c_write_str(ssh, "\r\n");
32874aea 2495 }
2496 } else {
86916870 2497 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
51470298 2498 s->username[sizeof(s->username)-1] = '\0';
374330e2 2499 }
fb09bf1c 2500
51470298 2501 send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
c5e9c988 2502 {
51470298 2503 char userlog[22 + sizeof(s->username)];
2504 sprintf(userlog, "Sent username \"%s\"", s->username);
c5e9c988 2505 logevent(userlog);
32874aea 2506 if (flags & FLAG_INTERACTIVE &&
2507 (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
3c8e959b 2508 strcat(userlog, "\r\n");
51470298 2509 c_write_str(ssh, userlog);
3c8e959b 2510 }
c5e9c988 2511 }
374330e2 2512 }
2513
fb09bf1c 2514 crWaitUntil(ispkt);
374330e2 2515
51470298 2516 if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
0df73905 2517 /* We must not attempt PK auth. Pretend we've already tried it. */
51470298 2518 s->tried_publickey = s->tried_agent = 1;
0df73905 2519 } else {
51470298 2520 s->tried_publickey = s->tried_agent = 0;
0df73905 2521 }
51470298 2522 s->tis_auth_refused = s->ccard_auth_refused = 0;
86916870 2523 /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
9a30e26b 2524 if (!filename_is_null(ssh->cfg.keyfile)) {
2525 if (!rsakey_pubblob(&ssh->cfg.keyfile,
51470298 2526 &s->publickey_blob, &s->publickey_bloblen))
2527 s->publickey_blob = NULL;
396778f1 2528 } else
51470298 2529 s->publickey_blob = NULL;
7cca0d81 2530
51470298 2531 while (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2532 s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
614a20a0 2533
51470298 2534 if (agent_exists() && !s->tried_agent) {
32874aea 2535 /*
2536 * Attempt RSA authentication using Pageant.
2537 */
32874aea 2538 void *r;
2539
51470298 2540 s->authed = FALSE;
2541 s->tried_agent = 1;
32874aea 2542 logevent("Pageant is running. Requesting keys.");
2543
2544 /* Request the keys held by the agent. */
51470298 2545 PUT_32BIT(s->request, 1);
2546 s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
2547 agent_query(s->request, 5, &r, &s->responselen);
2548 s->response = (unsigned char *) r;
2549 if (s->response && s->responselen >= 5 &&
2550 s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
2551 s->p = s->response + 5;
2552 s->nkeys = GET_32BIT(s->p);
2553 s->p += 4;
32874aea 2554 {
2555 char buf[64];
51470298 2556 sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
32874aea 2557 logevent(buf);
2558 }
51470298 2559 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
32874aea 2560 {
2561 char buf[64];
51470298 2562 sprintf(buf, "Trying Pageant key #%d", s->keyi);
32874aea 2563 logevent(buf);
2564 }
51470298 2565 if (s->publickey_blob &&
2566 !memcmp(s->p, s->publickey_blob,
2567 s->publickey_bloblen)) {
396778f1 2568 logevent("This key matches configured key file");
51470298 2569 s->tried_publickey = 1;
396778f1 2570 }
51470298 2571 s->p += 4;
2572 s->p += ssh1_read_bignum(s->p, &s->key.exponent);
2573 s->p += ssh1_read_bignum(s->p, &s->key.modulus);
2574 s->commentlen = GET_32BIT(s->p);
2575 s->p += 4;
d8baa528 2576 s->commentp = (char *)s->p;
51470298 2577 s->p += s->commentlen;
2578 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2579 PKT_BIGNUM, s->key.modulus, PKT_END);
32874aea 2580 crWaitUntil(ispkt);
51470298 2581 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
32874aea 2582 logevent("Key refused");
2583 continue;
2584 }
2585 logevent("Received RSA challenge");
51470298 2586 ssh1_read_bignum(ssh->pktin.body, &s->challenge);
32874aea 2587 {
2588 char *agentreq, *q, *ret;
2d466ffd 2589 void *vret;
32874aea 2590 int len, retlen;
2591 len = 1 + 4; /* message type, bit count */
51470298 2592 len += ssh1_bignum_length(s->key.exponent);
2593 len += ssh1_bignum_length(s->key.modulus);
2594 len += ssh1_bignum_length(s->challenge);
32874aea 2595 len += 16; /* session id */
2596 len += 4; /* response format */
3d88e64d 2597 agentreq = snewn(4 + len, char);
32874aea 2598 PUT_32BIT(agentreq, len);
2599 q = agentreq + 4;
2600 *q++ = SSH1_AGENTC_RSA_CHALLENGE;
51470298 2601 PUT_32BIT(q, bignum_bitcount(s->key.modulus));
32874aea 2602 q += 4;
51470298 2603 q += ssh1_write_bignum(q, s->key.exponent);
2604 q += ssh1_write_bignum(q, s->key.modulus);
2605 q += ssh1_write_bignum(q, s->challenge);
2606 memcpy(q, s->session_id, 16);
32874aea 2607 q += 16;
2608 PUT_32BIT(q, 1); /* response format */
2d466ffd 2609 agent_query(agentreq, len + 4, &vret, &retlen);
2610 ret = vret;
32874aea 2611 sfree(agentreq);
2612 if (ret) {
2613 if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
2614 logevent("Sending Pageant's response");
51470298 2615 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
32874aea 2616 PKT_DATA, ret + 5, 16,
2617 PKT_END);
2618 sfree(ret);
2619 crWaitUntil(ispkt);
51470298 2620 if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
32874aea 2621 logevent
2622 ("Pageant's response accepted");
2623 if (flags & FLAG_VERBOSE) {
51470298 2624 c_write_str(ssh, "Authenticated using"
2625 " RSA key \"");
2626 c_write(ssh, s->commentp,
2627 s->commentlen);
2628 c_write_str(ssh, "\" from agent\r\n");
32874aea 2629 }
51470298 2630 s->authed = TRUE;
32874aea 2631 } else
2632 logevent
2633 ("Pageant's response not accepted");
2634 } else {
2635 logevent
2636 ("Pageant failed to answer challenge");
2637 sfree(ret);
2638 }
2639 } else {
2640 logevent("No reply received from Pageant");
2641 }
2642 }
51470298 2643 freebn(s->key.exponent);
2644 freebn(s->key.modulus);
2645 freebn(s->challenge);
2646 if (s->authed)
32874aea 2647 break;
2648 }
2649 }
51470298 2650 if (s->authed)
32874aea 2651 break;
2652 }
9a30e26b 2653 if (!filename_is_null(ssh->cfg.keyfile) && !s->tried_publickey)
51470298 2654 s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
32874aea 2655
86916870 2656 if (ssh->cfg.try_tis_auth &&
51470298 2657 (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
2658 !s->tis_auth_refused) {
2659 s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
32874aea 2660 logevent("Requested TIS authentication");
51470298 2661 send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
32874aea 2662 crWaitUntil(ispkt);
51470298 2663 if (ssh->pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
32874aea 2664 logevent("TIS authentication declined");
2665 if (flags & FLAG_INTERACTIVE)
51470298 2666 c_write_str(ssh, "TIS authentication refused.\r\n");
2667 s->tis_auth_refused = 1;
614a20a0 2668 continue;
32874aea 2669 } else {
51470298 2670 int challengelen = GET_32BIT(ssh->pktin.body);
32874aea 2671 logevent("Received TIS challenge");
51470298 2672 if (challengelen > sizeof(s->prompt) - 1)
2673 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2674 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
614a20a0 2675 /* Prompt heuristic comes from OpenSSH */
51470298 2676 strncpy(s->prompt + challengelen,
2677 memchr(s->prompt, '\n', challengelen) ?
614a20a0 2678 "": "\r\nResponse: ",
51470298 2679 (sizeof s->prompt) - challengelen);
2680 s->prompt[(sizeof s->prompt) - 1] = '\0';
32874aea 2681 }
2682 }
86916870 2683 if (ssh->cfg.try_tis_auth &&
51470298 2684 (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
2685 !s->ccard_auth_refused) {
2686 s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
32874aea 2687 logevent("Requested CryptoCard authentication");
51470298 2688 send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
32874aea 2689 crWaitUntil(ispkt);
51470298 2690 if (ssh->pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
32874aea 2691 logevent("CryptoCard authentication declined");
51470298 2692 c_write_str(ssh, "CryptoCard authentication refused.\r\n");
2693 s->ccard_auth_refused = 1;
614a20a0 2694 continue;
32874aea 2695 } else {
51470298 2696 int challengelen = GET_32BIT(ssh->pktin.body);
32874aea 2697 logevent("Received CryptoCard challenge");
51470298 2698 if (challengelen > sizeof(s->prompt) - 1)
2699 challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
2700 memcpy(s->prompt, ssh->pktin.body + 4, challengelen);
2701 strncpy(s->prompt + challengelen,
2702 memchr(s->prompt, '\n', challengelen) ?
614a20a0 2703 "" : "\r\nResponse: ",
51470298 2704 sizeof(s->prompt) - challengelen);
2705 s->prompt[sizeof(s->prompt) - 1] = '\0';
32874aea 2706 }
2707 }
51470298 2708 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
2709 sprintf(s->prompt, "%.90s@%.90s's password: ",
2710 s->username, ssh->savedhost);
32874aea 2711 }
51470298 2712 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
32874aea 2713 char *comment = NULL;
231ee168 2714 int type;
2715 char msgbuf[256];
32874aea 2716 if (flags & FLAG_VERBOSE)
51470298 2717 c_write_str(ssh, "Trying public key authentication.\r\n");
6c6d9ed9 2718 logeventf(ssh, "Trying public key \"%s\"",
2719 filename_to_str(&ssh->cfg.keyfile));
9a30e26b 2720 type = key_type(&ssh->cfg.keyfile);
231ee168 2721 if (type != SSH_KEYTYPE_SSH1) {
2722 sprintf(msgbuf, "Key is of wrong type (%s)",
2723 key_type_to_str(type));
2724 logevent(msgbuf);
51470298 2725 c_write_str(ssh, msgbuf);
2726 c_write_str(ssh, "\r\n");
2727 s->tried_publickey = 1;
231ee168 2728 continue;
2729 }
9a30e26b 2730 if (!rsakey_encrypted(&ssh->cfg.keyfile, &comment)) {
32874aea 2731 if (flags & FLAG_VERBOSE)
51470298 2732 c_write_str(ssh, "No passphrase required.\r\n");
32874aea 2733 goto tryauth;
2734 }
51470298 2735 sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
32874aea 2736 sfree(comment);
2737 }
a52f067e 2738
614a20a0 2739 /*
2740 * Show password prompt, having first obtained it via a TIS
2741 * or CryptoCard exchange if we're doing TIS or CryptoCard
2742 * authentication.
2743 */
fa17a66e 2744 if (ssh_get_line) {
51470298 2745 if (!ssh_get_line(s->prompt, s->password,
2746 sizeof(s->password), TRUE)) {
32874aea 2747 /*
2748 * get_line failed to get a password (for example
2749 * because one was supplied on the command line
2750 * which has already failed to work). Terminate.
2751 */
51470298 2752 send_packet(ssh, SSH1_MSG_DISCONNECT,
2bc6a386 2753 PKT_STR, "No more passwords available to try",
2754 PKT_END);
247308b5 2755 logevent("Unable to authenticate");
a8327734 2756 connection_fatal(ssh->frontend, "Unable to authenticate");
3bb2f322 2757 ssh_closing((Plug)ssh, NULL, 0, 0);
32874aea 2758 crReturn(1);
2759 }
fb09bf1c 2760 } else {
614a20a0 2761 /* Prompt may have come from server. We've munged it a bit, so
2762 * we know it to be zero-terminated at least once. */
51470298 2763 int ret; /* need not be saved over crReturn */
2764 c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
2765 s->pos = 0;
0405e71f 2766
51470298 2767 setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
0405e71f 2768 do {
32874aea 2769 crWaitUntil(!ispkt);
51470298 2770 ret = process_userpass_input(ssh, in, inlen);
0405e71f 2771 } while (ret == 0);
2772 if (ret < 0)
2773 cleanup_exit(0);
51470298 2774 c_write_str(ssh, "\r\n");
32874aea 2775 }
2776
2777 tryauth:
51470298 2778 if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
32874aea 2779 /*
2780 * Try public key authentication with the specified
2781 * key file.
2782 */
51470298 2783 s->tried_publickey = 1;
2784
2785 {
9a30e26b 2786 int ret = loadrsakey(&ssh->cfg.keyfile, &s->key, s->password);
51470298 2787 if (ret == 0) {
2788 c_write_str(ssh, "Couldn't load private key from ");
9fab77dc 2789 c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
51470298 2790 c_write_str(ssh, ".\r\n");
2791 continue; /* go and try password */
2792 }
2793 if (ret == -1) {
2794 c_write_str(ssh, "Wrong passphrase.\r\n");
2795 s->tried_publickey = 0;
2796 continue; /* try again */
2797 }
32874aea 2798 }
2799
2800 /*
2801 * Send a public key attempt.
2802 */
51470298 2803 send_packet(ssh, SSH1_CMSG_AUTH_RSA,
2804 PKT_BIGNUM, s->key.modulus, PKT_END);
32874aea 2805
2806 crWaitUntil(ispkt);
51470298 2807 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
2808 c_write_str(ssh, "Server refused our public key.\r\n");
32874aea 2809 continue; /* go and try password */
2810 }
51470298 2811 if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
6b5cf8b4 2812 bombout(("Bizarre response to offer of public key"));
32874aea 2813 crReturn(0);
2814 }
32874aea 2815
51470298 2816 {
2817 int i;
2818 unsigned char buffer[32];
2819 Bignum challenge, response;
2820
2821 ssh1_read_bignum(ssh->pktin.body, &challenge);
2822 response = rsadecrypt(challenge, &s->key);
2823 freebn(s->key.private_exponent);/* burn the evidence */
32874aea 2824
51470298 2825 for (i = 0; i < 32; i++) {
2826 buffer[i] = bignum_byte(response, 31 - i);
2827 }
2828
2829 MD5Init(&md5c);
2830 MD5Update(&md5c, buffer, 32);
2831 MD5Update(&md5c, s->session_id, 16);
2832 MD5Final(buffer, &md5c);
32874aea 2833
51470298 2834 send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
2835 PKT_DATA, buffer, 16, PKT_END);
2836
2837 freebn(challenge);
2838 freebn(response);
2839 }
32874aea 2840
2841 crWaitUntil(ispkt);
51470298 2842 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
32874aea 2843 if (flags & FLAG_VERBOSE)
51470298 2844 c_write_str(ssh, "Failed to authenticate with"
2845 " our public key.\r\n");
32874aea 2846 continue; /* go and try password */
51470298 2847 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
6b5cf8b4 2848 bombout(("Bizarre response to RSA authentication response"));
32874aea 2849 crReturn(0);
2850 }
2851
2852 break; /* we're through! */
2853 } else {
51470298 2854 if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
32874aea 2855 /*
2856 * Defence against traffic analysis: we send a
2857 * whole bunch of packets containing strings of
2858 * different lengths. One of these strings is the
2859 * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
2860 * The others are all random data in
2861 * SSH1_MSG_IGNORE packets. This way a passive
2862 * listener can't tell which is the password, and
2863 * hence can't deduce the password length.
2864 *
2865 * Anybody with a password length greater than 16
2866 * bytes is going to have enough entropy in their
2867 * password that a listener won't find it _that_
2868 * much help to know how long it is. So what we'll
2869 * do is:
2870 *
2871 * - if password length < 16, we send 15 packets
2872 * containing string lengths 1 through 15
2873 *
2874 * - otherwise, we let N be the nearest multiple
2875 * of 8 below the password length, and send 8
2876 * packets containing string lengths N through
2877 * N+7. This won't obscure the order of
2878 * magnitude of the password length, but it will
2879 * introduce a bit of extra uncertainty.
2880 *
2881 * A few servers (the old 1.2.18 through 1.2.22)
2882 * can't deal with SSH1_MSG_IGNORE. For these
2883 * servers, we need an alternative defence. We make
2884 * use of the fact that the password is interpreted
2885 * as a C string: so we can append a NUL, then some
2886 * random data.
bd358db1 2887 *
2888 * One server (a Cisco one) can deal with neither
2889 * SSH1_MSG_IGNORE _nor_ a padded password string.
2890 * For this server we are left with no defences
2891 * against password length sniffing.
32874aea 2892 */
51470298 2893 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
b17c8428 2894 /*
2895 * The server can deal with SSH1_MSG_IGNORE, so
2896 * we can use the primary defence.
2897 */
32874aea 2898 int bottom, top, pwlen, i;
2899 char *randomstr;
2900
51470298 2901 pwlen = strlen(s->password);
32874aea 2902 if (pwlen < 16) {
2903 bottom = 0; /* zero length passwords are OK! :-) */
2904 top = 15;
2905 } else {
2906 bottom = pwlen & ~7;
2907 top = bottom + 7;
2908 }
2909
2910 assert(pwlen >= bottom && pwlen <= top);
2911
3d88e64d 2912 randomstr = snewn(top + 1, char);
32874aea 2913
2914 for (i = bottom; i <= top; i++) {
2915 if (i == pwlen)
51470298 2916 defer_packet(ssh, s->pwpkt_type,
2917 PKT_STR, s->password, PKT_END);
32874aea 2918 else {
2919 for (j = 0; j < i; j++) {
2920 do {
2921 randomstr[j] = random_byte();
2922 } while (randomstr[j] == '\0');
2923 }
2924 randomstr[i] = '\0';
51470298 2925 defer_packet(ssh, SSH1_MSG_IGNORE,
32874aea 2926 PKT_STR, randomstr, PKT_END);
2927 }
2928 }
bd358db1 2929 logevent("Sending password with camouflage packets");
51470298 2930 ssh_pkt_defersend(ssh);
bd358db1 2931 }
51470298 2932 else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
b17c8428 2933 /*
2934 * The server can't deal with SSH1_MSG_IGNORE
2935 * but can deal with padded passwords, so we
2936 * can use the secondary defence.
2937 */
bd358db1 2938 char string[64];
51470298 2939 char *ss;
bd358db1 2940 int len;
2941
51470298 2942 len = strlen(s->password);
bd358db1 2943 if (len < sizeof(string)) {
51470298 2944 ss = string;
2945 strcpy(string, s->password);
bd358db1 2946 len++; /* cover the zero byte */
2947 while (len < sizeof(string)) {
2948 string[len++] = (char) random_byte();
2949 }
2950 } else {
51470298 2951 ss = s->password;
bd358db1 2952 }
2953 logevent("Sending length-padded password");
51470298 2954 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2955 PKT_DATA, ss, len, PKT_END);
bd358db1 2956 } else {
2957 /*
2958 * The server has _both_
2959 * BUG_CHOKES_ON_SSH1_IGNORE and
2960 * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
2961 * therefore nothing we can do.
2962 */
2963 int len;
51470298 2964 len = strlen(s->password);
bd358db1 2965 logevent("Sending unpadded password");
51470298 2966 send_packet(ssh, s->pwpkt_type, PKT_INT, len,
2967 PKT_DATA, s->password, len, PKT_END);
32874aea 2968 }
2969 } else {
51470298 2970 send_packet(ssh, s->pwpkt_type, PKT_STR, s->password, PKT_END);
32874aea 2971 }
2972 }
c5e9c988 2973 logevent("Sent password");
51470298 2974 memset(s->password, 0, strlen(s->password));
fb09bf1c 2975 crWaitUntil(ispkt);
51470298 2976 if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
32874aea 2977 if (flags & FLAG_VERBOSE)
51470298 2978 c_write_str(ssh, "Access denied\r\n");
c5e9c988 2979 logevent("Authentication refused");
51470298 2980 } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
6b5cf8b4 2981 bombout(("Strange packet received, type %d", ssh->pktin.type));
32874aea 2982 crReturn(0);
374330e2 2983 }
2984 }
2985
c5e9c988 2986 logevent("Authentication successful");
2987
fb09bf1c 2988 crFinish(1);
2989}
2990
32874aea 2991void sshfwd_close(struct ssh_channel *c)
2992{
51470298 2993 Ssh ssh = c->ssh;
2994
80e48603 2995 if (c && !c->closes) {
4ed34d25 2996 /*
2997 * If the channel's remoteid is -1, we have sent
2998 * CHANNEL_OPEN for this channel, but it hasn't even been
2999 * acknowledged by the server. So we must set a close flag
3000 * on it now, and then when the server acks the channel
3001 * open, we can close it then.
3002 */
36cac739 3003 if (((int)c->remoteid) != -1) {
51470298 3004 if (ssh->version == 1) {
3005 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
4ed34d25 3006 PKT_END);
3007 } else {
51470298 3008 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
3009 ssh2_pkt_adduint32(ssh, c->remoteid);
3010 ssh2_pkt_send(ssh);
4ed34d25 3011 }
32874aea 3012 }
0357890f 3013 c->closes = 1; /* sent MSG_CLOSE */
32874aea 3014 if (c->type == CHAN_X11) {
3015 c->u.x11.s = NULL;
d74d141c 3016 logevent("Forwarded X11 connection terminated");
4ed34d25 3017 } else if (c->type == CHAN_SOCKDATA ||
3018 c->type == CHAN_SOCKDATA_DORMANT) {
d74d141c 3019 c->u.pfd.s = NULL;
3020 logevent("Forwarded port closed");
32874aea 3021 }
3022 }
3023}
3024
5471d09a 3025int sshfwd_write(struct ssh_channel *c, char *buf, int len)
32874aea 3026{
51470298 3027 Ssh ssh = c->ssh;
3028
3029 if (ssh->version == 1) {
3030 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
32874aea 3031 PKT_INT, c->remoteid,
3032 PKT_INT, len, PKT_DATA, buf, len, PKT_END);
5471d09a 3033 /*
3034 * In SSH1 we can return 0 here - implying that forwarded
3035 * connections are never individually throttled - because
3036 * the only circumstance that can cause throttling will be
3037 * the whole SSH connection backing up, in which case
3038 * _everything_ will be throttled as a whole.
3039 */
3040 return 0;
783415f8 3041 } else {
32874aea 3042 ssh2_add_channel_data(c, buf, len);
5471d09a 3043 return ssh2_try_send(c);
3044 }
3045}
3046
3047void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
3048{
51470298 3049 Ssh ssh = c->ssh;
3050
3051 if (ssh->version == 1) {
5471d09a 3052 if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
3053 c->v.v1.throttling = 0;
51470298 3054 ssh1_throttle(ssh, -1);
5471d09a 3055 }
3056 } else {
3057 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
783415f8 3058 }
9c964e85 3059}
3060
51470298 3061static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
32874aea 3062{
51470298 3063 crBegin(ssh->ssh1_protocol_crstate);
fb09bf1c 3064
3065 random_init();
3066
51470298 3067 while (!do_ssh1_login(ssh, in, inlen, ispkt)) {
fb09bf1c 3068 crReturnV;
85ee8208 3069 }
51470298 3070 if (ssh->state == SSH_STATE_CLOSED)
32874aea 3071 crReturnV;
fb09bf1c 3072
86916870 3073 if (ssh->cfg.agentfwd && agent_exists()) {
32874aea 3074 logevent("Requesting agent forwarding");
51470298 3075 send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
32874aea 3076 do {
3077 crReturnV;
3078 } while (!ispkt);
51470298 3079 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3080 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
6b5cf8b4 3081 bombout(("Protocol confusion"));
32874aea 3082 crReturnV;
51470298 3083 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
32874aea 3084 logevent("Agent forwarding refused");
3085 } else {
3086 logevent("Agent forwarding enabled");
51470298 3087 ssh->agentfwd_enabled = TRUE;
db7d555c 3088 }
dacbd0e8 3089 }
3090
86916870 3091 if (ssh->cfg.x11_forward) {
32874aea 3092 char proto[20], data[64];
3093 logevent("Requesting X11 forwarding");
302121de 3094 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
86916870 3095 data, sizeof(data), ssh->cfg.x11_auth);
3096 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
51470298 3097 if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
3098 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
32874aea 3099 PKT_STR, proto, PKT_STR, data,
86916870 3100 PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
421d6835 3101 PKT_END);
32874aea 3102 } else {
51470298 3103 send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
32874aea 3104 PKT_STR, proto, PKT_STR, data, PKT_END);
3105 }
3106 do {
3107 crReturnV;
3108 } while (!ispkt);
51470298 3109 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3110 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
6b5cf8b4 3111 bombout(("Protocol confusion"));
32874aea 3112 crReturnV;
51470298 3113 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
32874aea 3114 logevent("X11 forwarding refused");
3115 } else {
3116 logevent("X11 forwarding enabled");
51470298 3117 ssh->X11_fwd_enabled = TRUE;
9c964e85 3118 }
3119 }
3120
d74d141c 3121 {
9bf696b1 3122 char type;
d74d141c 3123 int n;
a4fc0d74 3124 int sport,dport,sserv,dserv;
6ee9b735 3125 char sports[256], dports[256], saddr[256], host[256];
d74d141c 3126
51470298 3127 ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
d74d141c 3128 /* Add port forwardings. */
86916870 3129 ssh->portfwd_strptr = ssh->cfg.portfwd;
51470298 3130 while (*ssh->portfwd_strptr) {
3131 type = *ssh->portfwd_strptr++;
6ee9b735 3132 saddr[0] = '\0';
d74d141c 3133 n = 0;
6ee9b735 3134 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
3135 if (*ssh->portfwd_strptr == ':') {
3136 /*
3137 * We've seen a colon in the middle of the
3138 * source port number. This means that
3139 * everything we've seen until now is the
3140 * source _address_, so we'll move it into
3141 * saddr and start sports from the beginning
3142 * again.
3143 */
3144 ssh->portfwd_strptr++;
3145 sports[n] = '\0';
3146 strcpy(saddr, sports);
3147 n = 0;
3148 }
3149 if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
3150 }
d74d141c 3151 sports[n] = 0;
51470298 3152 if (*ssh->portfwd_strptr == '\t')
3153 ssh->portfwd_strptr++;
d74d141c 3154 n = 0;
6ee9b735 3155 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
3156 if (n < 255) host[n++] = *ssh->portfwd_strptr++;
3157 }
d74d141c 3158 host[n] = 0;
51470298 3159 if (*ssh->portfwd_strptr == ':')
3160 ssh->portfwd_strptr++;
d74d141c 3161 n = 0;
6ee9b735 3162 while (*ssh->portfwd_strptr) {
3163 if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
3164 }
d74d141c 3165 dports[n] = 0;
51470298 3166 ssh->portfwd_strptr++;
d74d141c 3167 dport = atoi(dports);
a4fc0d74 3168 dserv = 0;
3169 if (dport == 0) {
3170 dserv = 1;
68a49acb 3171 dport = net_service_lookup(dports);
3172 if (!dport) {
57356d63 3173 logeventf(ssh, "Service lookup failed for"
3174 " destination port \"%s\"", dports);
a4fc0d74 3175 }
3176 }
d74d141c 3177 sport = atoi(sports);
a4fc0d74 3178 sserv = 0;
3179 if (sport == 0) {
3180 sserv = 1;
68a49acb 3181 sport = net_service_lookup(sports);
3182 if (!sport) {
57356d63 3183 logeventf(ssh, "Service lookup failed for source"
3184 " port \"%s\"", sports);
a4fc0d74 3185 }
3186 }
d74d141c 3187 if (sport && dport) {
3188 if (type == 'L') {
6ee9b735 3189 pfd_addforward(host, dport, *saddr ? saddr : NULL,
e8fa8f62 3190 sport, ssh, &ssh->cfg);
6ee9b735 3191 logeventf(ssh, "Local port %.*s%.*s%.*s%.*s%d%.*s"
3192 " forwarding to %s:%.*s%.*s%d%.*s",
3193 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
3194 (int)(*saddr?1:0), ":",
57356d63 3195 (int)(sserv ? strlen(sports) : 0), sports,
3196 sserv, "(", sport, sserv, ")",
3197 host,
3198 (int)(dserv ? strlen(dports) : 0), dports,
3199 dserv, "(", dport, dserv, ")");
d74d141c 3200 } else {
3201 struct ssh_rportfwd *pf;
3d88e64d 3202 pf = snew(struct ssh_rportfwd);
bc240b21 3203 strcpy(pf->dhost, host);
3204 pf->dport = dport;
6ee9b735 3205 if (saddr) {
3206 logeventf(ssh,
3207 "SSH1 cannot handle source address spec \"%s:%d\"; ignoring",
3208 saddr, sport);
3209 }
51470298 3210 if (add234(ssh->rportfwds, pf) != pf) {
57356d63 3211 logeventf(ssh,
3212 "Duplicate remote port forwarding to %s:%d",
3213 host, dport);
bc240b21 3214 sfree(pf);
d74d141c 3215 } else {
57356d63 3216 logeventf(ssh, "Requesting remote port %.*s%.*s%d%.*s"
3217 " forward to %s:%.*s%.*s%d%.*s",
3218 (int)(sserv ? strlen(sports) : 0), sports,
3219 sserv, "(", sport, sserv, ")",
3220 host,
3221 (int)(dserv ? strlen(dports) : 0), dports,
3222 dserv, "(", dport, dserv, ")");
51470298 3223 send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
d74d141c 3224 PKT_INT, sport,
3225 PKT_STR, host,
3226 PKT_INT, dport,
3227 PKT_END);
9bf696b1 3228 do {
3229 crReturnV;
3230 } while (!ispkt);
51470298 3231 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3232 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
6b5cf8b4 3233 bombout(("Protocol confusion"));
9bf696b1 3234 crReturnV;
51470298 3235 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3236 c_write_str(ssh, "Server refused port"
3237 " forwarding\r\n");
9bf696b1 3238 }
3239 logevent("Remote port forwarding enabled");
d74d141c 3240 }
3241 }
3242 }
3243 }
3244 }
3245
86916870 3246 if (!ssh->cfg.nopty) {
51470298 3247 send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
86916870 3248 PKT_STR, ssh->cfg.termtype,
51470298 3249 PKT_INT, ssh->term_height,
3250 PKT_INT, ssh->term_width,
32874aea 3251 PKT_INT, 0, PKT_INT, 0, PKT_CHAR, 0, PKT_END);
51470298 3252 ssh->state = SSH_STATE_INTERMED;
32874aea 3253 do {
3254 crReturnV;
3255 } while (!ispkt);
51470298 3256 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3257 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
6b5cf8b4 3258 bombout(("Protocol confusion"));
32874aea 3259 crReturnV;
51470298 3260 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3261 c_write_str(ssh, "Server refused to allocate pty\r\n");
3262 ssh->editing = ssh->echoing = 1;
32874aea 3263 }
c5e9c988 3264 logevent("Allocated pty");
0965bee0 3265 } else {
51470298 3266 ssh->editing = ssh->echoing = 1;
374330e2 3267 }
3268
86916870 3269 if (ssh->cfg.compression) {
51470298 3270 send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
32874aea 3271 do {
3272 crReturnV;
3273 } while (!ispkt);
51470298 3274 if (ssh->pktin.type != SSH1_SMSG_SUCCESS
3275 && ssh->pktin.type != SSH1_SMSG_FAILURE) {
6b5cf8b4 3276 bombout(("Protocol confusion"));
32874aea 3277 crReturnV;
51470298 3278 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
3279 c_write_str(ssh, "Server refused to compress\r\n");
32874aea 3280 }
4ba9b64b 3281 logevent("Started compression");
51470298 3282 ssh->v1_compressing = TRUE;
5366aed8 3283 ssh->cs_comp_ctx = zlib_compress_init();
3284 logevent("Initialised zlib (RFC1950) compression");
3285 ssh->sc_comp_ctx = zlib_decompress_init();
3286 logevent("Initialised zlib (RFC1950) decompression");
4ba9b64b 3287 }
3288
fd5e5847 3289 /*
3290 * Start the shell or command.
3291 *
3292 * Special case: if the first-choice command is an SSH2
3293 * subsystem (hence not usable here) and the second choice
3294 * exists, we fall straight back to that.
3295 */
3296 {
86916870 3297 char *cmd = ssh->cfg.remote_cmd_ptr;
fd5e5847 3298
86916870 3299 if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
3300 cmd = ssh->cfg.remote_cmd_ptr2;
51470298 3301 ssh->fallback_cmd = TRUE;
fd5e5847 3302 }
3303 if (*cmd)
51470298 3304 send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
fd5e5847 3305 else
51470298 3306 send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
fd5e5847 3307 logevent("Started session");
3308 }
374330e2 3309
51470298 3310 ssh->state = SSH_STATE_SESSION;
3311 if (ssh->size_needed)
3312 ssh_size(ssh, ssh->term_width, ssh->term_height);
3313 if (ssh->eof_needed)
3314 ssh_special(ssh, TS_EOF);
374330e2 3315
b9d7bcad 3316 if (ssh->ldisc)
3317 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
51470298 3318 ssh->send_ok = 1;
3319 ssh->channels = newtree234(ssh_channelcmp);
374330e2 3320 while (1) {
3321 crReturnV;
3322 if (ispkt) {
51470298 3323 if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
3324 ssh->pktin.type == SSH1_SMSG_STDERR_DATA) {
3325 long len = GET_32BIT(ssh->pktin.body);
5471d09a 3326 int bufsize =
51470298 3327 from_backend(ssh->frontend,
3328 ssh->pktin.type == SSH1_SMSG_STDERR_DATA,
d8baa528 3329 (char *)(ssh->pktin.body) + 4, len);
51470298 3330 if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
3331 ssh->v1_stdout_throttling = 1;
3332 ssh1_throttle(ssh, +1);
5471d09a 3333 }
51470298 3334 } else if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
3bb2f322 3335 ssh_closing((Plug)ssh, NULL, 0, 0);
c5e9c988 3336 logevent("Received disconnect request");
32874aea 3337 crReturnV;
51470298 3338 } else if (ssh->pktin.type == SSH1_SMSG_X11_OPEN) {
32874aea 3339 /* Remote side is trying to open a channel to talk to our
3340 * X-Server. Give them back a local channel number. */
3341 struct ssh_channel *c;
9c964e85 3342
3343 logevent("Received X11 connect request");
3344 /* Refuse if X11 forwarding is disabled. */
51470298 3345 if (!ssh->X11_fwd_enabled) {
3346 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3347 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
9c964e85 3348 logevent("Rejected X11 connect request");
3349 } else {
3d88e64d 3350 c = snew(struct ssh_channel);
51470298 3351 c->ssh = ssh;
9c964e85 3352
86916870 3353 if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
e8fa8f62 3354 ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
32874aea 3355 logevent("opening X11 forward connection failed");
3356 sfree(c);
51470298 3357 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3358 PKT_INT, GET_32BIT(ssh->pktin.body),
32874aea 3359 PKT_END);
9c964e85 3360 } else {
32874aea 3361 logevent
3362 ("opening X11 forward connection succeeded");
51470298 3363 c->remoteid = GET_32BIT(ssh->pktin.body);
3364 c->localid = alloc_channel_id(ssh);
32874aea 3365 c->closes = 0;
5471d09a 3366 c->v.v1.throttling = 0;
32874aea 3367 c->type = CHAN_X11; /* identify channel type */
51470298 3368 add234(ssh->channels, c);
3369 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
32874aea 3370 PKT_INT, c->remoteid, PKT_INT,
3371 c->localid, PKT_END);
3372 logevent("Opened X11 forward channel");
9c964e85 3373 }
3374 }
51470298 3375 } else if (ssh->pktin.type == SSH1_SMSG_AGENT_OPEN) {
32874aea 3376 /* Remote side is trying to open a channel to talk to our
3377 * agent. Give them back a local channel number. */
3378 struct ssh_channel *c;
db7d555c 3379
3380 /* Refuse if agent forwarding is disabled. */
51470298 3381 if (!ssh->agentfwd_enabled) {
3382 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3383 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
db7d555c 3384 } else {
3d88e64d 3385 c = snew(struct ssh_channel);
51470298 3386 c->ssh = ssh;
3387 c->remoteid = GET_32BIT(ssh->pktin.body);
3388 c->localid = alloc_channel_id(ssh);
db7d555c 3389 c->closes = 0;
5471d09a 3390 c->v.v1.throttling = 0;
32874aea 3391 c->type = CHAN_AGENT; /* identify channel type */
db7d555c 3392 c->u.a.lensofar = 0;
51470298 3393 add234(ssh->channels, c);
3394 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
db7d555c 3395 PKT_INT, c->remoteid, PKT_INT, c->localid,
3396 PKT_END);
3397 }
51470298 3398 } else if (ssh->pktin.type == SSH1_MSG_PORT_OPEN) {
d74d141c 3399 /* Remote side is trying to open a channel to talk to a
3400 * forwarded port. Give them back a local channel number. */
3401 struct ssh_channel *c;
3402 struct ssh_rportfwd pf;
3403 int hostsize, port;
3404 char host[256], buf[1024];
3405 char *p, *h, *e;
3d88e64d 3406 c = snew(struct ssh_channel);
51470298 3407 c->ssh = ssh;
d74d141c 3408
51470298 3409 hostsize = GET_32BIT(ssh->pktin.body+4);
d8baa528 3410 for (h = host, p = (char *)(ssh->pktin.body+8);
3411 hostsize != 0; hostsize--) {
d74d141c 3412 if (h+1 < host+sizeof(host))
3413 *h++ = *p;
95bc8819 3414 p++;
d74d141c 3415 }
3416 *h = 0;
3417 port = GET_32BIT(p);
3418
bc240b21 3419 strcpy(pf.dhost, host);
3420 pf.dport = port;
d74d141c 3421
51470298 3422 if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
d74d141c 3423 sprintf(buf, "Rejected remote port open request for %s:%d",
3424 host, port);
3425 logevent(buf);
51470298 3426 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3427 PKT_INT, GET_32BIT(ssh->pktin.body), PKT_END);
d74d141c 3428 } else {
3429 sprintf(buf, "Received remote port open request for %s:%d",
3430 host, port);
3431 logevent(buf);
e8fa8f62 3432 e = pfd_newconnect(&c->u.pfd.s, host, port, c, &ssh->cfg);
d74d141c 3433 if (e != NULL) {
3434 char buf[256];
3435 sprintf(buf, "Port open failed: %s", e);
3436 logevent(buf);
3437 sfree(c);
51470298 3438 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
3439 PKT_INT, GET_32BIT(ssh->pktin.body),
d74d141c 3440 PKT_END);
3441 } else {
51470298 3442 c->remoteid = GET_32BIT(ssh->pktin.body);
3443 c->localid = alloc_channel_id(ssh);
d74d141c 3444 c->closes = 0;
5471d09a 3445 c->v.v1.throttling = 0;
d74d141c 3446 c->type = CHAN_SOCKDATA; /* identify channel type */
51470298 3447 add234(ssh->channels, c);
3448 send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
d74d141c 3449 PKT_INT, c->remoteid, PKT_INT,
3450 c->localid, PKT_END);
3451 logevent("Forwarded port opened successfully");
3452 }
3453 }
3454
51470298 3455 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
3456 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
3457 unsigned int localid = GET_32BIT(ssh->pktin.body+4);
bc240b21 3458 struct ssh_channel *c;
3459
51470298 3460 c = find234(ssh->channels, &remoteid, ssh_channelfind);
bc240b21 3461 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3462 c->remoteid = localid;
3463 c->type = CHAN_SOCKDATA;
7781f316 3464 c->v.v1.throttling = 0;
bc240b21 3465 pfd_confirm(c->u.pfd.s);
3466 }
d74d141c 3467
4ed34d25 3468 if (c && c->closes) {
3469 /*
3470 * We have a pending close on this channel,
3471 * which we decided on before the server acked
3472 * the channel open. So now we know the
3473 * remoteid, we can close it again.
3474 */
51470298 3475 send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
3476 PKT_INT, c->remoteid, PKT_END);
4ed34d25 3477 }
3478
51470298 3479 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
3480 unsigned int remoteid = GET_32BIT(ssh->pktin.body);
724cface 3481 struct ssh_channel *c;
3482
51470298 3483 c = find234(ssh->channels, &remoteid, ssh_channelfind);
724cface 3484 if (c && c->type == CHAN_SOCKDATA_DORMANT) {
3485 logevent("Forwarded connection refused by server");
3486 pfd_close(c->u.pfd.s);
51470298 3487 del234(ssh->channels, c);
724cface 3488 sfree(c);
3489 }
3490
51470298 3491 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
3492 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
32874aea 3493 /* Remote side closes a channel. */
51470298 3494 unsigned i = GET_32BIT(ssh->pktin.body);
32874aea 3495 struct ssh_channel *c;
51470298 3496 c = find234(ssh->channels, &i, ssh_channelfind);
d0d844c1 3497 if (c && ((int)c->remoteid) != -1) {
32874aea 3498 int closetype;
3499 closetype =
51470298 3500 (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
0357890f 3501
783415f8 3502 if ((c->closes == 0) && (c->type == CHAN_X11)) {
d74d141c 3503 logevent("Forwarded X11 connection terminated");
9c964e85 3504 assert(c->u.x11.s != NULL);
3505 x11_close(c->u.x11.s);
3506 c->u.x11.s = NULL;
3507 }
d74d141c 3508 if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
3509 logevent("Forwarded port closed");
3510 assert(c->u.pfd.s != NULL);
3511 pfd_close(c->u.pfd.s);
3512 c->u.pfd.s = NULL;
3513 }
0357890f 3514
3515 c->closes |= (closetype << 2); /* seen this message */
3516 if (!(c->closes & closetype)) {
51470298 3517 send_packet(ssh, ssh->pktin.type, PKT_INT, c->remoteid,
0357890f 3518 PKT_END);
3519 c->closes |= closetype; /* sent it too */
3520 }
3521
3522 if (c->closes == 15) {
51470298 3523 del234(ssh->channels, c);
32874aea 3524 sfree(c);
3525 }
d0d844c1 3526 } else {
6b5cf8b4 3527 bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
51470298 3528 ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
d0d844c1 3529 "_CONFIRMATION", c ? "half-open" : "nonexistent",
3530 i));
32874aea 3531 }
51470298 3532 } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_DATA) {
32874aea 3533 /* Data sent down one of our channels. */
51470298 3534 int i = GET_32BIT(ssh->pktin.body);
3535 int len = GET_32BIT(ssh->pktin.body + 4);
3536 unsigned char *p = ssh->pktin.body + 8;
32874aea 3537 struct ssh_channel *c;
51470298 3538 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 3539 if (c) {
5471d09a 3540 int bufsize;
32874aea 3541 switch (c->type) {
3542 case CHAN_X11:
d8baa528 3543 bufsize = x11_send(c->u.x11.s, (char *)p, len);
9c964e85 3544 break;
d74d141c 3545 case CHAN_SOCKDATA:
d8baa528 3546 bufsize = pfd_send(c->u.pfd.s, (char *)p, len);
bc240b21 3547 break;
32874aea 3548 case CHAN_AGENT:
3549 /* Data for an agent message. Buffer it. */
3550 while (len > 0) {
3551 if (c->u.a.lensofar < 4) {
3552 int l = min(4 - c->u.a.lensofar, len);
3553 memcpy(c->u.a.msglen + c->u.a.lensofar, p,
3554 l);
3555 p += l;
3556 len -= l;
3557 c->u.a.lensofar += l;
3558 }
3559 if (c->u.a.lensofar == 4) {
3560 c->u.a.totallen =
3561 4 + GET_32BIT(c->u.a.msglen);
3d88e64d 3562 c->u.a.message = snewn(c->u.a.totallen,
3563 unsigned char);
32874aea 3564 memcpy(c->u.a.message, c->u.a.msglen, 4);
3565 }
3566 if (c->u.a.lensofar >= 4 && len > 0) {
3567 int l =
3568 min(c->u.a.totallen - c->u.a.lensofar,
3569 len);
3570 memcpy(c->u.a.message + c->u.a.lensofar, p,
3571 l);
3572 p += l;
3573 len -= l;
3574 c->u.a.lensofar += l;
3575 }
3576 if (c->u.a.lensofar == c->u.a.totallen) {
3577 void *reply, *sentreply;
3578 int replylen;
3579 agent_query(c->u.a.message,
3580 c->u.a.totallen, &reply,
3581 &replylen);
3582 if (reply)
3583 sentreply = reply;
3584 else {
3585 /* Fake SSH_AGENT_FAILURE. */
3586 sentreply = "\0\0\0\1\5";
3587 replylen = 5;
3588 }
51470298 3589 send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
32874aea 3590 PKT_INT, c->remoteid,
3591 PKT_INT, replylen,
3592 PKT_DATA, sentreply, replylen,
3593 PKT_END);
3594 if (reply)
3595 sfree(reply);
3596 sfree(c->u.a.message);
3597 c->u.a.lensofar = 0;
3598 }
3599 }
5471d09a 3600 bufsize = 0; /* agent channels never back up */
32874aea 3601 break;
3602 }
90347b95 3603 if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
5471d09a 3604 c->v.v1.throttling = 1;
51470298 3605 ssh1_throttle(ssh, +1);
5471d09a 3606 }
32874aea 3607 }
51470298 3608 } else if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
972a41c8 3609 /* may be from EXEC_SHELL on some servers */
51470298 3610 } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
972a41c8 3611 /* may be from EXEC_SHELL on some servers
374330e2 3612 * if no pty is available or in other odd cases. Ignore */
51470298 3613 } else if (ssh->pktin.type == SSH1_SMSG_EXIT_STATUS) {
d8d6c7e5 3614 char buf[100];
51470298 3615 ssh->exitcode = GET_32BIT(ssh->pktin.body);
d8d6c7e5 3616 sprintf(buf, "Server sent command exit status %d",
51470298 3617 ssh->exitcode);
d8d6c7e5 3618 logevent(buf);
51470298 3619 send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
4252c9cc 3620 /*
3621 * In case `helpful' firewalls or proxies tack
3622 * extra human-readable text on the end of the
3623 * session which we might mistake for another
3624 * encrypted packet, we close the session once
3625 * we've sent EXIT_CONFIRMATION.
3626 */
3bb2f322 3627 ssh_closing((Plug)ssh, NULL, 0, 0);
4252c9cc 3628 crReturnV;
374330e2 3629 } else {
6b5cf8b4 3630 bombout(("Strange packet received: type %d", ssh->pktin.type));
32874aea 3631 crReturnV;
374330e2 3632 }
3633 } else {
8df7a775 3634 while (inlen > 0) {
3635 int len = min(inlen, 512);
51470298 3636 send_packet(ssh, SSH1_CMSG_STDIN_DATA,
8df7a775 3637 PKT_INT, len, PKT_DATA, in, len, PKT_END);
3638 in += len;
3639 inlen -= len;
3640 }
374330e2 3641 }
3642 }
3643
3644 crFinishV;
3645}
3646
3647/*
e5574168 3648 * Utility routine for decoding comma-separated strings in KEXINIT.
3649 */
32874aea 3650static int in_commasep_string(char *needle, char *haystack, int haylen)
3651{
57356d63 3652 int needlen;
3653 if (!needle || !haystack) /* protect against null pointers */
3654 return 0;
3655 needlen = strlen(needle);
e5574168 3656 while (1) {
32874aea 3657 /*
3658 * Is it at the start of the string?
3659 */
3660 if (haylen >= needlen && /* haystack is long enough */
3661 !memcmp(needle, haystack, needlen) && /* initial match */
3662 (haylen == needlen || haystack[needlen] == ',')
3663 /* either , or EOS follows */
3664 )
3665 return 1;
3666 /*
3667 * If not, search for the next comma and resume after that.
3668 * If no comma found, terminate.
3669 */
3670 while (haylen > 0 && *haystack != ',')
3671 haylen--, haystack++;
3672 if (haylen == 0)
3673 return 0;
3674 haylen--, haystack++; /* skip over comma itself */
e5574168 3675 }
3676}
3677
3678/*
d39f364a 3679 * SSH2 key creation method.
3680 */
d8baa528 3681static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
3682 unsigned char *sessid, char chr,
3683 unsigned char *keyspace)
32874aea 3684{
d39f364a 3685 SHA_State s;
3686 /* First 20 bytes. */
3687 SHA_Init(&s);
51470298 3688 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
088bde77 3689 sha_mpint(&s, K);
d39f364a 3690 SHA_Bytes(&s, H, 20);
3691 SHA_Bytes(&s, &chr, 1);
5e0d7cb8 3692 SHA_Bytes(&s, sessid, 20);
d39f364a 3693 SHA_Final(&s, keyspace);
3694 /* Next 20 bytes. */
3695 SHA_Init(&s);
51470298 3696 if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
088bde77 3697 sha_mpint(&s, K);
d39f364a 3698 SHA_Bytes(&s, H, 20);
3699 SHA_Bytes(&s, keyspace, 20);
32874aea 3700 SHA_Final(&s, keyspace + 20);
d39f364a 3701}
3702
3703/*
7cca0d81 3704 * Handle the SSH2 transport layer.
e5574168 3705 */
51470298 3706static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
e5574168 3707{
51470298 3708 struct do_ssh2_transport_state {
3709 int nbits, pbits, warn;
3710 Bignum p, g, e, f, K;
3711 int kex_init_value, kex_reply_value;
3712 const struct ssh_mac **maclist;
3713 int nmacs;
3714 const struct ssh2_cipher *cscipher_tobe;
3715 const struct ssh2_cipher *sccipher_tobe;
3716 const struct ssh_mac *csmac_tobe;
3717 const struct ssh_mac *scmac_tobe;
3718 const struct ssh_compress *cscomp_tobe;
3719 const struct ssh_compress *sccomp_tobe;
3720 char *hostkeydata, *sigdata, *keystr, *fingerprint;
3721 int hostkeylen, siglen;
3722 void *hkey; /* actual host key */
3723 unsigned char exchange_hash[20];
3724 int n_preferred_ciphers;
3725 const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
3726 const struct ssh_compress *preferred_comp;
3727 int first_kex;
3728 };
3729 crState(do_ssh2_transport_state);
3730
3731 crBegin(ssh->do_ssh2_transport_crstate);
3732
3733 s->cscipher_tobe = s->sccipher_tobe = NULL;
3734 s->csmac_tobe = s->scmac_tobe = NULL;
3735 s->cscomp_tobe = s->sccomp_tobe = NULL;
3736
7cca0d81 3737 random_init();
51470298 3738 s->first_kex = 1;
e5574168 3739
51470298 3740 {
3741 int i;
3742 /*
3743 * Set up the preferred ciphers. (NULL => warn below here)
3744 */
3745 s->n_preferred_ciphers = 0;
3746 for (i = 0; i < CIPHER_MAX; i++) {
86916870 3747 switch (ssh->cfg.ssh_cipherlist[i]) {
51470298 3748 case CIPHER_BLOWFISH:
3749 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
3750 break;
3751 case CIPHER_DES:
86916870 3752 if (ssh->cfg.ssh2_des_cbc) {
51470298 3753 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
3754 }
3755 break;
3756 case CIPHER_3DES:
3757 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
3758 break;
3759 case CIPHER_AES:
3760 s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
3761 break;
3762 case CIPHER_WARN:
3763 /* Flag for later. Don't bother if it's the last in
3764 * the list. */
3765 if (i < CIPHER_MAX - 1) {
3766 s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
3767 }
3768 break;
ca20bfcf 3769 }
ca20bfcf 3770 }
5e8358ad 3771 }
ca20bfcf 3772
3773 /*
3774 * Set up preferred compression.
3775 */
86916870 3776 if (ssh->cfg.compression)
51470298 3777 s->preferred_comp = &ssh_zlib;
4ba9b64b 3778 else
51470298 3779 s->preferred_comp = &ssh_comp_none;
5e8358ad 3780
7591b9ff 3781 /*
3782 * Be prepared to work around the buggy MAC problem.
3783 */
51470298 3784 if (ssh->remote_bugs & BUG_SSH2_HMAC)
3785 s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
7591b9ff 3786 else
51470298 3787 s->maclist = macs, s->nmacs = lenof(macs);
7591b9ff 3788
32874aea 3789 begin_key_exchange:
51470298 3790 {
3791 int i, j, cipherstr_started;
3792
3793 /*
3794 * Construct and send our key exchange packet.
3795 */
3796 ssh2_pkt_init(ssh, SSH2_MSG_KEXINIT);
3797 for (i = 0; i < 16; i++)
3798 ssh2_pkt_addbyte(ssh, (unsigned char) random_byte());
3799 /* List key exchange algorithms. */
3800 ssh2_pkt_addstring_start(ssh);
3801 for (i = 0; i < lenof(kex_algs); i++) {
3802 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3803 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3804 continue;
3805 ssh2_pkt_addstring_str(ssh, kex_algs[i]->name);
3806 if (i < lenof(kex_algs) - 1)
3807 ssh2_pkt_addstring_str(ssh, ",");
32874aea 3808 }
51470298 3809 /* List server host key algorithms. */
3810 ssh2_pkt_addstring_start(ssh);
3811 for (i = 0; i < lenof(hostkey_algs); i++) {
3812 ssh2_pkt_addstring_str(ssh, hostkey_algs[i]->name);
3813 if (i < lenof(hostkey_algs) - 1)
3814 ssh2_pkt_addstring_str(ssh, ",");
32874aea 3815 }
51470298 3816 /* List client->server encryption algorithms. */
3817 ssh2_pkt_addstring_start(ssh);
3818 cipherstr_started = 0;
3819 for (i = 0; i < s->n_preferred_ciphers; i++) {
3820 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3821 if (!c) continue; /* warning flag */
3822 for (j = 0; j < c->nciphers; j++) {
3823 if (cipherstr_started)
3824 ssh2_pkt_addstring_str(ssh, ",");
3825 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3826 cipherstr_started = 1;
3827 }
3828 }
3829 /* List server->client encryption algorithms. */
3830 ssh2_pkt_addstring_start(ssh);
3831 cipherstr_started = 0;
3832 for (i = 0; i < s->n_preferred_ciphers; i++) {
3833 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3834 if (!c) continue; /* warning flag */
3835 for (j = 0; j < c->nciphers; j++) {
3836 if (cipherstr_started)
3837 ssh2_pkt_addstring_str(ssh, ",");
3838 ssh2_pkt_addstring_str(ssh, c->list[j]->name);
3839 cipherstr_started = 1;
3840 }
3841 }
3842 /* List client->server MAC algorithms. */
3843 ssh2_pkt_addstring_start(ssh);
3844 for (i = 0; i < s->nmacs; i++) {
3845 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3846 if (i < s->nmacs - 1)
3847 ssh2_pkt_addstring_str(ssh, ",");
3848 }
3849 /* List server->client MAC algorithms. */
3850 ssh2_pkt_addstring_start(ssh);
3851 for (i = 0; i < s->nmacs; i++) {
3852 ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
3853 if (i < s->nmacs - 1)
3854 ssh2_pkt_addstring_str(ssh, ",");
3855 }
3856 /* List client->server compression algorithms. */
3857 ssh2_pkt_addstring_start(ssh);
3858 for (i = 0; i < lenof(compressions) + 1; i++) {
3859 const struct ssh_compress *c =
3860 i == 0 ? s->preferred_comp : compressions[i - 1];
3861 ssh2_pkt_addstring_str(ssh, c->name);
3862 if (i < lenof(compressions))
3863 ssh2_pkt_addstring_str(ssh, ",");
3864 }
3865 /* List server->client compression algorithms. */
3866 ssh2_pkt_addstring_start(ssh);
3867 for (i = 0; i < lenof(compressions) + 1; i++) {
3868 const struct ssh_compress *c =
3869 i == 0 ? s->preferred_comp : compressions[i - 1];
3870 ssh2_pkt_addstring_str(ssh, c->name);
3871 if (i < lenof(compressions))
3872 ssh2_pkt_addstring_str(ssh, ",");
3873 }
3874 /* List client->server languages. Empty list. */
3875 ssh2_pkt_addstring_start(ssh);
3876 /* List server->client languages. Empty list. */
3877 ssh2_pkt_addstring_start(ssh);
3878 /* First KEX packet does _not_ follow, because we're not that brave. */
3879 ssh2_pkt_addbool(ssh, FALSE);
3880 /* Reserved. */
3881 ssh2_pkt_adduint32(ssh, 0);
e5574168 3882 }
0db56f73 3883
51470298 3884 ssh->exhash = ssh->exhashbase;
3885 sha_string(&ssh->exhash, ssh->pktout.data + 5, ssh->pktout.length - 5);
0db56f73 3886
51470298 3887 ssh2_pkt_send(ssh);
e5574168 3888
32874aea 3889 if (!ispkt)
3890 crWaitUntil(ispkt);
57356d63 3891 if (ssh->pktin.length > 5)
3892 sha_string(&ssh->exhash, ssh->pktin.data + 5, ssh->pktin.length - 5);
e5574168 3893
3894 /*
3895 * Now examine the other side's KEXINIT to see what we're up
3896 * to.
3897 */
51470298 3898 {
3899 char *str;
3900 int i, j, len;
3901
3902 if (ssh->pktin.type != SSH2_MSG_KEXINIT) {
6b5cf8b4 3903 bombout(("expected key exchange packet from server"));
51470298 3904 crReturn(0);
32874aea 3905 }
51470298 3906 ssh->kex = NULL;
3907 ssh->hostkey = NULL;
3908 s->cscipher_tobe = NULL;
3909 s->sccipher_tobe = NULL;
3910 s->csmac_tobe = NULL;
3911 s->scmac_tobe = NULL;
3912 s->cscomp_tobe = NULL;
3913 s->sccomp_tobe = NULL;
3914 ssh->pktin.savedpos += 16; /* skip garbage cookie */
3915 ssh2_pkt_getstring(ssh, &str, &len); /* key exchange algorithms */
3916 for (i = 0; i < lenof(kex_algs); i++) {
3917 if (kex_algs[i] == &ssh_diffiehellman_gex &&
3918 (ssh->remote_bugs & BUG_SSH2_DH_GEX))
3919 continue;
3920 if (in_commasep_string(kex_algs[i]->name, str, len)) {
3921 ssh->kex = kex_algs[i];
3922 break;
3923 }
32874aea 3924 }
51470298 3925 ssh2_pkt_getstring(ssh, &str, &len); /* host key algorithms */
3926 for (i = 0; i < lenof(hostkey_algs); i++) {
3927 if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
3928 ssh->hostkey = hostkey_algs[i];
3929 break;
3930 }
3931 }
3932 ssh2_pkt_getstring(ssh, &str, &len); /* client->server cipher */
3933 s->warn = 0;
3934 for (i = 0; i < s->n_preferred_ciphers; i++) {
3935 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3936 if (!c) {
3937 s->warn = 1;
3938 } else {
3939 for (j = 0; j < c->nciphers; j++) {
3940 if (in_commasep_string(c->list[j]->name, str, len)) {
3941 s->cscipher_tobe = c->list[j];
3942 break;
3943 }
ca20bfcf 3944 }
32874aea 3945 }
51470298 3946 if (s->cscipher_tobe) {
3947 if (s->warn)
a8327734 3948 askcipher(ssh->frontend, s->cscipher_tobe->name, 1);
51470298 3949 break;
3950 }
32874aea 3951 }
51470298 3952 if (!s->cscipher_tobe) {
6b5cf8b4 3953 bombout(("Couldn't agree a client-to-server cipher (available: %s)",
57356d63 3954 str ? str : "(null)"));
51470298 3955 crReturn(0);
ca20bfcf 3956 }
0ef8f407 3957
51470298 3958 ssh2_pkt_getstring(ssh, &str, &len); /* server->client cipher */
3959 s->warn = 0;
3960 for (i = 0; i < s->n_preferred_ciphers; i++) {
3961 const struct ssh2_ciphers *c = s->preferred_ciphers[i];
3962 if (!c) {
3963 s->warn = 1;
3964 } else {
3965 for (j = 0; j < c->nciphers; j++) {
3966 if (in_commasep_string(c->list[j]->name, str, len)) {
3967 s->sccipher_tobe = c->list[j];
3968 break;
3969 }
ca20bfcf 3970 }
32874aea 3971 }
51470298 3972 if (s->sccipher_tobe) {
3973 if (s->warn)
a8327734 3974 askcipher(ssh->frontend, s->sccipher_tobe->name, 2);
51470298 3975 break;
3976 }
32874aea 3977 }
51470298 3978 if (!s->sccipher_tobe) {
6b5cf8b4 3979 bombout(("Couldn't agree a server-to-client cipher (available: %s)",
57356d63 3980 str ? str : "(null)"));
51470298 3981 crReturn(0);
ca20bfcf 3982 }
0ef8f407 3983
51470298 3984 ssh2_pkt_getstring(ssh, &str, &len); /* client->server mac */
3985 for (i = 0; i < s->nmacs; i++) {
3986 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3987 s->csmac_tobe = s->maclist[i];
3988 break;
3989 }
32874aea 3990 }
51470298 3991 ssh2_pkt_getstring(ssh, &str, &len); /* server->client mac */
3992 for (i = 0; i < s->nmacs; i++) {
3993 if (in_commasep_string(s->maclist[i]->name, str, len)) {
3994 s->scmac_tobe = s->maclist[i];
3995 break;
3996 }
32874aea 3997 }
51470298 3998 ssh2_pkt_getstring(ssh, &str, &len); /* client->server compression */
3999 for (i = 0; i < lenof(compressions) + 1; i++) {
4000 const struct ssh_compress *c =
4001 i == 0 ? s->preferred_comp : compressions[i - 1];
4002 if (in_commasep_string(c->name, str, len)) {
4003 s->cscomp_tobe = c;
4004 break;
4005 }
32874aea 4006 }
51470298 4007 ssh2_pkt_getstring(ssh, &str, &len); /* server->client compression */
4008 for (i = 0; i < lenof(compressions) + 1; i++) {
4009 const struct ssh_compress *c =
4010 i == 0 ? s->preferred_comp : compressions[i - 1];
4011 if (in_commasep_string(c->name, str, len)) {
4012 s->sccomp_tobe = c;
4013 break;
4014 }
32874aea 4015 }
e5574168 4016 }
e5574168 4017
4018 /*
7bd5a860 4019 * Work out the number of bits of key we will need from the key
4020 * exchange. We start with the maximum key length of either
4021 * cipher...
4022 */
4023 {
32874aea 4024 int csbits, scbits;
7bd5a860 4025
51470298 4026 csbits = s->cscipher_tobe->keylen;
4027 scbits = s->sccipher_tobe->keylen;
4028 s->nbits = (csbits > scbits ? csbits : scbits);
7bd5a860 4029 }
4030 /* The keys only have 160-bit entropy, since they're based on
4031 * a SHA-1 hash. So cap the key size at 160 bits. */
51470298 4032 if (s->nbits > 160)
4033 s->nbits = 160;
7bd5a860 4034
4035 /*
a92dd380 4036 * If we're doing Diffie-Hellman group exchange, start by
4037 * requesting a group.
e5574168 4038 */
51470298 4039 if (ssh->kex == &ssh_diffiehellman_gex) {
32874aea 4040 logevent("Doing Diffie-Hellman group exchange");
51470298 4041 ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
32874aea 4042 /*
4043 * Work out how big a DH group we will need to allow that
4044 * much data.
7bd5a860 4045 */
51470298 4046 s->pbits = 512 << ((s->nbits - 1) / 64);
4047 ssh2_pkt_init(ssh, SSH2_MSG_KEX_DH_GEX_REQUEST);
4048 ssh2_pkt_adduint32(ssh, s->pbits);
4049 ssh2_pkt_send(ssh);
32874aea 4050
4051 crWaitUntil(ispkt);
51470298 4052 if (ssh->pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
6b5cf8b4 4053 bombout(("expected key exchange group packet from server"));
32874aea 4054 crReturn(0);
4055 }
51470298 4056 s->p = ssh2_pkt_getmp(ssh);
4057 s->g = ssh2_pkt_getmp(ssh);
27cd7fc2 4058 ssh->kex_ctx = dh_setup_group(s->p, s->g);
51470298 4059 s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
4060 s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
a92dd380 4061 } else {
51470298 4062 ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
27cd7fc2 4063 ssh->kex_ctx = dh_setup_group1();
51470298 4064 s->kex_init_value = SSH2_MSG_KEXDH_INIT;
4065 s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
8d5de777 4066 }
e5574168 4067
a92dd380 4068 logevent("Doing Diffie-Hellman key exchange");
e5574168 4069 /*
a92dd380 4070 * Now generate and send e for Diffie-Hellman.
e5574168 4071 */
27cd7fc2 4072 s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
51470298 4073 ssh2_pkt_init(ssh, s->kex_init_value);
4074 ssh2_pkt_addmp(ssh, s->e);
4075 ssh2_pkt_send(ssh);
e5574168 4076
4077 crWaitUntil(ispkt);
51470298 4078 if (ssh->pktin.type != s->kex_reply_value) {
6b5cf8b4 4079 bombout(("expected key exchange reply packet from server"));
32874aea 4080 crReturn(0);
7cca0d81 4081 }
51470298 4082 ssh2_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
4083 s->f = ssh2_pkt_getmp(ssh);
4084 ssh2_pkt_getstring(ssh, &s->sigdata, &s->siglen);
e5574168 4085
27cd7fc2 4086 s->K = dh_find_K(ssh->kex_ctx, s->f);
e5574168 4087
51470298 4088 sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
4089 if (ssh->kex == &ssh_diffiehellman_gex) {
4090 sha_uint32(&ssh->exhash, s->pbits);
4091 sha_mpint(&ssh->exhash, s->p);
4092 sha_mpint(&ssh->exhash, s->g);
a92dd380 4093 }
51470298 4094 sha_mpint(&ssh->exhash, s->e);
4095 sha_mpint(&ssh->exhash, s->f);
4096 sha_mpint(&ssh->exhash, s->K);
4097 SHA_Final(&ssh->exhash, s->exchange_hash);
e5574168 4098
27cd7fc2 4099 dh_cleanup(ssh->kex_ctx);
fabd1805 4100 ssh->kex_ctx = NULL;
3709bfe9 4101
7cca0d81 4102#if 0
765c4200 4103 debug(("Exchange hash is:\n"));
51470298 4104 dmemdump(s->exchange_hash, 20);
7cca0d81 4105#endif
4106
51470298 4107 s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
4108 if (!s->hkey ||
4109 !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
d8baa528 4110 (char *)s->exchange_hash, 20)) {
6b5cf8b4 4111 bombout(("Server's host key did not match the signature supplied"));
32874aea 4112 crReturn(0);
8d5de777 4113 }
e5574168 4114
4115 /*
7cca0d81 4116 * Authenticate remote host: verify host key. (We've already
4117 * checked the signature of the exchange hash.)
e5574168 4118 */
51470298 4119 s->keystr = ssh->hostkey->fmtkey(s->hkey);
4120 s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
a8327734 4121 verify_ssh_host_key(ssh->frontend,
4122 ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
51470298 4123 s->keystr, s->fingerprint);
4124 if (s->first_kex) { /* don't bother logging this in rekeys */
5e0d7cb8 4125 logevent("Host key fingerprint is:");
51470298 4126 logevent(s->fingerprint);
5e0d7cb8 4127 }
51470298 4128 sfree(s->fingerprint);
4129 sfree(s->keystr);
4130 ssh->hostkey->freekey(s->hkey);
d39f364a 4131
4132 /*
7cca0d81 4133 * Send SSH2_MSG_NEWKEYS.
d39f364a 4134 */
51470298 4135 ssh2_pkt_init(ssh, SSH2_MSG_NEWKEYS);
4136 ssh2_pkt_send(ssh);
d39f364a 4137
4138 /*
8406eaf9 4139 * Expect SSH2_MSG_NEWKEYS from server.
4140 */
4141 crWaitUntil(ispkt);
51470298 4142 if (ssh->pktin.type != SSH2_MSG_NEWKEYS) {
6b5cf8b4 4143 bombout(("expected new-keys packet from server"));
8406eaf9 4144 crReturn(0);
4145 }
4146
4147 /*
d39f364a 4148 * Create and initialise session keys.
4149 */
371e569c 4150 if (ssh->cs_cipher_ctx)
4151 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
51470298 4152 ssh->cscipher = s->cscipher_tobe;
371e569c 4153 ssh->cs_cipher_ctx = ssh->cscipher->make_context();
e0e1a00d 4154
371e569c 4155 if (ssh->sc_cipher_ctx)
4156 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
51470298 4157 ssh->sccipher = s->sccipher_tobe;
371e569c 4158 ssh->sc_cipher_ctx = ssh->sccipher->make_context();
e0e1a00d 4159
4160 if (ssh->cs_mac_ctx)
4161 ssh->csmac->free_context(ssh->cs_mac_ctx);
51470298 4162 ssh->csmac = s->csmac_tobe;
e0e1a00d 4163 ssh->cs_mac_ctx = ssh->csmac->make_context();
4164
4165 if (ssh->sc_mac_ctx)
4166 ssh->scmac->free_context(ssh->sc_mac_ctx);
51470298 4167 ssh->scmac = s->scmac_tobe;
e0e1a00d 4168 ssh->sc_mac_ctx = ssh->scmac->make_context();
4169
5366aed8 4170 if (ssh->cs_comp_ctx)
4171 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
51470298 4172 ssh->cscomp = s->cscomp_tobe;
5366aed8 4173 ssh->cs_comp_ctx = ssh->cscomp->compress_init();
4174
4175 if (ssh->sc_comp_ctx)
4176 ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
51470298 4177 ssh->sccomp = s->sccomp_tobe;
5366aed8 4178 ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
4179
d39f364a 4180 /*
5e0d7cb8 4181 * Set IVs after keys. Here we use the exchange hash from the
4182 * _first_ key exchange.
d39f364a 4183 */
51470298 4184 {
4185 unsigned char keyspace[40];
4186 if (s->first_kex)
4187 memcpy(ssh->v2_session_id, s->exchange_hash,
4188 sizeof(s->exchange_hash));
4189 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
371e569c 4190 ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
51470298 4191 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
371e569c 4192 ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
51470298 4193 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
371e569c 4194 ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
51470298 4195 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
371e569c 4196 ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
51470298 4197 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
e0e1a00d 4198 ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
51470298 4199 ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
e0e1a00d 4200 ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
51470298 4201 }
57356d63 4202 logeventf(ssh, "Initialised %.200s client->server encryption",
4203 ssh->cscipher->text_name);
4204 logeventf(ssh, "Initialised %.200s server->client encryption",
4205 ssh->sccipher->text_name);
4206 if (ssh->cscomp->text_name)
4207 logeventf(ssh, "Initialised %s compression",
4208 ssh->cscomp->text_name);
4209 if (ssh->sccomp->text_name)
4210 logeventf(ssh, "Initialised %s decompression",
4211 ssh->sccomp->text_name);
d39f364a 4212
033b4cef 4213 /*
0db56f73 4214 * If this is the first key exchange phase, we must pass the
4215 * SSH2_MSG_NEWKEYS packet to the next layer, not because it
4216 * wants to see it but because it will need time to initialise
4217 * itself before it sees an actual packet. In subsequent key
4218 * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
4219 * it would only confuse the layer above.
4220 */
51470298 4221 if (!s->first_kex) {
32874aea 4222 crReturn(0);
0db56f73 4223 }
51470298 4224 s->first_kex = 0;
0db56f73 4225
4226 /*
7cca0d81 4227 * Now we're encrypting. Begin returning 1 to the protocol main
4228 * function so that other things can run on top of the
4229 * transport. If we ever see a KEXINIT, we must go back to the
4230 * start.
033b4cef 4231 */
51470298 4232 while (!(ispkt && ssh->pktin.type == SSH2_MSG_KEXINIT)) {
32874aea 4233 crReturn(1);
e96adf72 4234 }
5e0d7cb8 4235 logevent("Server initiated key re-exchange");
7cca0d81 4236 goto begin_key_exchange;
e5574168 4237
4238 crFinish(1);
4239}
4240
7cca0d81 4241/*
783415f8 4242 * Add data to an SSH2 channel output buffer.
4243 */
32874aea 4244static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
4245 int len)
4246{
5471d09a 4247 bufchain_add(&c->v.v2.outbuffer, buf, len);
783415f8 4248}
4249
4250/*
4251 * Attempt to send data on an SSH2 channel.
4252 */
5471d09a 4253static int ssh2_try_send(struct ssh_channel *c)
32874aea 4254{
51470298 4255 Ssh ssh = c->ssh;
4256
5471d09a 4257 while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
4258 int len;
4259 void *data;
4260 bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
4261 if ((unsigned)len > c->v.v2.remwindow)
4262 len = c->v.v2.remwindow;
4263 if ((unsigned)len > c->v.v2.remmaxpkt)
4264 len = c->v.v2.remmaxpkt;
51470298 4265 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_DATA);
4266 ssh2_pkt_adduint32(ssh, c->remoteid);
4267 ssh2_pkt_addstring_start(ssh);
4268 ssh2_pkt_addstring_data(ssh, data, len);
4269 ssh2_pkt_send(ssh);
5471d09a 4270 bufchain_consume(&c->v.v2.outbuffer, len);
4271 c->v.v2.remwindow -= len;
4272 }
4273
4274 /*
4275 * After having sent as much data as we can, return the amount
4276 * still buffered.
4277 */
4278 return bufchain_size(&c->v.v2.outbuffer);
4279}
4280
4281/*
4282 * Potentially enlarge the window on an SSH2 channel.
4283 */
4284static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
4285{
51470298 4286 Ssh ssh = c->ssh;
4287
6b69f42e 4288 /*
4289 * Never send WINDOW_ADJUST for a channel that the remote side
4290 * already thinks it's closed; there's no point, since it won't
4291 * be sending any more data anyway.
4292 */
4293 if (c->closes != 0)
4294 return;
4295
5471d09a 4296 if (newwin > c->v.v2.locwindow) {
51470298 4297 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST);
4298 ssh2_pkt_adduint32(ssh, c->remoteid);
4299 ssh2_pkt_adduint32(ssh, newwin - c->v.v2.locwindow);
4300 ssh2_pkt_send(ssh);
5471d09a 4301 c->v.v2.locwindow = newwin;
783415f8 4302 }
4303}
4304
4305/*
7cca0d81 4306 * Handle the SSH2 userauth and connection layers.
4307 */
51470298 4308static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
7cca0d81 4309{
51470298 4310 struct do_ssh2_authconn_state {
4311 enum {
4312 AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
4313 AUTH_PASSWORD,
4314 AUTH_KEYBOARD_INTERACTIVE
4315 } method;
4316 enum {
4317 AUTH_TYPE_NONE,
4318 AUTH_TYPE_PUBLICKEY,
4319 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
4320 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
4321 AUTH_TYPE_PASSWORD,
4322 AUTH_TYPE_KEYBOARD_INTERACTIVE,
4323 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
4324 } type;
4325 int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
4326 int tried_pubkey_config, tried_agent, tried_keyb_inter;
4327 int kbd_inter_running;
4328 int we_are_in;
4329 int num_prompts, curr_prompt, echo;
4330 char username[100];
4331 int got_username;
4332 char pwprompt[200];
4333 char password[100];
4334 void *publickey_blob;
4335 int publickey_bloblen;
4336 unsigned char request[5], *response, *p;
4337 int responselen;
4338 int keyi, nkeys;
4339 int authed;
4340 char *pkblob, *alg, *commentp;
4341 int pklen, alglen, commentlen;
4342 int siglen, retlen, len;
4343 char *q, *agentreq, *ret;
4344 int try_send;
4345 };
4346 crState(do_ssh2_authconn_state);
4347
4348 crBegin(ssh->do_ssh2_authconn_crstate);
e5574168 4349
7cca0d81 4350 /*
4351 * Request userauth protocol, and await a response to it.
4352 */
51470298 4353 ssh2_pkt_init(ssh, SSH2_MSG_SERVICE_REQUEST);
4354 ssh2_pkt_addstring(ssh, "ssh-userauth");
4355 ssh2_pkt_send(ssh);
7cca0d81 4356 crWaitUntilV(ispkt);
51470298 4357 if (ssh->pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
6b5cf8b4 4358 bombout(("Server refused user authentication protocol"));
32874aea 4359 crReturnV;
8d5de777 4360 }
7cca0d81 4361
4362 /*
1408a877 4363 * We repeat this whole loop, including the username prompt,
4364 * until we manage a successful authentication. If the user
51470298 4365 * types the wrong _password_, they can be sent back to the
4366 * beginning to try another username, if this is configured on.
4367 * (If they specify a username in the config, they are never
4368 * asked, even if they do give a wrong password.)
1408a877 4369 *
4370 * I think this best serves the needs of
4371 *
4372 * - the people who have no configuration, no keys, and just
4373 * want to try repeated (username,password) pairs until they
4374 * type both correctly
4375 *
4376 * - people who have keys and configuration but occasionally
4377 * need to fall back to passwords
4378 *
4379 * - people with a key held in Pageant, who might not have
4380 * logged in to a particular machine before; so they want to
4381 * type a username, and then _either_ their key will be
4382 * accepted, _or_ they will type a password. If they mistype
4383 * the username they will want to be able to get back and
4384 * retype it!
7cca0d81 4385 */
51470298 4386 s->username[0] = '\0';
4387 s->got_username = FALSE;
1408a877 4388 do {
1408a877 4389 /*
4390 * Get a username.
4391 */
86916870 4392 if (s->got_username && !ssh->cfg.change_username) {
5bb641e1 4393 /*
4394 * We got a username last time round this loop, and
4395 * with change_username turned off we don't try to get
4396 * it again.
4397 */
86916870 4398 } else if ((flags & FLAG_INTERACTIVE) && !*ssh->cfg.username) {
c0a81592 4399 if (ssh_get_line && !ssh_getline_pw_only) {
32874aea 4400 if (!ssh_get_line("login as: ",
51470298 4401 s->username, sizeof(s->username), FALSE)) {
32874aea 4402 /*
4403 * get_line failed to get a username.
4404 * Terminate.
4405 */
4406 logevent("No username provided. Abandoning session.");
3bb2f322 4407 ssh_closing((Plug)ssh, NULL, 0, 0);
32874aea 4408 crReturnV;
4409 }
4410 } else {
51470298 4411 int ret; /* need not be saved across crReturn */
4412 c_write_str(ssh, "login as: ");
4413 ssh->send_ok = 1;
4414 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
0405e71f 4415 do {
32874aea 4416 crWaitUntilV(!ispkt);
51470298 4417 ret = process_userpass_input(ssh, in, inlen);
0405e71f 4418 } while (ret == 0);
4419 if (ret < 0)
4420 cleanup_exit(0);
4ca0c9d1 4421 c_write_str(ssh, "\r\n");
32874aea 4422 }
51470298 4423 s->username[strcspn(s->username, "\n\r")] = '\0';
7cca0d81 4424 } else {
57356d63 4425 char *stuff;
86916870 4426 strncpy(s->username, ssh->cfg.username, sizeof(s->username));
51470298 4427 s->username[sizeof(s->username)-1] = '\0';
65a22376 4428 if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
57356d63 4429 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
51470298 4430 c_write_str(ssh, stuff);
57356d63 4431 sfree(stuff);
7cca0d81 4432 }
4433 }
51470298 4434 s->got_username = TRUE;
7cca0d81 4435
65a22376 4436 /*
1408a877 4437 * Send an authentication request using method "none": (a)
4438 * just in case it succeeds, and (b) so that we know what
4439 * authentication methods we can usefully try next.
65a22376 4440 */
51470298 4441 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4442
4443 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4444 ssh2_pkt_addstring(ssh, s->username);
4445 ssh2_pkt_addstring(ssh, "ssh-connection");/* service requested */
4446 ssh2_pkt_addstring(ssh, "none"); /* method */
4447 ssh2_pkt_send(ssh);
4448 s->type = AUTH_TYPE_NONE;
4449 s->gotit = FALSE;
4450 s->we_are_in = FALSE;
4451
4452 s->tried_pubkey_config = FALSE;
4453 s->tried_agent = FALSE;
4454 s->tried_keyb_inter = FALSE;
4455 s->kbd_inter_running = FALSE;
86916870 4456 /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
9a30e26b 4457 if (!filename_is_null(ssh->cfg.keyfile)) {
231ee168 4458 int keytype;
6c6d9ed9 4459 logeventf(ssh, "Reading private key file \"%.150s\"",
4460 filename_to_str(&ssh->cfg.keyfile));
9a30e26b 4461 keytype = key_type(&ssh->cfg.keyfile);
51470298 4462 if (keytype == SSH_KEYTYPE_SSH2) {
4463 s->publickey_blob =
9a30e26b 4464 ssh2_userkey_loadpub(&ssh->cfg.keyfile, NULL,
51470298 4465 &s->publickey_bloblen);
4466 } else {
57356d63 4467 char *msgbuf;
c2ad7d0d 4468 logeventf(ssh, "Unable to use this key file (%s)",
a8327734 4469 key_type_to_str(keytype));
57356d63 4470 msgbuf = dupprintf("Unable to use key file \"%.150s\""
6c6d9ed9 4471 " (%s)\r\n",
4472 filename_to_str(&ssh->cfg.keyfile),
57356d63 4473 key_type_to_str(keytype));
51470298 4474 c_write_str(ssh, msgbuf);
57356d63 4475 sfree(msgbuf);
51470298 4476 s->publickey_blob = NULL;
231ee168 4477 }
396778f1 4478 } else
51470298 4479 s->publickey_blob = NULL;
65a22376 4480
1408a877 4481 while (1) {
4482 /*
4483 * Wait for the result of the last authentication request.
4484 */
51470298 4485 if (!s->gotit)
1408a877 4486 crWaitUntilV(ispkt);
51470298 4487 while (ssh->pktin.type == SSH2_MSG_USERAUTH_BANNER) {
32874aea 4488 char *banner;
4489 int size;
4490 /*
4491 * Don't show the banner if we're operating in
4492 * non-verbose non-interactive mode. (It's probably
4493 * a script, which means nobody will read the
4494 * banner _anyway_, and moreover the printing of
4495 * the banner will screw up processing on the
4496 * output of (say) plink.)
4497 */
4498 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
51470298 4499 ssh2_pkt_getstring(ssh, &banner, &size);
32874aea 4500 if (banner)
51470298 4501 c_write_untrusted(ssh, banner, size);
32874aea 4502 }
1408a877 4503 crWaitUntilV(ispkt);
4504 }
51470298 4505 if (ssh->pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
1408a877 4506 logevent("Access granted");
51470298 4507 s->we_are_in = TRUE;
1408a877 4508 break;
4509 }
65a22376 4510
51470298 4511 if (s->kbd_inter_running &&
4512 ssh->pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
b3186d64 4513 /*
45068b27 4514 * This is either a further set-of-prompts packet
4515 * in keyboard-interactive authentication, or it's
4516 * the same one and we came back here with `gotit'
4517 * set. In the former case, we must reset the
4518 * curr_prompt variable.
b3186d64 4519 */
51470298 4520 if (!s->gotit)
4521 s->curr_prompt = 0;
4522 } else if (ssh->pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
6b5cf8b4 4523 bombout(("Strange packet received during authentication: type %d",
51470298 4524 ssh->pktin.type));
38c4a8da 4525 crReturnV;
65a22376 4526 }
4527
51470298 4528 s->gotit = FALSE;
65a22376 4529
1408a877 4530 /*
4531 * OK, we're now sitting on a USERAUTH_FAILURE message, so
4532 * we can look at the string in it and know what we can
4533 * helpfully try next.
4534 */
51470298 4535 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
1408a877 4536 char *methods;
4537 int methlen;
51470298 4538 ssh2_pkt_getstring(ssh, &methods, &methlen);
4539 s->kbd_inter_running = FALSE;
4540 if (!ssh2_pkt_getbool(ssh)) {
1408a877 4541 /*
4542 * We have received an unequivocal Access
4543 * Denied. This can translate to a variety of
4544 * messages:
4545 *
4546 * - if we'd just tried "none" authentication,
4547 * it's not worth printing anything at all
4548 *
4549 * - if we'd just tried a public key _offer_,
4550 * the message should be "Server refused our
4551 * key" (or no message at all if the key
4552 * came from Pageant)
4553 *
4554 * - if we'd just tried anything else, the
4555 * message really should be "Access denied".
4556 *
4557 * Additionally, if we'd just tried password
4558 * authentication, we should break out of this
4559 * whole loop so as to go back to the username
4560 * prompt.
4561 */
51470298 4562 if (s->type == AUTH_TYPE_NONE) {
1408a877 4563 /* do nothing */
51470298 4564 } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
4565 s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
4566 if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
4567 c_write_str(ssh, "Server refused our key\r\n");
1408a877 4568 logevent("Server refused public key");
51470298 4569 } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
4bdf7c46 4570 /* server declined keyboard-interactive; ignore */
1408a877 4571 } else {
51470298 4572 c_write_str(ssh, "Access denied\r\n");
1408a877 4573 logevent("Access denied");
51470298 4574 if (s->type == AUTH_TYPE_PASSWORD) {
4575 s->we_are_in = FALSE;
1408a877 4576 break;
4577 }
4578 }
4579 } else {
51470298 4580 c_write_str(ssh, "Further authentication required\r\n");
1408a877 4581 logevent("Further authentication required");
4582 }
65a22376 4583
51470298 4584 s->can_pubkey =
32874aea 4585 in_commasep_string("publickey", methods, methlen);
51470298 4586 s->can_passwd =
32874aea 4587 in_commasep_string("password", methods, methlen);
86916870 4588 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
761187b6 4589 in_commasep_string("keyboard-interactive", methods, methlen);
1408a877 4590 }
65a22376 4591
51470298 4592 s->method = 0;
4593 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
65a22376 4594
0405e71f 4595 /*
4596 * Most password/passphrase prompts will be
4597 * non-echoing, so we set this to 0 by default.
4598 * Exception is that some keyboard-interactive prompts
4599 * can be echoing, in which case we'll set this to 1.
4600 */
51470298 4601 s->echo = 0;
0405e71f 4602
51470298 4603 if (!s->method && s->can_pubkey &&
4604 agent_exists() && !s->tried_agent) {
1983e559 4605 /*
4606 * Attempt public-key authentication using Pageant.
4607 */
1983e559 4608 void *r;
51470298 4609 s->authed = FALSE;
1983e559 4610
51470298 4611 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4612 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
00db133f 4613
51470298 4614 s->tried_agent = TRUE;
1983e559 4615
4616 logevent("Pageant is running. Requesting keys.");
4617
4618 /* Request the keys held by the agent. */
51470298 4619 PUT_32BIT(s->request, 1);
4620 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
4621 agent_query(s->request, 5, &r, &s->responselen);
4622 s->response = (unsigned char *) r;
4623 if (s->response && s->responselen >= 5 &&
4624 s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
4625 s->p = s->response + 5;
4626 s->nkeys = GET_32BIT(s->p);
4627 s->p += 4;
32874aea 4628 {
4629 char buf[64];
51470298 4630 sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
32874aea 4631 logevent(buf);
4632 }
51470298 4633 for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
2d466ffd 4634 void *vret;
1983e559 4635
32874aea 4636 {
4637 char buf[64];
51470298 4638 sprintf(buf, "Trying Pageant key #%d", s->keyi);
32874aea 4639 logevent(buf);
4640 }
51470298 4641 s->pklen = GET_32BIT(s->p);
4642 s->p += 4;
4643 if (s->publickey_blob &&
4644 s->pklen == s->publickey_bloblen &&
4645 !memcmp(s->p, s->publickey_blob,
4646 s->publickey_bloblen)) {
396778f1 4647 logevent("This key matches configured key file");
51470298 4648 s->tried_pubkey_config = 1;
396778f1 4649 }
d8baa528 4650 s->pkblob = (char *)s->p;
51470298 4651 s->p += s->pklen;
4652 s->alglen = GET_32BIT(s->pkblob);
4653 s->alg = s->pkblob + 4;
4654 s->commentlen = GET_32BIT(s->p);
4655 s->p += 4;
d8baa528 4656 s->commentp = (char *)s->p;
51470298 4657 s->p += s->commentlen;
4658 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4659 ssh2_pkt_addstring(ssh, s->username);
4660 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4661 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4662 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4663 ssh2_pkt_addstring_start(ssh);
4664 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4665 ssh2_pkt_addstring_start(ssh);
4666 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4667 ssh2_pkt_send(ssh);
1983e559 4668
4669 crWaitUntilV(ispkt);
51470298 4670 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
1983e559 4671 logevent("Key refused");
4672 continue;
4673 }
4674
32874aea 4675 if (flags & FLAG_VERBOSE) {
51470298 4676 c_write_str(ssh, "Authenticating with "
4677 "public key \"");
4678 c_write(ssh, s->commentp, s->commentlen);
4679 c_write_str(ssh, "\" from agent\r\n");
32874aea 4680 }
1983e559 4681
4682 /*
4683 * Server is willing to accept the key.
4684 * Construct a SIGN_REQUEST.
4685 */
51470298 4686 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4687 ssh2_pkt_addstring(ssh, s->username);
4688 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4689 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4690 ssh2_pkt_addbool(ssh, TRUE);
4691 ssh2_pkt_addstring_start(ssh);
4692 ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
4693 ssh2_pkt_addstring_start(ssh);
4694 ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
4695
4696 s->siglen = ssh->pktout.length - 5 + 4 + 20;
dda87a28 4697 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
4698 s->siglen -= 4;
51470298 4699 s->len = 1; /* message type */
4700 s->len += 4 + s->pklen; /* key blob */
4701 s->len += 4 + s->siglen; /* data to sign */
4702 s->len += 4; /* flags */
3d88e64d 4703 s->agentreq = snewn(4 + s->len, char);
51470298 4704 PUT_32BIT(s->agentreq, s->len);
4705 s->q = s->agentreq + 4;
4706 *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
4707 PUT_32BIT(s->q, s->pklen);
4708 s->q += 4;
4709 memcpy(s->q, s->pkblob, s->pklen);
4710 s->q += s->pklen;
4711 PUT_32BIT(s->q, s->siglen);
4712 s->q += 4;
1983e559 4713 /* Now the data to be signed... */
dda87a28 4714 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
4715 PUT_32BIT(s->q, 20);
4716 s->q += 4;
4717 }
51470298 4718 memcpy(s->q, ssh->v2_session_id, 20);
4719 s->q += 20;
4720 memcpy(s->q, ssh->pktout.data + 5,
4721 ssh->pktout.length - 5);
4722 s->q += ssh->pktout.length - 5;
1983e559 4723 /* And finally the (zero) flags word. */
51470298 4724 PUT_32BIT(s->q, 0);
4725 agent_query(s->agentreq, s->len + 4, &vret, &s->retlen);
4726 s->ret = vret;
4727 sfree(s->agentreq);
4728 if (s->ret) {
4729 if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
1983e559 4730 logevent("Sending Pageant's response");
51470298 4731 ssh2_add_sigblob(ssh, s->pkblob, s->pklen,
4732 s->ret + 9,
4733 GET_32BIT(s->ret + 5));
4734 ssh2_pkt_send(ssh);
4735 s->authed = TRUE;
1983e559 4736 break;
4737 } else {
32874aea 4738 logevent
4739 ("Pageant failed to answer challenge");
51470298 4740 sfree(s->ret);
1983e559 4741 }
4742 }
4743 }
51470298 4744 if (s->authed)
1983e559 4745 continue;
4746 }
4747 }
4748
51470298 4749 if (!s->method && s->can_pubkey && s->publickey_blob
4750 && !s->tried_pubkey_config) {
1408a877 4751 unsigned char *pub_blob;
4752 char *algorithm, *comment;
4753 int pub_blob_len;
65a22376 4754
51470298 4755 s->tried_pubkey_config = TRUE;
65a22376 4756
51470298 4757 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4758 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
00db133f 4759
65a22376 4760 /*
1408a877 4761 * Try the public key supplied in the configuration.
4762 *
4763 * First, offer the public blob to see if the server is
4764 * willing to accept it.
65a22376 4765 */
d8baa528 4766 pub_blob =
9a30e26b 4767 (unsigned char *)ssh2_userkey_loadpub(&ssh->cfg.keyfile,
d8baa528 4768 &algorithm,
4769 &pub_blob_len);
1408a877 4770 if (pub_blob) {
51470298 4771 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4772 ssh2_pkt_addstring(ssh, s->username);
4773 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4774 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4775 ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
4776 ssh2_pkt_addstring(ssh, algorithm);
4777 ssh2_pkt_addstring_start(ssh);
d8baa528 4778 ssh2_pkt_addstring_data(ssh, (char *)pub_blob,
4779 pub_blob_len);
51470298 4780 ssh2_pkt_send(ssh);
32874aea 4781 logevent("Offered public key"); /* FIXME */
1408a877 4782
4783 crWaitUntilV(ispkt);
51470298 4784 if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
4785 s->gotit = TRUE;
4786 s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
32874aea 4787 continue; /* key refused; give up on it */
1408a877 4788 }
65a22376 4789
1408a877 4790 logevent("Offer of public key accepted");
65a22376 4791 /*
1408a877 4792 * Actually attempt a serious authentication using
4793 * the key.
65a22376 4794 */
9a30e26b 4795 if (ssh2_userkey_encrypted(&ssh->cfg.keyfile, &comment)) {
51470298 4796 sprintf(s->pwprompt,
32874aea 4797 "Passphrase for key \"%.100s\": ",
4798 comment);
51470298 4799 s->need_pw = TRUE;
1408a877 4800 } else {
51470298 4801 s->need_pw = FALSE;
1408a877 4802 }
51470298 4803 c_write_str(ssh, "Authenticating with public key \"");
4804 c_write_str(ssh, comment);
4805 c_write_str(ssh, "\"\r\n");
4806 s->method = AUTH_PUBLICKEY_FILE;
65a22376 4807 }
1408a877 4808 }
4809
51470298 4810 if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
4811 s->method = AUTH_KEYBOARD_INTERACTIVE;
4812 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4813 s->tried_keyb_inter = TRUE;
af659722 4814
51470298 4815 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4816 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
00db133f 4817
51470298 4818 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4819 ssh2_pkt_addstring(ssh, s->username);
4820 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4821 ssh2_pkt_addstring(ssh, "keyboard-interactive"); /* method */
4822 ssh2_pkt_addstring(ssh, ""); /* lang */
4823 ssh2_pkt_addstring(ssh, "");
4824 ssh2_pkt_send(ssh);
af659722 4825
4826 crWaitUntilV(ispkt);
51470298 4827 if (ssh->pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
4828 if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE)
4829 s->gotit = TRUE;
af659722 4830 logevent("Keyboard-interactive authentication refused");
51470298 4831 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
af659722 4832 continue;
4833 }
4834
51470298 4835 s->kbd_inter_running = TRUE;
4836 s->curr_prompt = 0;
af659722 4837 }
4838
51470298 4839 if (s->kbd_inter_running) {
4840 s->method = AUTH_KEYBOARD_INTERACTIVE;
4841 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
4842 s->tried_keyb_inter = TRUE;
af659722 4843
51470298 4844 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4845 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
00db133f 4846
51470298 4847 if (s->curr_prompt == 0) {
45068b27 4848 /*
4849 * We've got a fresh USERAUTH_INFO_REQUEST.
4850 * Display header data, and start going through
4851 * the prompts.
4852 */
4853 char *name, *inst, *lang;
4854 int name_len, inst_len, lang_len;
4855
51470298 4856 ssh2_pkt_getstring(ssh, &name, &name_len);
4857 ssh2_pkt_getstring(ssh, &inst, &inst_len);
4858 ssh2_pkt_getstring(ssh, &lang, &lang_len);
45068b27 4859 if (name_len > 0) {
51470298 4860 c_write_untrusted(ssh, name, name_len);
4861 c_write_str(ssh, "\r\n");
45068b27 4862 }
4863 if (inst_len > 0) {
51470298 4864 c_write_untrusted(ssh, inst, inst_len);
4865 c_write_str(ssh, "\r\n");
45068b27 4866 }
51470298 4867 s->num_prompts = ssh2_pkt_getuint32(ssh);
45068b27 4868 }
af659722 4869
45068b27 4870 /*
4871 * If there are prompts remaining in the packet,
4872 * display one and get a response.
4873 */
51470298 4874 if (s->curr_prompt < s->num_prompts) {
45068b27 4875 char *prompt;
4876 int prompt_len;
af659722 4877
51470298 4878 ssh2_pkt_getstring(ssh, &prompt, &prompt_len);
45068b27 4879 if (prompt_len > 0) {
51470298 4880 strncpy(s->pwprompt, prompt, sizeof(s->pwprompt));
4881 s->pwprompt[prompt_len < sizeof(s->pwprompt) ?
4882 prompt_len : sizeof(s->pwprompt)-1] = '\0';
45068b27 4883 } else {
51470298 4884 strcpy(s->pwprompt,
45068b27 4885 "<server failed to send prompt>: ");
4886 }
51470298 4887 s->echo = ssh2_pkt_getbool(ssh);
4888 s->need_pw = TRUE;
45068b27 4889 } else
51470298 4890 s->need_pw = FALSE;
af659722 4891 }
4892
51470298 4893 if (!s->method && s->can_passwd) {
4894 s->method = AUTH_PASSWORD;
4895 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
4896 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
4897 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
4898 ssh->savedhost);
4899 s->need_pw = TRUE;
1408a877 4900 }
4901
51470298 4902 if (s->need_pw) {
fa17a66e 4903 if (ssh_get_line) {
51470298 4904 if (!ssh_get_line(s->pwprompt, s->password,
4905 sizeof(s->password), TRUE)) {
1408a877 4906 /*
fa17a66e 4907 * get_line failed to get a password (for
4908 * example because one was supplied on the
4909 * command line which has already failed to
4910 * work). Terminate.
1408a877 4911 */
51470298 4912 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
4913 ssh2_pkt_adduint32(ssh,SSH2_DISCONNECT_BY_APPLICATION);
4914 ssh2_pkt_addstring(ssh, "No more passwords available"
4915 " to try");
4916 ssh2_pkt_addstring(ssh, "en"); /* language tag */
4917 ssh2_pkt_send(ssh);
247308b5 4918 logevent("Unable to authenticate");
a8327734 4919 connection_fatal(ssh->frontend,
4920 "Unable to authenticate");
3bb2f322 4921 ssh_closing((Plug)ssh, NULL, 0, 0);
1408a877 4922 crReturnV;
4923 }
4924 } else {
51470298 4925 int ret; /* need not be saved across crReturn */
4926 c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
4927 ssh->send_ok = 1;
1408a877 4928
51470298 4929 setup_userpass_input(ssh, s->password,
4930 sizeof(s->password), s->echo);
0405e71f 4931 do {
1408a877 4932 crWaitUntilV(!ispkt);
51470298 4933 ret = process_userpass_input(ssh, in, inlen);
0405e71f 4934 } while (ret == 0);
4935 if (ret < 0)
4936 cleanup_exit(0);
51470298 4937 c_write_str(ssh, "\r\n");
65a22376 4938 }
65a22376 4939 }
65a22376 4940
51470298 4941 if (s->method == AUTH_PUBLICKEY_FILE) {
1408a877 4942 /*
4943 * We have our passphrase. Now try the actual authentication.
4944 */
4945 struct ssh2_userkey *key;
65a22376 4946
9a30e26b 4947 key = ssh2_load_userkey(&ssh->cfg.keyfile, s->password);
1408a877 4948 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
4949 if (key == SSH2_WRONG_PASSPHRASE) {
51470298 4950 c_write_str(ssh, "Wrong passphrase\r\n");
4951 s->tried_pubkey_config = FALSE;
1408a877 4952 } else {
51470298 4953 c_write_str(ssh, "Unable to load private key\r\n");
4954 s->tried_pubkey_config = TRUE;
1408a877 4955 }
4956 /* Send a spurious AUTH_NONE to return to the top. */
51470298 4957 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4958 ssh2_pkt_addstring(ssh, s->username);
4959 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4960 ssh2_pkt_addstring(ssh, "none"); /* method */
4961 ssh2_pkt_send(ssh);
4962 s->type = AUTH_TYPE_NONE;
1408a877 4963 } else {
1dd353b5 4964 unsigned char *pkblob, *sigblob, *sigdata;
4965 int pkblob_len, sigblob_len, sigdata_len;
dda87a28 4966 int p;
65a22376 4967
1408a877 4968 /*
4969 * We have loaded the private key and the server
4970 * has announced that it's willing to accept it.
4971 * Hallelujah. Generate a signature and send it.
4972 */
51470298 4973 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
4974 ssh2_pkt_addstring(ssh, s->username);
4975 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
4976 ssh2_pkt_addstring(ssh, "publickey"); /* method */
4977 ssh2_pkt_addbool(ssh, TRUE);
4978 ssh2_pkt_addstring(ssh, key->alg->name);
1dd353b5 4979 pkblob = key->alg->public_blob(key->data, &pkblob_len);
51470298 4980 ssh2_pkt_addstring_start(ssh);
d8baa528 4981 ssh2_pkt_addstring_data(ssh, (char *)pkblob, pkblob_len);
1408a877 4982
4983 /*
4984 * The data to be signed is:
4985 *
4986 * string session-id
4987 *
4988 * followed by everything so far placed in the
4989 * outgoing packet.
4990 */
51470298 4991 sigdata_len = ssh->pktout.length - 5 + 4 + 20;
dda87a28 4992 if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
4993 sigdata_len -= 4;
92d60585 4994 sigdata = snewn(sigdata_len, unsigned char);
dda87a28 4995 p = 0;
4996 if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
4997 PUT_32BIT(sigdata+p, 20);
4998 p += 4;
4999 }
5000 memcpy(sigdata+p, ssh->v2_session_id, 20); p += 20;
5001 memcpy(sigdata+p, ssh->pktout.data + 5,
51470298 5002 ssh->pktout.length - 5);
dda87a28 5003 p += ssh->pktout.length - 5;
5004 assert(p == sigdata_len);
d8baa528 5005 sigblob = key->alg->sign(key->data, (char *)sigdata,
1dd353b5 5006 sigdata_len, &sigblob_len);
51470298 5007 ssh2_add_sigblob(ssh, pkblob, pkblob_len,
1dd353b5 5008 sigblob, sigblob_len);
5009 sfree(pkblob);
5010 sfree(sigblob);
1408a877 5011 sfree(sigdata);
5012
51470298 5013 ssh2_pkt_send(ssh);
5014 s->type = AUTH_TYPE_PUBLICKEY;
1408a877 5015 }
51470298 5016 } else if (s->method == AUTH_PASSWORD) {
65a22376 5017 /*
1408a877 5018 * We send the password packet lumped tightly together with
5019 * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
5020 * string long enough to make the total length of the two
5021 * packets constant. This should ensure that a passive
5022 * listener doing traffic analyis can't work out the length
5023 * of the password.
5024 *
5025 * For this to work, we need an assumption about the
5026 * maximum length of the password packet. I think 256 is
5027 * pretty conservative. Anyone using a password longer than
5028 * that probably doesn't have much to worry about from
5029 * people who find out how long their password is!
65a22376 5030 */
51470298 5031 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
5032 ssh2_pkt_addstring(ssh, s->username);
5033 ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
5034 ssh2_pkt_addstring(ssh, "password");
5035 ssh2_pkt_addbool(ssh, FALSE);
5036 ssh2_pkt_addstring(ssh, s->password);
1409c1b3 5037 memset(s->password, 0, sizeof(s->password));
51470298 5038 ssh2_pkt_defer(ssh);
65a22376 5039 /*
1408a877 5040 * We'll include a string that's an exact multiple of the
5041 * cipher block size. If the cipher is NULL for some
5042 * reason, we don't do this trick at all because we gain
5043 * nothing by it.
65a22376 5044 */
51470298 5045 if (ssh->cscipher) {
32874aea 5046 int stringlen, i;
5047
51470298 5048 stringlen = (256 - ssh->deferred_len);
5049 stringlen += ssh->cscipher->blksize - 1;
5050 stringlen -= (stringlen % ssh->cscipher->blksize);
5051 if (ssh->cscomp) {
32874aea 5052 /*
5053 * Temporarily disable actual compression,
5054 * so we can guarantee to get this string
5055 * exactly the length we want it. The
5056 * compression-disabling routine should
5057 * return an integer indicating how many
5058 * bytes we should adjust our string length
5059 * by.
5060 */
5366aed8 5061 stringlen -=
5062 ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
32874aea 5063 }
51470298 5064 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
5065 ssh2_pkt_addstring_start(ssh);
6e9e9520 5066 for (i = 0; i < stringlen; i++) {
32874aea 5067 char c = (char) random_byte();
51470298 5068 ssh2_pkt_addstring_data(ssh, &c, 1);
65a22376 5069 }
51470298 5070 ssh2_pkt_defer(ssh);
65a22376 5071 }
51470298 5072 ssh_pkt_defersend(ssh);
0d43337a 5073 logevent("Sent password");
51470298 5074 s->type = AUTH_TYPE_PASSWORD;
5075 } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
5076 if (s->curr_prompt == 0) {
5077 ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE);
5078 ssh2_pkt_adduint32(ssh, s->num_prompts);
45068b27 5079 }
51470298 5080 if (s->need_pw) { /* only add pw if we just got one! */
5081 ssh2_pkt_addstring(ssh, s->password);
5082 memset(s->password, 0, sizeof(s->password));
5083 s->curr_prompt++;
45068b27 5084 }
51470298 5085 if (s->curr_prompt >= s->num_prompts) {
5086 ssh2_pkt_send(ssh);
45068b27 5087 } else {
5088 /*
5089 * If there are prompts remaining, we set
5090 * `gotit' so that we won't attempt to get
5091 * another packet. Then we go back round the
5092 * loop and will end up retrieving another
5093 * prompt out of the existing packet. Funky or
5094 * what?
5095 */
51470298 5096 s->gotit = TRUE;
45068b27 5097 }
51470298 5098 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
1408a877 5099 } else {
51470298 5100 c_write_str(ssh, "No supported authentication methods"
5101 " left to try!\r\n");
5102 logevent("No supported authentications offered."
5103 " Disconnecting");
5104 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5105 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5106 ssh2_pkt_addstring(ssh, "No supported authentication"
5107 " methods available");
5108 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5109 ssh2_pkt_send(ssh);
3bb2f322 5110 ssh_closing((Plug)ssh, NULL, 0, 0);
1408a877 5111 crReturnV;
65a22376 5112 }
65a22376 5113 }
51470298 5114 } while (!s->we_are_in);
7cca0d81 5115
5116 /*
5117 * Now we're authenticated for the connection protocol. The
5118 * connection protocol will automatically have started at this
5119 * point; there's no need to send SERVICE_REQUEST.
5120 */
5121
5122 /*
5123 * So now create a channel with a session in it.
5124 */
51470298 5125 ssh->channels = newtree234(ssh_channelcmp);
3d88e64d 5126 ssh->mainchan = snew(struct ssh_channel);
51470298 5127 ssh->mainchan->ssh = ssh;
5128 ssh->mainchan->localid = alloc_channel_id(ssh);
5129 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
5130 ssh2_pkt_addstring(ssh, "session");
5131 ssh2_pkt_adduint32(ssh, ssh->mainchan->localid);
5132 ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
5133 ssh2_pkt_adduint32(ssh, ssh->mainchan->v.v2.locwindow);/* our window size */
5134 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5135 ssh2_pkt_send(ssh);
7cca0d81 5136 crWaitUntilV(ispkt);
51470298 5137 if (ssh->pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
6b5cf8b4 5138 bombout(("Server refused to open a session"));
32874aea 5139 crReturnV;
5140 /* FIXME: error data comes back in FAILURE packet */
7cca0d81 5141 }
51470298 5142 if (ssh2_pkt_getuint32(ssh) != ssh->mainchan->localid) {
6b5cf8b4 5143 bombout(("Server's channel confirmation cited wrong channel"));
32874aea 5144 crReturnV;
7cca0d81 5145 }
51470298 5146 ssh->mainchan->remoteid = ssh2_pkt_getuint32(ssh);
5147 ssh->mainchan->type = CHAN_MAINSESSION;
5148 ssh->mainchan->closes = 0;
5149 ssh->mainchan->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5150 ssh->mainchan->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
5151 bufchain_init(&ssh->mainchan->v.v2.outbuffer);
5152 add234(ssh->channels, ssh->mainchan);
7cca0d81 5153 logevent("Opened channel for session");
5154
5155 /*
783415f8 5156 * Potentially enable X11 forwarding.
5157 */
86916870 5158 if (ssh->cfg.x11_forward) {
32874aea 5159 char proto[20], data[64];
5160 logevent("Requesting X11 forwarding");
302121de 5161 ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
86916870 5162 data, sizeof(data), ssh->cfg.x11_auth);
5163 x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
51470298 5164 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5165 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5166 ssh2_pkt_addstring(ssh, "x11-req");
5167 ssh2_pkt_addbool(ssh, 1); /* want reply */
5168 ssh2_pkt_addbool(ssh, 0); /* many connections */
5169 ssh2_pkt_addstring(ssh, proto);
5170 ssh2_pkt_addstring(ssh, data);
86916870 5171 ssh2_pkt_adduint32(ssh, x11_get_screen_number(ssh->cfg.x11_display));
51470298 5172 ssh2_pkt_send(ssh);
32874aea 5173
5174 do {
5175 crWaitUntilV(ispkt);
51470298 5176 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5177 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5178 struct ssh_channel *c;
51470298 5179 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 5180 if (!c)
5181 continue; /* nonexistent channel */
51470298 5182 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
32874aea 5183 }
51470298 5184 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
32874aea 5185
51470298 5186 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5187 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
6b5cf8b4 5188 bombout(("Unexpected response to X11 forwarding request:"
51470298 5189 " packet type %d", ssh->pktin.type));
32874aea 5190 crReturnV;
5191 }
5192 logevent("X11 forwarding refused");
5193 } else {
5194 logevent("X11 forwarding enabled");
51470298 5195 ssh->X11_fwd_enabled = TRUE;
32874aea 5196 }
783415f8 5197 }
5198
5199 /*
bc240b21 5200 * Enable port forwardings.
5201 */
5202 {
bc240b21 5203 char type;
5204 int n;
a4fc0d74 5205 int sport,dport,sserv,dserv;
6ee9b735 5206 char sports[256], dports[256], saddr[256], host[256];
bc240b21 5207
51470298 5208 ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
bc240b21 5209 /* Add port forwardings. */
86916870 5210 ssh->portfwd_strptr = ssh->cfg.portfwd;
51470298 5211 while (*ssh->portfwd_strptr) {
5212 type = *ssh->portfwd_strptr++;
6ee9b735 5213 saddr[0] = '\0';
bc240b21 5214 n = 0;
6ee9b735 5215 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
5216 if (*ssh->portfwd_strptr == ':') {
5217 /*
5218 * We've seen a colon in the middle of the
5219 * source port number. This means that
5220 * everything we've seen until now is the
5221 * source _address_, so we'll move it into
5222 * saddr and start sports from the beginning
5223 * again.
5224 */
5225 ssh->portfwd_strptr++;
5226 sports[n] = '\0';
5227 strcpy(saddr, sports);
5228 n = 0;
5229 }
5230 if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
5231 }
bc240b21 5232 sports[n] = 0;
51470298 5233 if (*ssh->portfwd_strptr == '\t')
5234 ssh->portfwd_strptr++;
bc240b21 5235 n = 0;
6ee9b735 5236 while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
5237 if (n < 255) host[n++] = *ssh->portfwd_strptr++;
5238 }
bc240b21 5239 host[n] = 0;
51470298 5240 if (*ssh->portfwd_strptr == ':')
5241 ssh->portfwd_strptr++;
bc240b21 5242 n = 0;
6ee9b735 5243 while (*ssh->portfwd_strptr) {
5244 if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
5245 }
bc240b21 5246 dports[n] = 0;
51470298 5247 ssh->portfwd_strptr++;
bc240b21 5248 dport = atoi(dports);
a4fc0d74 5249 dserv = 0;
5250 if (dport == 0) {
5251 dserv = 1;
68a49acb 5252 dport = net_service_lookup(dports);
5253 if (!dport) {
57356d63 5254 logeventf(ssh, "Service lookup failed for destination"
5255 " port \"%s\"", dports);
a4fc0d74 5256 }
5257 }
bc240b21 5258 sport = atoi(sports);
a4fc0d74 5259 sserv = 0;
5260 if (sport == 0) {
5261 sserv = 1;
68a49acb 5262 sport = net_service_lookup(sports);
5263 if (!sport) {
57356d63 5264 logeventf(ssh, "Service lookup failed for source"
5265 " port \"%s\"", sports);
a4fc0d74 5266 }
5267 }
bc240b21 5268 if (sport && dport) {
5269 if (type == 'L') {
6ee9b735 5270 pfd_addforward(host, dport, *saddr ? saddr : NULL,
e8fa8f62 5271 sport, ssh, &ssh->cfg);
6ee9b735 5272 logeventf(ssh, "Local port %.*s%.*s%.*s%.*s%d%.*s"
5273 " forwarding to %s:%.*s%.*s%d%.*s",
5274 (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
5275 (int)(*saddr?1:0), ":",
57356d63 5276 (int)(sserv ? strlen(sports) : 0), sports,
5277 sserv, "(", sport, sserv, ")",
5278 host,
5279 (int)(dserv ? strlen(dports) : 0), dports,
5280 dserv, "(", dport, dserv, ")");
bc240b21 5281 } else {
5282 struct ssh_rportfwd *pf;
3d88e64d 5283 pf = snew(struct ssh_rportfwd);
bc240b21 5284 strcpy(pf->dhost, host);
5285 pf->dport = dport;
5286 pf->sport = sport;
51470298 5287 if (add234(ssh->rportfwds, pf) != pf) {
57356d63 5288 logeventf(ssh, "Duplicate remote port forwarding"
5289 " to %s:%d", host, dport);
bc240b21 5290 sfree(pf);
5291 } else {
6ee9b735 5292 logeventf(ssh, "Requesting remote port "
5293 "%.*s%.*s%.*s%.*s%d%.*s"
57356d63 5294 " forward to %s:%.*s%.*s%d%.*s",
6ee9b735 5295 (int)(*saddr?strlen(saddr):0),
5296 *saddr?saddr:NULL,
5297 (int)(*saddr?1:0), ":",
57356d63 5298 (int)(sserv ? strlen(sports) : 0), sports,
5299 sserv, "(", sport, sserv, ")",
5300 host,
5301 (int)(dserv ? strlen(dports) : 0), dports,
5302 dserv, "(", dport, dserv, ")");
51470298 5303 ssh2_pkt_init(ssh, SSH2_MSG_GLOBAL_REQUEST);
5304 ssh2_pkt_addstring(ssh, "tcpip-forward");
5305 ssh2_pkt_addbool(ssh, 1);/* want reply */
6ee9b735 5306 if (*saddr)
5307 ssh2_pkt_addstring(ssh, saddr);
86916870 5308 if (ssh->cfg.rport_acceptall)
51470298 5309 ssh2_pkt_addstring(ssh, "0.0.0.0");
beefa433 5310 else
51470298 5311 ssh2_pkt_addstring(ssh, "127.0.0.1");
5312 ssh2_pkt_adduint32(ssh, sport);
5313 ssh2_pkt_send(ssh);
bc240b21 5314
5315 do {
5316 crWaitUntilV(ispkt);
51470298 5317 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5318 unsigned i = ssh2_pkt_getuint32(ssh);
bc240b21 5319 struct ssh_channel *c;
51470298 5320 c = find234(ssh->channels, &i, ssh_channelfind);
bc240b21 5321 if (!c)
5322 continue;/* nonexistent channel */
51470298 5323 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
bc240b21 5324 }
51470298 5325 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
bc240b21 5326
51470298 5327 if (ssh->pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
5328 if (ssh->pktin.type != SSH2_MSG_REQUEST_FAILURE) {
6b5cf8b4 5329 bombout(("Unexpected response to port "
c9886e66 5330 "forwarding request: packet type %d",
51470298 5331 ssh->pktin.type));
bc240b21 5332 crReturnV;
5333 }
5334 logevent("Server refused this port forwarding");
5335 } else {
5336 logevent("Remote port forwarding enabled");
5337 }
5338 }
5339 }
5340 }
5341 }
5342 }
5343
5344 /*
36c2a3e9 5345 * Potentially enable agent forwarding.
5346 */
86916870 5347 if (ssh->cfg.agentfwd && agent_exists()) {
32874aea 5348 logevent("Requesting OpenSSH-style agent forwarding");
51470298 5349 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5350 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
5351 ssh2_pkt_addstring(ssh, "auth-agent-req@openssh.com");
5352 ssh2_pkt_addbool(ssh, 1); /* want reply */
5353 ssh2_pkt_send(ssh);
32874aea 5354
5355 do {
5356 crWaitUntilV(ispkt);
51470298 5357 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5358 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5359 struct ssh_channel *c;
51470298 5360 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 5361 if (!c)
5362 continue; /* nonexistent channel */
51470298 5363 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
32874aea 5364 }
51470298 5365 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
32874aea 5366
51470298 5367 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5368 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
6b5cf8b4 5369 bombout(("Unexpected response to agent forwarding request:"
51470298 5370 " packet type %d", ssh->pktin.type));
32874aea 5371 crReturnV;
5372 }
5373 logevent("Agent forwarding refused");
5374 } else {
5375 logevent("Agent forwarding enabled");
51470298 5376 ssh->agentfwd_enabled = TRUE;
32874aea 5377 }
36c2a3e9 5378 }
5379
5380 /*
7cca0d81 5381 * Now allocate a pty for the session.
5382 */
86916870 5383 if (!ssh->cfg.nopty) {
51470298 5384 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5385 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
5386 ssh2_pkt_addstring(ssh, "pty-req");
5387 ssh2_pkt_addbool(ssh, 1); /* want reply */
86916870 5388 ssh2_pkt_addstring(ssh, ssh->cfg.termtype);
51470298 5389 ssh2_pkt_adduint32(ssh, ssh->term_width);
5390 ssh2_pkt_adduint32(ssh, ssh->term_height);
5391 ssh2_pkt_adduint32(ssh, 0); /* pixel width */
5392 ssh2_pkt_adduint32(ssh, 0); /* pixel height */
5393 ssh2_pkt_addstring_start(ssh);
5394 ssh2_pkt_addstring_data(ssh, "\0", 1); /* TTY_OP_END, no special options */
5395 ssh2_pkt_send(ssh);
5396 ssh->state = SSH_STATE_INTERMED;
32874aea 5397
5398 do {
5399 crWaitUntilV(ispkt);
51470298 5400 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5401 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5402 struct ssh_channel *c;
51470298 5403 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 5404 if (!c)
5405 continue; /* nonexistent channel */
51470298 5406 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
32874aea 5407 }
51470298 5408 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
32874aea 5409
51470298 5410 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5411 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
6b5cf8b4 5412 bombout(("Unexpected response to pty request:"
51470298 5413 " packet type %d", ssh->pktin.type));
32874aea 5414 crReturnV;
5415 }
51470298 5416 c_write_str(ssh, "Server refused to allocate pty\r\n");
5417 ssh->editing = ssh->echoing = 1;
32874aea 5418 } else {
5419 logevent("Allocated pty");
5420 }
0965bee0 5421 } else {
51470298 5422 ssh->editing = ssh->echoing = 1;
7cca0d81 5423 }
5424
5425 /*
fd5e5847 5426 * Start a shell or a remote command. We may have to attempt
5427 * this twice if the config data has provided a second choice
5428 * of command.
7cca0d81 5429 */
fd5e5847 5430 while (1) {
5431 int subsys;
5432 char *cmd;
5433
51470298 5434 if (ssh->fallback_cmd) {
86916870 5435 subsys = ssh->cfg.ssh_subsys2;
5436 cmd = ssh->cfg.remote_cmd_ptr2;
fd5e5847 5437 } else {
86916870 5438 subsys = ssh->cfg.ssh_subsys;
5439 cmd = ssh->cfg.remote_cmd_ptr;
fd5e5847 5440 }
5441
51470298 5442 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
5443 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
fd5e5847 5444 if (subsys) {
51470298 5445 ssh2_pkt_addstring(ssh, "subsystem");
5446 ssh2_pkt_addbool(ssh, 1); /* want reply */
5447 ssh2_pkt_addstring(ssh, cmd);
fd5e5847 5448 } else if (*cmd) {
51470298 5449 ssh2_pkt_addstring(ssh, "exec");
5450 ssh2_pkt_addbool(ssh, 1); /* want reply */
5451 ssh2_pkt_addstring(ssh, cmd);
fd5e5847 5452 } else {
51470298 5453 ssh2_pkt_addstring(ssh, "shell");
5454 ssh2_pkt_addbool(ssh, 1); /* want reply */
32874aea 5455 }
51470298 5456 ssh2_pkt_send(ssh);
fd5e5847 5457 do {
5458 crWaitUntilV(ispkt);
51470298 5459 if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5460 unsigned i = ssh2_pkt_getuint32(ssh);
fd5e5847 5461 struct ssh_channel *c;
51470298 5462 c = find234(ssh->channels, &i, ssh_channelfind);
fd5e5847 5463 if (!c)
5464 continue; /* nonexistent channel */
51470298 5465 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
fd5e5847 5466 }
51470298 5467 } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5468 if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
5469 if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
6b5cf8b4 5470 bombout(("Unexpected response to shell/command request:"
51470298 5471 " packet type %d", ssh->pktin.type));
fd5e5847 5472 crReturnV;
5473 }
5474 /*
5475 * We failed to start the command. If this is the
5476 * fallback command, we really are finished; if it's
5477 * not, and if the fallback command exists, try falling
5478 * back to it before complaining.
5479 */
86916870 5480 if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
fd5e5847 5481 logevent("Primary command failed; attempting fallback");
51470298 5482 ssh->fallback_cmd = TRUE;
fd5e5847 5483 continue;
5484 }
6b5cf8b4 5485 bombout(("Server refused to start a shell/command"));
32874aea 5486 crReturnV;
fd5e5847 5487 } else {
5488 logevent("Started a shell/command");
32874aea 5489 }
fd5e5847 5490 break;
7cca0d81 5491 }
5492
51470298 5493 ssh->state = SSH_STATE_SESSION;
5494 if (ssh->size_needed)
5495 ssh_size(ssh, ssh->term_width, ssh->term_height);
5496 if (ssh->eof_needed)
5497 ssh_special(ssh, TS_EOF);
6e48c3fe 5498
7cca0d81 5499 /*
5500 * Transfer data!
5501 */
b9d7bcad 5502 if (ssh->ldisc)
5503 ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
51470298 5504 ssh->send_ok = 1;
7cca0d81 5505 while (1) {
e5574168 5506 crReturnV;
51470298 5507 s->try_send = FALSE;
7cca0d81 5508 if (ispkt) {
51470298 5509 if (ssh->pktin.type == SSH2_MSG_CHANNEL_DATA ||
5510 ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
32874aea 5511 char *data;
5512 int length;
51470298 5513 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5514 struct ssh_channel *c;
51470298 5515 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 5516 if (!c)
5517 continue; /* nonexistent channel */
51470298 5518 if (ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5519 ssh2_pkt_getuint32(ssh) != SSH2_EXTENDED_DATA_STDERR)
32874aea 5520 continue; /* extended but not stderr */
51470298 5521 ssh2_pkt_getstring(ssh, &data, &length);
32874aea 5522 if (data) {
5471d09a 5523 int bufsize;
5524 c->v.v2.locwindow -= length;
32874aea 5525 switch (c->type) {
5526 case CHAN_MAINSESSION:
5471d09a 5527 bufsize =
51470298 5528 from_backend(ssh->frontend, ssh->pktin.type ==
5471d09a 5529 SSH2_MSG_CHANNEL_EXTENDED_DATA,
5530 data, length);
32874aea 5531 break;
5532 case CHAN_X11:
5471d09a 5533 bufsize = x11_send(c->u.x11.s, data, length);
32874aea 5534 break;
d74d141c 5535 case CHAN_SOCKDATA:
5471d09a 5536 bufsize = pfd_send(c->u.pfd.s, data, length);
bc240b21 5537 break;
36c2a3e9 5538 case CHAN_AGENT:
32874aea 5539 while (length > 0) {
5540 if (c->u.a.lensofar < 4) {
5541 int l = min(4 - c->u.a.lensofar, length);
5542 memcpy(c->u.a.msglen + c->u.a.lensofar,
5543 data, l);
5544 data += l;
5545 length -= l;
5546 c->u.a.lensofar += l;
5547 }
5548 if (c->u.a.lensofar == 4) {
5549 c->u.a.totallen =
5550 4 + GET_32BIT(c->u.a.msglen);
3d88e64d 5551 c->u.a.message = snewn(c->u.a.totallen,
5552 unsigned char);
32874aea 5553 memcpy(c->u.a.message, c->u.a.msglen, 4);
5554 }
5555 if (c->u.a.lensofar >= 4 && length > 0) {
5556 int l =
5557 min(c->u.a.totallen - c->u.a.lensofar,
5558 length);
5559 memcpy(c->u.a.message + c->u.a.lensofar,
5560 data, l);
5561 data += l;
5562 length -= l;
5563 c->u.a.lensofar += l;
5564 }
5565 if (c->u.a.lensofar == c->u.a.totallen) {
5566 void *reply, *sentreply;
5567 int replylen;
5568 agent_query(c->u.a.message,
5569 c->u.a.totallen, &reply,
5570 &replylen);
5571 if (reply)
5572 sentreply = reply;
5573 else {
5574 /* Fake SSH_AGENT_FAILURE. */
5575 sentreply = "\0\0\0\1\5";
5576 replylen = 5;
5577 }
51470298 5578 ssh2_add_channel_data(c, sentreply, replylen);
5579 s->try_send = TRUE;
32874aea 5580 if (reply)
5581 sfree(reply);
5582 sfree(c->u.a.message);
5583 c->u.a.lensofar = 0;
5584 }
5585 }
5471d09a 5586 bufsize = 0;
32874aea 5587 break;
5588 }
5589 /*
5471d09a 5590 * If we are not buffering too much data,
5591 * enlarge the window again at the remote side.
32874aea 5592 */
5471d09a 5593 if (bufsize < OUR_V2_WINSIZE)
5594 ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
32874aea 5595 }
51470298 5596 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_EOF) {
5597 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5598 struct ssh_channel *c;
5599
51470298 5600 c = find234(ssh->channels, &i, ssh_channelfind);
32874aea 5601 if (!c)
5602 continue; /* nonexistent channel */
5603
5604 if (c->type == CHAN_X11) {
5605 /*
5606 * Remote EOF on an X11 channel means we should
5607 * wrap up and close the channel ourselves.
5608 */
5609 x11_close(c->u.x11.s);
5610 sshfwd_close(c);
5611 } else if (c->type == CHAN_AGENT) {
36c2a3e9 5612 sshfwd_close(c);
d74d141c 5613 } else if (c->type == CHAN_SOCKDATA) {
bc240b21 5614 pfd_close(c->u.pfd.s);
5615 sshfwd_close(c);
36c2a3e9 5616 }
51470298 5617 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
5618 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5619 struct ssh_channel *c;
5620
51470298 5621 c = find234(ssh->channels, &i, ssh_channelfind);
d0d844c1 5622 if (!c || ((int)c->remoteid) == -1) {
6b5cf8b4 5623 bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
d0d844c1 5624 c ? "half-open" : "nonexistent", i));
5625 }
32874aea 5626 /* Do pre-close processing on the channel. */
5627 switch (c->type) {
5628 case CHAN_MAINSESSION:
5629 break; /* nothing to see here, move along */
5630 case CHAN_X11:
92f157bd 5631 if (c->u.x11.s != NULL)
5632 x11_close(c->u.x11.s);
5633 sshfwd_close(c);
32874aea 5634 break;
5635 case CHAN_AGENT:
92f157bd 5636 sshfwd_close(c);
32874aea 5637 break;
d74d141c 5638 case CHAN_SOCKDATA:
92f157bd 5639 if (c->u.pfd.s != NULL)
5640 pfd_close(c->u.pfd.s);
5641 sshfwd_close(c);
bc240b21 5642 break;
32874aea 5643 }
92f157bd 5644 if (c->closes == 0) {
51470298 5645 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5646 ssh2_pkt_adduint32(ssh, c->remoteid);
5647 ssh2_pkt_send(ssh);
92f157bd 5648 }
51470298 5649 del234(ssh->channels, c);
5471d09a 5650 bufchain_clear(&c->v.v2.outbuffer);
32874aea 5651 sfree(c);
5652
5653 /*
5654 * See if that was the last channel left open.
5655 */
51470298 5656 if (count234(ssh->channels) == 0) {
3bb2f322 5657 logevent("All channels closed. Disconnecting");
ca2914d1 5658#if 0
5659 /*
5660 * We used to send SSH_MSG_DISCONNECT here,
5661 * because I'd believed that _every_ conforming
5662 * SSH2 connection had to end with a disconnect
5663 * being sent by at least one side; apparently
5664 * I was wrong and it's perfectly OK to
5665 * unceremoniously slam the connection shut
5666 * when you're done, and indeed OpenSSH feels
5667 * this is more polite than sending a
5668 * DISCONNECT. So now we don't.
5669 */
51470298 5670 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5671 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5672 ssh2_pkt_addstring(ssh, "All open channels closed");
5673 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5674 ssh2_pkt_send(ssh);
ca2914d1 5675#endif
3bb2f322 5676 ssh_closing((Plug)ssh, NULL, 0, 0);
32874aea 5677 crReturnV;
5678 }
5679 continue; /* remote sends close; ignore (FIXME) */
51470298 5680 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
5681 unsigned i = ssh2_pkt_getuint32(ssh);
32874aea 5682 struct ssh_channel *c;
51470298 5683 c = find234(ssh->channels, &i, ssh_channelfind);
a6253970 5684 if (!c || c->closes)
5685 continue; /* nonexistent or closing channel */
51470298 5686 c->v.v2.remwindow += ssh2_pkt_getuint32(ssh);
5687 s->try_send = TRUE;
5688 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
5689 unsigned i = ssh2_pkt_getuint32(ssh);
bc240b21 5690 struct ssh_channel *c;
51470298 5691 c = find234(ssh->channels, &i, ssh_channelfind);
bc240b21 5692 if (!c)
5693 continue; /* nonexistent channel */
5694 if (c->type != CHAN_SOCKDATA_DORMANT)
5695 continue; /* dunno why they're confirming this */
51470298 5696 c->remoteid = ssh2_pkt_getuint32(ssh);
bc240b21 5697 c->type = CHAN_SOCKDATA;
51470298 5698 c->v.v2.remwindow = ssh2_pkt_getuint32(ssh);
5699 c->v.v2.remmaxpkt = ssh2_pkt_getuint32(ssh);
4ed34d25 5700 if (c->u.pfd.s)
5701 pfd_confirm(c->u.pfd.s);
5702 if (c->closes) {
5703 /*
5704 * We have a pending close on this channel,
5705 * which we decided on before the server acked
5706 * the channel open. So now we know the
5707 * remoteid, we can close it again.
5708 */
51470298 5709 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
5710 ssh2_pkt_adduint32(ssh, c->remoteid);
5711 ssh2_pkt_send(ssh);
4ed34d25 5712 }
51470298 5713 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
5714 unsigned i = ssh2_pkt_getuint32(ssh);
724cface 5715 struct ssh_channel *c;
51470298 5716 c = find234(ssh->channels, &i, ssh_channelfind);
724cface 5717 if (!c)
5718 continue; /* nonexistent channel */
5719 if (c->type != CHAN_SOCKDATA_DORMANT)
5720 continue; /* dunno why they're failing this */
5721
5722 logevent("Forwarded connection refused by server");
5723
5724 pfd_close(c->u.pfd.s);
5725
51470298 5726 del234(ssh->channels, c);
724cface 5727 sfree(c);
51470298 5728 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
ebb0a590 5729 unsigned localid;
5730 char *type;
5731 int typelen, want_reply;
5732 struct ssh_channel *c;
5733
51470298 5734 localid = ssh2_pkt_getuint32(ssh);
5735 ssh2_pkt_getstring(ssh, &type, &typelen);
5736 want_reply = ssh2_pkt_getbool(ssh);
ebb0a590 5737
5738 /*
5739 * First, check that the channel exists. Otherwise,
5740 * we can instantly disconnect with a rude message.
5741 */
51470298 5742 c = find234(ssh->channels, &localid, ssh_channelfind);
ebb0a590 5743 if (!c) {
5744 char buf[80];
5745 sprintf(buf, "Received channel request for nonexistent"
5746 " channel %d", localid);
5747 logevent(buf);
51470298 5748 ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
5749 ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
5750 ssh2_pkt_addstring(ssh, buf);
5751 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5752 ssh2_pkt_send(ssh);
6b5cf8b4 5753 connection_fatal(ssh->frontend, "%s", buf);
3bb2f322 5754 ssh_closing((Plug)ssh, NULL, 0, 0);
ebb0a590 5755 crReturnV;
5756 }
5757
5758 /*
d8d6c7e5 5759 * Having got the channel number, we now look at
5760 * the request type string to see if it's something
5761 * we recognise.
ebb0a590 5762 */
d8d6c7e5 5763 if (typelen == 11 && !memcmp(type, "exit-status", 11) &&
51470298 5764 c == ssh->mainchan) {
d8d6c7e5 5765 /* We recognise "exit-status" on the primary channel. */
5766 char buf[100];
51470298 5767 ssh->exitcode = ssh2_pkt_getuint32(ssh);
d8d6c7e5 5768 sprintf(buf, "Server sent command exit status %d",
51470298 5769 ssh->exitcode);
d8d6c7e5 5770 logevent(buf);
5771 if (want_reply) {
51470298 5772 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_SUCCESS);
5773 ssh2_pkt_adduint32(ssh, c->remoteid);
5774 ssh2_pkt_send(ssh);
d8d6c7e5 5775 }
5776 } else {
5777 /*
5778 * This is a channel request we don't know
5779 * about, so we now either ignore the request
5780 * or respond with CHANNEL_FAILURE, depending
5781 * on want_reply.
5782 */
5783 if (want_reply) {
51470298 5784 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_FAILURE);
5785 ssh2_pkt_adduint32(ssh, c->remoteid);
5786 ssh2_pkt_send(ssh);
d8d6c7e5 5787 }
ebb0a590 5788 }
51470298 5789 } else if (ssh->pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
697d4856 5790 char *type;
5791 int typelen, want_reply;
5792
51470298 5793 ssh2_pkt_getstring(ssh, &type, &typelen);
5794 want_reply = ssh2_pkt_getbool(ssh);
697d4856 5795
5796 /*
5797 * We currently don't support any global requests
5798 * at all, so we either ignore the request or
5799 * respond with REQUEST_FAILURE, depending on
5800 * want_reply.
5801 */
5802 if (want_reply) {
51470298 5803 ssh2_pkt_init(ssh, SSH2_MSG_REQUEST_FAILURE);
5804 ssh2_pkt_send(ssh);
697d4856 5805 }
51470298 5806 } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN) {
32874aea 5807 char *type;
5808 int typelen;
b3ebaa28 5809 char *peeraddr;
5810 int peeraddrlen;
5811 int port;
32874aea 5812 char *error = NULL;
5813 struct ssh_channel *c;
bc240b21 5814 unsigned remid, winsize, pktsize;
51470298 5815 ssh2_pkt_getstring(ssh, &type, &typelen);
3d88e64d 5816 c = snew(struct ssh_channel);
51470298 5817 c->ssh = ssh;
32874aea 5818
51470298 5819 remid = ssh2_pkt_getuint32(ssh);
5820 winsize = ssh2_pkt_getuint32(ssh);
5821 pktsize = ssh2_pkt_getuint32(ssh);
b3ebaa28 5822 ssh2_pkt_getstring(ssh, &peeraddr, &peeraddrlen);
5823 port = ssh2_pkt_getuint32(ssh);
bc240b21 5824
32874aea 5825 if (typelen == 3 && !memcmp(type, "x11", 3)) {
3d88e64d 5826 char *addrstr = snewn(peeraddrlen+1, char);
b3ebaa28 5827 memcpy(addrstr, peeraddr, peeraddrlen);
5828 peeraddr[peeraddrlen] = '\0';
5829
51470298 5830 if (!ssh->X11_fwd_enabled)
32874aea 5831 error = "X11 forwarding is not enabled";
86916870 5832 else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
e8fa8f62 5833 ssh->x11auth, addrstr, port,
5834 &ssh->cfg) != NULL) {
32874aea 5835 error = "Unable to open an X11 connection";
5836 } else {
5837 c->type = CHAN_X11;
5838 }
b3ebaa28 5839
5840 sfree(addrstr);
bc240b21 5841 } else if (typelen == 15 &&
5842 !memcmp(type, "forwarded-tcpip", 15)) {
5843 struct ssh_rportfwd pf, *realpf;
5844 char *dummy;
5845 int dummylen;
51470298 5846 ssh2_pkt_getstring(ssh, &dummy, &dummylen);/* skip address */
5847 pf.sport = ssh2_pkt_getuint32(ssh);
5848 realpf = find234(ssh->rportfwds, &pf, NULL);
bc240b21 5849 if (realpf == NULL) {
5850 error = "Remote port is not recognised";
5851 } else {
5852 char *e = pfd_newconnect(&c->u.pfd.s, realpf->dhost,
e8fa8f62 5853 realpf->dport, c, &ssh->cfg);
57356d63 5854 logeventf(ssh, "Received remote port open request"
5855 " for %s:%d", realpf->dhost, realpf->dport);
bc240b21 5856 if (e != NULL) {
57356d63 5857 logeventf(ssh, "Port open failed: %s", e);
bc240b21 5858 error = "Port open failed";
5859 } else {
5860 logevent("Forwarded port opened successfully");
5861 c->type = CHAN_SOCKDATA;
5862 }
5863 }
32874aea 5864 } else if (typelen == 22 &&
36c2a3e9 5865 !memcmp(type, "auth-agent@openssh.com", 3)) {
51470298 5866 if (!ssh->agentfwd_enabled)
32874aea 5867 error = "Agent forwarding is not enabled";
36c2a3e9 5868 else {
32874aea 5869 c->type = CHAN_AGENT; /* identify channel type */
36c2a3e9 5870 c->u.a.lensofar = 0;
32874aea 5871 }
5872 } else {
5873 error = "Unsupported channel type requested";
5874 }
5875
bc240b21 5876 c->remoteid = remid;
32874aea 5877 if (error) {
51470298 5878 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE);
5879 ssh2_pkt_adduint32(ssh, c->remoteid);
5880 ssh2_pkt_adduint32(ssh, SSH2_OPEN_CONNECT_FAILED);
5881 ssh2_pkt_addstring(ssh, error);
5882 ssh2_pkt_addstring(ssh, "en"); /* language tag */
5883 ssh2_pkt_send(ssh);
32874aea 5884 sfree(c);
5885 } else {
51470298 5886 c->localid = alloc_channel_id(ssh);
32874aea 5887 c->closes = 0;
5471d09a 5888 c->v.v2.locwindow = OUR_V2_WINSIZE;
5889 c->v.v2.remwindow = winsize;
5890 c->v.v2.remmaxpkt = pktsize;
5891 bufchain_init(&c->v.v2.outbuffer);
51470298 5892 add234(ssh->channels, c);
5893 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
5894 ssh2_pkt_adduint32(ssh, c->remoteid);
5895 ssh2_pkt_adduint32(ssh, c->localid);
5896 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);
5897 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
5898 ssh2_pkt_send(ssh);
32874aea 5899 }
7cca0d81 5900 } else {
6b5cf8b4 5901 bombout(("Strange packet received: type %d", ssh->pktin.type));
32874aea 5902 crReturnV;
7cca0d81 5903 }
5904 } else {
32874aea 5905 /*
5906 * We have spare data. Add it to the channel buffer.
5907 */
d8baa528 5908 ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
51470298 5909 s->try_send = TRUE;
32874aea 5910 }
51470298 5911 if (s->try_send) {
32874aea 5912 int i;
5913 struct ssh_channel *c;
5914 /*
5915 * Try to send data on all channels if we can.
5916 */
51470298 5917 for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
a6253970 5918 int bufsize;
5919 if (c->closes)
5920 continue; /* don't send on closing channels */
5921 bufsize = ssh2_try_send(c);
5471d09a 5922 if (bufsize == 0) {
5923 switch (c->type) {
5924 case CHAN_MAINSESSION:
5925 /* stdin need not receive an unthrottle
5926 * notification since it will be polled */
5927 break;
5928 case CHAN_X11:
5929 x11_unthrottle(c->u.x11.s);
5930 break;
5931 case CHAN_AGENT:
5932 /* agent sockets are request/response and need no
5933 * buffer management */
5934 break;
5935 case CHAN_SOCKDATA:
5936 pfd_unthrottle(c->u.pfd.s);
5937 break;
5938 }
5939 }
5940 }
7cca0d81 5941 }
e5574168 5942 }
5943
5944 crFinishV;
5945}
5946
5947/*
7cca0d81 5948 * Handle the top-level SSH2 protocol.
5949 */
51470298 5950static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
7cca0d81 5951{
51470298 5952 if (do_ssh2_transport(ssh, in, inlen, ispkt) == 0)
32874aea 5953 return;
51470298 5954 do_ssh2_authconn(ssh, in, inlen, ispkt);
7cca0d81 5955}
5956
5957/*
8df7a775 5958 * Called to set up the connection.
374330e2 5959 *
5960 * Returns an error message, or NULL on success.
374330e2 5961 */
51470298 5962static char *ssh_init(void *frontend_handle, void **backend_handle,
86916870 5963 Config *cfg,
887035a5 5964 char *host, int port, char **realhost, int nodelay)
32874aea 5965{
fb09bf1c 5966 char *p;
51470298 5967 Ssh ssh;
5968
3d88e64d 5969 ssh = snew(struct ssh_tag);
86916870 5970 ssh->cfg = *cfg; /* STRUCTURE COPY */
125105d1 5971 ssh->version = 0; /* when not ready yet */
51470298 5972 ssh->s = NULL;
5973 ssh->cipher = NULL;
371e569c 5974 ssh->v1_cipher_ctx = NULL;
0183b242 5975 ssh->crcda_ctx = NULL;
51470298 5976 ssh->cscipher = NULL;
371e569c 5977 ssh->cs_cipher_ctx = NULL;
51470298 5978 ssh->sccipher = NULL;
371e569c 5979 ssh->sc_cipher_ctx = NULL;
51470298 5980 ssh->csmac = NULL;
a8327734 5981 ssh->cs_mac_ctx = NULL;
51470298 5982 ssh->scmac = NULL;
e0e1a00d 5983 ssh->sc_mac_ctx = NULL;
51470298 5984 ssh->cscomp = NULL;
5366aed8 5985 ssh->cs_comp_ctx = NULL;
51470298 5986 ssh->sccomp = NULL;
5366aed8 5987 ssh->sc_comp_ctx = NULL;
51470298 5988 ssh->kex = NULL;
389aa499 5989 ssh->kex_ctx = NULL;
51470298 5990 ssh->hostkey = NULL;
5991 ssh->exitcode = -1;
5992 ssh->state = SSH_STATE_PREPACKET;
5993 ssh->size_needed = FALSE;
5994 ssh->eof_needed = FALSE;
b9d7bcad 5995 ssh->ldisc = NULL;
a8327734 5996 ssh->logctx = NULL;
51470298 5997 {
5998 static const struct Packet empty = { 0, 0, NULL, NULL, 0 };
5999 ssh->pktin = ssh->pktout = empty;
6000 }
6001 ssh->deferred_send_data = NULL;
6002 ssh->deferred_len = 0;
6003 ssh->deferred_size = 0;
6004 ssh->fallback_cmd = 0;
6005 ssh->pkt_ctx = 0;
302121de 6006 ssh->x11auth = NULL;
be738459 6007 ssh->v1_compressing = FALSE;
51470298 6008 ssh->v2_outgoing_sequence = 0;
6009 ssh->ssh1_rdpkt_crstate = 0;
6010 ssh->ssh2_rdpkt_crstate = 0;
6011 ssh->do_ssh_init_crstate = 0;
6012 ssh->ssh_gotdata_crstate = 0;
6013 ssh->ssh1_protocol_crstate = 0;
6014 ssh->do_ssh1_login_crstate = 0;
6015 ssh->do_ssh2_transport_crstate = 0;
6016 ssh->do_ssh2_authconn_crstate = 0;
6017 ssh->do_ssh_init_state = NULL;
6018 ssh->do_ssh1_login_state = NULL;
6019 ssh->do_ssh2_transport_state = NULL;
6020 ssh->do_ssh2_authconn_state = NULL;
6571dbfd 6021 ssh->mainchan = NULL;
968d2d92 6022 ssh->throttled_all = 0;
6023 ssh->v1_stdout_throttling = 0;
51470298 6024
6025 *backend_handle = ssh;
32874aea 6026
8f203108 6027#ifdef MSCRYPTOAPI
32874aea 6028 if (crypto_startup() == 0)
8f203108 6029 return "Microsoft high encryption pack not installed!";
6030#endif
374330e2 6031
51470298 6032 ssh->frontend = frontend_handle;
86916870 6033 ssh->term_width = ssh->cfg.width;
6034 ssh->term_height = ssh->cfg.height;
887035a5 6035
fabd1805 6036 ssh->channels = NULL;
6037 ssh->rportfwds = NULL;
6038
51470298 6039 ssh->send_ok = 0;
6040 ssh->editing = 0;
6041 ssh->echoing = 0;
6042 ssh->v1_throttle_count = 0;
6043 ssh->overall_bufsize = 0;
6044 ssh->fallback_cmd = 0;
8df7a775 6045
3648d4c5 6046 ssh->protocol = NULL;
6047
51470298 6048 p = connect_to_host(ssh, host, port, realhost, nodelay);
fb09bf1c 6049 if (p != NULL)
6050 return p;
374330e2 6051
374330e2 6052 return NULL;
6053}
6054
fabd1805 6055static void ssh_free(void *handle)
6056{
6057 Ssh ssh = (Ssh) handle;
6058 struct ssh_channel *c;
6059 struct ssh_rportfwd *pf;
6060
6061 if (ssh->v1_cipher_ctx)
6062 ssh->cipher->free_context(ssh->v1_cipher_ctx);
6063 if (ssh->cs_cipher_ctx)
6064 ssh->cscipher->free_context(ssh->cs_cipher_ctx);
6065 if (ssh->sc_cipher_ctx)
6066 ssh->sccipher->free_context(ssh->sc_cipher_ctx);
6067 if (ssh->cs_mac_ctx)
6068 ssh->csmac->free_context(ssh->cs_mac_ctx);
6069 if (ssh->sc_mac_ctx)
6070 ssh->scmac->free_context(ssh->sc_mac_ctx);
6071 if (ssh->cs_comp_ctx)
6072 ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
6073 if (ssh->sc_comp_ctx)
6074 ssh->sccomp->compress_cleanup(ssh->sc_comp_ctx);
6075 if (ssh->kex_ctx)
6076 dh_cleanup(ssh->kex_ctx);
6077 sfree(ssh->savedhost);
6078
6079 if (ssh->channels) {
6080 while ((c = delpos234(ssh->channels, 0)) != NULL) {
6081 switch (c->type) {
6082 case CHAN_X11:
6083 if (c->u.x11.s != NULL)
6084 x11_close(c->u.x11.s);
6085 break;
6086 case CHAN_SOCKDATA:
6087 if (c->u.pfd.s != NULL)
6088 pfd_close(c->u.pfd.s);
6089 break;
6090 }
6091 sfree(c);
6092 }
6093 freetree234(ssh->channels);
6094 }
6095
6096 if (ssh->rportfwds) {
6097 while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
6098 sfree(pf);
6099 freetree234(ssh->rportfwds);
6100 }
6101 sfree(ssh->deferred_send_data);
6102 if (ssh->x11auth)
6103 x11_free_auth(ssh->x11auth);
6104 sfree(ssh->do_ssh_init_state);
6105 sfree(ssh->do_ssh1_login_state);
6106 sfree(ssh->do_ssh2_transport_state);
6107 sfree(ssh->do_ssh2_authconn_state);
6108
6109 if (ssh->s)
6110 sk_close(ssh->s);
6111 sfree(ssh);
6112}
6113
374330e2 6114/*
86916870 6115 * Reconfigure the SSH backend.
6116 *
6117 * Currently, this function does nothing very useful. In future,
6118 * however, we could do some handy things with it. For example, we
6119 * could make the port forwarding configurer active in the Change
6120 * Settings box, and this routine could close down existing
6121 * forwardings and open up new ones in response to changes.
6122 */
6123static void ssh_reconfig(void *handle, Config *cfg)
6124{
6125 Ssh ssh = (Ssh) handle;
6126 ssh->cfg = *cfg; /* STRUCTURE COPY */
6127}
6128
6129/*
374330e2 6130 * Called to send data down the Telnet connection.
6131 */
51470298 6132static int ssh_send(void *handle, char *buf, int len)
32874aea 6133{
51470298 6134 Ssh ssh = (Ssh) handle;
6135
6136 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5471d09a 6137 return 0;
374330e2 6138
d8baa528 6139 ssh->protocol(ssh, (unsigned char *)buf, len, 0);
5471d09a 6140
51470298 6141 return ssh_sendbuffer(ssh);
5471d09a 6142}
6143
6144/*
6145 * Called to query the current amount of buffered stdin data.
6146 */
51470298 6147static int ssh_sendbuffer(void *handle)
5471d09a 6148{
51470298 6149 Ssh ssh = (Ssh) handle;
5471d09a 6150 int override_value;
6151
51470298 6152 if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
5471d09a 6153 return 0;
6154
6155 /*
6156 * If the SSH socket itself has backed up, add the total backup
6157 * size on that to any individual buffer on the stdin channel.
6158 */
6159 override_value = 0;
51470298 6160 if (ssh->throttled_all)
6161 override_value = ssh->overall_bufsize;
5471d09a 6162
51470298 6163 if (ssh->version == 1) {
5471d09a 6164 return override_value;
51470298 6165 } else if (ssh->version == 2) {
6166 if (!ssh->mainchan || ssh->mainchan->closes > 0)
5471d09a 6167 return override_value;
6168 else
51470298 6169 return (override_value +
6170 bufchain_size(&ssh->mainchan->v.v2.outbuffer));
5471d09a 6171 }
6172
6173 return 0;
374330e2 6174}
6175
6176/*
6e48c3fe 6177 * Called to set the size of the window from SSH's POV.
374330e2 6178 */
51470298 6179static void ssh_size(void *handle, int width, int height)
32874aea 6180{
51470298 6181 Ssh ssh = (Ssh) handle;
6182
6183 ssh->term_width = width;
6184 ssh->term_height = height;
f278d6f8 6185
51470298 6186 switch (ssh->state) {
374330e2 6187 case SSH_STATE_BEFORE_SIZE:
3687d221 6188 case SSH_STATE_PREPACKET:
21248260 6189 case SSH_STATE_CLOSED:
374330e2 6190 break; /* do nothing */
6191 case SSH_STATE_INTERMED:
51470298 6192 ssh->size_needed = TRUE; /* buffer for later */
374330e2 6193 break;
6194 case SSH_STATE_SESSION:
86916870 6195 if (!ssh->cfg.nopty) {
51470298 6196 if (ssh->version == 1) {
6197 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
6198 PKT_INT, ssh->term_height,
6199 PKT_INT, ssh->term_width,
32874aea 6200 PKT_INT, 0, PKT_INT, 0, PKT_END);
6201 } else {
51470298 6202 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
6203 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
6204 ssh2_pkt_addstring(ssh, "window-change");
6205 ssh2_pkt_addbool(ssh, 0);
6206 ssh2_pkt_adduint32(ssh, ssh->term_width);
6207 ssh2_pkt_adduint32(ssh, ssh->term_height);
6208 ssh2_pkt_adduint32(ssh, 0);
6209 ssh2_pkt_adduint32(ssh, 0);
6210 ssh2_pkt_send(ssh);
32874aea 6211 }
6212 }
6213 break;
374330e2 6214 }
6215}
6216
6217/*
125105d1 6218 * Return a list of the special codes that make sense in this
6219 * protocol.
6220 */
6221static const struct telnet_special *ssh_get_specials(void *handle)
6222{
6223 Ssh ssh = (Ssh) handle;
6224
6225 if (ssh->version == 1) {
6226 static const struct telnet_special ssh1_specials[] = {
6227 {"IGNORE message", TS_NOP},
6228 {NULL, 0}
6229 };
6230 return ssh1_specials;
6231 } else if (ssh->version == 2) {
6232 static const struct telnet_special ssh2_specials[] = {
6233 {"Break", TS_BRK},
6234 {"IGNORE message", TS_NOP},
6235 {NULL, 0}
6236 };
6237 return ssh2_specials;
6238 } else
6239 return NULL;
6240}
6241
6242/*
6abbf9e3 6243 * Send Telnet special codes. TS_EOF is useful for `plink', so you
6244 * can send an EOF and collect resulting output (e.g. `plink
6245 * hostname sort').
374330e2 6246 */
51470298 6247static void ssh_special(void *handle, Telnet_Special code)
32874aea 6248{
51470298 6249 Ssh ssh = (Ssh) handle;
6250
6abbf9e3 6251 if (code == TS_EOF) {
51470298 6252 if (ssh->state != SSH_STATE_SESSION) {
32874aea 6253 /*
6254 * Buffer the EOF in case we are pre-SESSION, so we can
6255 * send it as soon as we reach SESSION.
6256 */
6257 if (code == TS_EOF)
51470298 6258 ssh->eof_needed = TRUE;
32874aea 6259 return;
6260 }
51470298 6261 if (ssh->version == 1) {
6262 send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
32874aea 6263 } else {
51470298 6264 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_EOF);
6265 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
6266 ssh2_pkt_send(ssh);
32874aea 6267 }
6268 logevent("Sent EOF message");
125105d1 6269 } else if (code == TS_PING || code == TS_NOP) {
51470298 6270 if (ssh->state == SSH_STATE_CLOSED
6271 || ssh->state == SSH_STATE_PREPACKET) return;
6272 if (ssh->version == 1) {
6273 if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
6274 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
32874aea 6275 } else {
51470298 6276 ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
6277 ssh2_pkt_addstring_start(ssh);
6278 ssh2_pkt_send(ssh);
32874aea 6279 }
125105d1 6280 } else if (code == TS_BRK) {
6281 if (ssh->state == SSH_STATE_CLOSED
6282 || ssh->state == SSH_STATE_PREPACKET) return;
6283 if (ssh->version == 1) {
6284 logevent("Unable to send BREAK signal in SSH1");
6285 } else {
6286 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
6287 ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
6288 ssh2_pkt_addstring(ssh, "break");
6289 ssh2_pkt_addbool(ssh, 0);
6290 ssh2_pkt_adduint32(ssh, 0); /* default break length */
6291 ssh2_pkt_send(ssh);
6292 }
6abbf9e3 6293 } else {
32874aea 6294 /* do nothing */
6abbf9e3 6295 }
374330e2 6296}
6297
51470298 6298void *new_sock_channel(void *handle, Socket s)
d74d141c 6299{
51470298 6300 Ssh ssh = (Ssh) handle;
d74d141c 6301 struct ssh_channel *c;
3d88e64d 6302 c = snew(struct ssh_channel);
51470298 6303 c->ssh = ssh;
d74d141c 6304
6305 if (c) {
bc240b21 6306 c->remoteid = -1; /* to be set when open confirmed */
51470298 6307 c->localid = alloc_channel_id(ssh);
d74d141c 6308 c->closes = 0;
bc240b21 6309 c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
d74d141c 6310 c->u.pfd.s = s;
013dd8c0 6311 bufchain_init(&c->v.v2.outbuffer);
51470298 6312 add234(ssh->channels, c);
d74d141c 6313 }
6314 return c;
6315}
6316
5471d09a 6317/*
6318 * This is called when stdout/stderr (the entity to which
6319 * from_backend sends data) manages to clear some backlog.
6320 */
ae9ae89f 6321static void ssh_unthrottle(void *handle, int bufsize)
5471d09a 6322{
51470298 6323 Ssh ssh = (Ssh) handle;
6324 if (ssh->version == 1) {
6325 if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
6326 ssh->v1_stdout_throttling = 0;
6327 ssh1_throttle(ssh, -1);
5471d09a 6328 }
6329 } else {
51470298 6330 if (ssh->mainchan && ssh->mainchan->closes == 0)
6331 ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
5471d09a 6332 }
6333}
6334
6b78788a 6335void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
d74d141c 6336{
6337 struct ssh_channel *c = (struct ssh_channel *)channel;
6b78788a 6338 Ssh ssh = c->ssh;
d74d141c 6339
57356d63 6340 logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
d74d141c 6341
51470298 6342 if (ssh->version == 1) {
6343 send_packet(ssh, SSH1_MSG_PORT_OPEN,
bc240b21 6344 PKT_INT, c->localid,
6345 PKT_STR, hostname,
6346 PKT_INT, port,
6347 //PKT_STR, <org:orgport>,
6348 PKT_END);
6349 } else {
51470298 6350 ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
6351 ssh2_pkt_addstring(ssh, "direct-tcpip");
6352 ssh2_pkt_adduint32(ssh, c->localid);
5471d09a 6353 c->v.v2.locwindow = OUR_V2_WINSIZE;
51470298 6354 ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);/* our window size */
6355 ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
6356 ssh2_pkt_addstring(ssh, hostname);
6357 ssh2_pkt_adduint32(ssh, port);
bc240b21 6358 /*
6359 * We make up values for the originator data; partly it's
6360 * too much hassle to keep track, and partly I'm not
6361 * convinced the server should be told details like that
6362 * about my local network configuration.
6363 */
51470298 6364 ssh2_pkt_addstring(ssh, "client-side-connection");
6365 ssh2_pkt_adduint32(ssh, 0);
6366 ssh2_pkt_send(ssh);
bc240b21 6367 }
d74d141c 6368}
6369
6370
51470298 6371static Socket ssh_socket(void *handle)
32874aea 6372{
51470298 6373 Ssh ssh = (Ssh) handle;
6374 return ssh->s;
32874aea 6375}
8ccc75b0 6376
51470298 6377static int ssh_sendok(void *handle)
32874aea 6378{
51470298 6379 Ssh ssh = (Ssh) handle;
6380 return ssh->send_ok;
32874aea 6381}
fb09bf1c 6382
51470298 6383static int ssh_ldisc(void *handle, int option)
32874aea 6384{
51470298 6385 Ssh ssh = (Ssh) handle;
32874aea 6386 if (option == LD_ECHO)
51470298 6387 return ssh->echoing;
32874aea 6388 if (option == LD_EDIT)
51470298 6389 return ssh->editing;
0965bee0 6390 return FALSE;
6391}
6392
b9d7bcad 6393static void ssh_provide_ldisc(void *handle, void *ldisc)
6394{
6395 Ssh ssh = (Ssh) handle;
6396 ssh->ldisc = ldisc;
6397}
6398
a8327734 6399static void ssh_provide_logctx(void *handle, void *logctx)
6400{
6401 Ssh ssh = (Ssh) handle;
6402 ssh->logctx = logctx;
6403}
6404
51470298 6405static int ssh_return_exitcode(void *handle)
6406{
6407 Ssh ssh = (Ssh) handle;
3bb2f322 6408 if (ssh->s != NULL)
6409 return -1;
6410 else
6411 return (ssh->exitcode >= 0 ? ssh->exitcode : 0);
51470298 6412}
6413
6414/*
6415 * Gross hack: pscp will try to start SFTP but fall back to scp1 if
6416 * that fails. This variable is the means by which scp.c can reach
6417 * into the SSH code and find out which one it got.
6418 */
6419extern int ssh_fallback_cmd(void *handle)
d8d6c7e5 6420{
51470298 6421 Ssh ssh = (Ssh) handle;
6422 return ssh->fallback_cmd;
d8d6c7e5 6423}
6424
374330e2 6425Backend ssh_backend = {
6426 ssh_init,
fabd1805 6427 ssh_free,
86916870 6428 ssh_reconfig,
374330e2 6429 ssh_send,
5471d09a 6430 ssh_sendbuffer,
374330e2 6431 ssh_size,
4017be6d 6432 ssh_special,
125105d1 6433 ssh_get_specials,
8ccc75b0 6434 ssh_socket,
d8d6c7e5 6435 ssh_return_exitcode,
97db3be4 6436 ssh_sendok,
0965bee0 6437 ssh_ldisc,
b9d7bcad 6438 ssh_provide_ldisc,
a8327734 6439 ssh_provide_logctx,
5471d09a 6440 ssh_unthrottle,
97db3be4 6441 22
bc240b21 6442};