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