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