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