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