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