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