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