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