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