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