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