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