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