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