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