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