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