]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
Unify GET_32BIT()/PUT_32BIT() et al from numerous source files into misc.h.
[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_WARN:
4919                 /* Flag for later. Don't bother if it's the last in
4920                  * the list. */
4921                 if (i < CIPHER_MAX - 1) {
4922                     s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
4923                 }
4924                 break;
4925             }
4926         }
4927
4928         /*
4929          * Set up preferred compression.
4930          */
4931         if (ssh->cfg.compression)
4932             s->preferred_comp = &ssh_zlib;
4933         else
4934             s->preferred_comp = &ssh_comp_none;
4935
4936         /*
4937          * Enable queueing of outgoing auth- or connection-layer
4938          * packets while we are in the middle of a key exchange.
4939          */
4940         ssh->queueing = TRUE;
4941
4942         /*
4943          * Flag that KEX is in progress.
4944          */
4945         ssh->kex_in_progress = TRUE;
4946
4947         /*
4948          * Construct and send our key exchange packet.
4949          */
4950         s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
4951         for (i = 0; i < 16; i++)
4952             ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
4953         /* List key exchange algorithms. */
4954         ssh2_pkt_addstring_start(s->pktout);
4955         commalist_started = 0;
4956         for (i = 0; i < s->n_preferred_kex; i++) {
4957             const struct ssh_kex *k = s->preferred_kex[i];
4958             if (!k) continue;          /* warning flag */
4959             if (commalist_started)
4960                 ssh2_pkt_addstring_str(s->pktout, ",");
4961             ssh2_pkt_addstring_str(s->pktout, s->preferred_kex[i]->name);
4962             commalist_started = 1;
4963         }
4964         /* List server host key algorithms. */
4965         ssh2_pkt_addstring_start(s->pktout);
4966         for (i = 0; i < lenof(hostkey_algs); i++) {
4967             ssh2_pkt_addstring_str(s->pktout, hostkey_algs[i]->name);
4968             if (i < lenof(hostkey_algs) - 1)
4969                 ssh2_pkt_addstring_str(s->pktout, ",");
4970         }
4971         /* List client->server encryption algorithms. */
4972         ssh2_pkt_addstring_start(s->pktout);
4973         commalist_started = 0;
4974         for (i = 0; i < s->n_preferred_ciphers; i++) {
4975             const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4976             if (!c) continue;          /* warning flag */
4977             for (j = 0; j < c->nciphers; j++) {
4978                 if (commalist_started)
4979                     ssh2_pkt_addstring_str(s->pktout, ",");
4980                 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4981                 commalist_started = 1;
4982             }
4983         }
4984         /* List server->client encryption algorithms. */
4985         ssh2_pkt_addstring_start(s->pktout);
4986         commalist_started = 0;
4987         for (i = 0; i < s->n_preferred_ciphers; i++) {
4988             const struct ssh2_ciphers *c = s->preferred_ciphers[i];
4989             if (!c) continue; /* warning flag */
4990             for (j = 0; j < c->nciphers; j++) {
4991                 if (commalist_started)
4992                     ssh2_pkt_addstring_str(s->pktout, ",");
4993                 ssh2_pkt_addstring_str(s->pktout, c->list[j]->name);
4994                 commalist_started = 1;
4995             }
4996         }
4997         /* List client->server MAC algorithms. */
4998         ssh2_pkt_addstring_start(s->pktout);
4999         for (i = 0; i < s->nmacs; i++) {
5000             ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5001             if (i < s->nmacs - 1)
5002                 ssh2_pkt_addstring_str(s->pktout, ",");
5003         }
5004         /* List server->client MAC algorithms. */
5005         ssh2_pkt_addstring_start(s->pktout);
5006         for (i = 0; i < s->nmacs; i++) {
5007             ssh2_pkt_addstring_str(s->pktout, s->maclist[i]->name);
5008             if (i < s->nmacs - 1)
5009                 ssh2_pkt_addstring_str(s->pktout, ",");
5010         }
5011         /* List client->server compression algorithms. */
5012         ssh2_pkt_addstring_start(s->pktout);
5013         assert(lenof(compressions) > 1);
5014         ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5015         for (i = 0; i < lenof(compressions); i++) {
5016             const struct ssh_compress *c = compressions[i];
5017             if (c != s->preferred_comp) {
5018                 ssh2_pkt_addstring_str(s->pktout, ",");
5019                 ssh2_pkt_addstring_str(s->pktout, c->name);
5020             }
5021         }
5022         /* List server->client compression algorithms. */
5023         ssh2_pkt_addstring_start(s->pktout);
5024         assert(lenof(compressions) > 1);
5025         ssh2_pkt_addstring_str(s->pktout, s->preferred_comp->name);
5026         for (i = 0; i < lenof(compressions); i++) {
5027             const struct ssh_compress *c = compressions[i];
5028             if (c != s->preferred_comp) {
5029                 ssh2_pkt_addstring_str(s->pktout, ",");
5030                 ssh2_pkt_addstring_str(s->pktout, c->name);
5031             }
5032         }
5033         /* List client->server languages. Empty list. */
5034         ssh2_pkt_addstring_start(s->pktout);
5035         /* List server->client languages. Empty list. */
5036         ssh2_pkt_addstring_start(s->pktout);
5037         /* First KEX packet does _not_ follow, because we're not that brave. */
5038         ssh2_pkt_addbool(s->pktout, FALSE);
5039         /* Reserved. */
5040         ssh2_pkt_adduint32(s->pktout, 0);
5041     }
5042
5043     ssh->exhash = ssh->exhashbase;
5044     sha_string(&ssh->exhash, s->pktout->data + 5, s->pktout->length - 5);
5045
5046     ssh2_pkt_send_noqueue(ssh, s->pktout);
5047
5048     if (!pktin)
5049         crWaitUntil(pktin);
5050     if (pktin->length > 5)
5051         sha_string(&ssh->exhash, pktin->data + 5, pktin->length - 5);
5052
5053     /*
5054      * Now examine the other side's KEXINIT to see what we're up
5055      * to.
5056      */
5057     {
5058         char *str, *preferred;
5059         int i, j, len;
5060
5061         if (pktin->type != SSH2_MSG_KEXINIT) {
5062             bombout(("expected key exchange packet from server"));
5063             crStop(0);
5064         }
5065         ssh->kex = NULL;
5066         ssh->hostkey = NULL;
5067         s->cscipher_tobe = NULL;
5068         s->sccipher_tobe = NULL;
5069         s->csmac_tobe = NULL;
5070         s->scmac_tobe = NULL;
5071         s->cscomp_tobe = NULL;
5072         s->sccomp_tobe = NULL;
5073         s->warn_kex = s->warn_cscipher = s->warn_sccipher = FALSE;
5074
5075         pktin->savedpos += 16;          /* skip garbage cookie */
5076         ssh_pkt_getstring(pktin, &str, &len);    /* key exchange algorithms */
5077
5078         preferred = NULL;
5079         for (i = 0; i < s->n_preferred_kex; i++) {
5080             const struct ssh_kex *k = s->preferred_kex[i];
5081             if (!k) {
5082                 s->warn_kex = TRUE;
5083             } else {
5084                 if (!preferred) preferred = k->name;
5085                 if (in_commasep_string(k->name, str, len))
5086                     ssh->kex = k;
5087             }
5088             if (ssh->kex)
5089                 break;
5090         }
5091         if (!ssh->kex) {
5092             bombout(("Couldn't agree a key exchange algorithm (available: %s)",
5093                      str ? str : "(null)"));
5094             crStop(0);
5095         }
5096         /*
5097          * Note that the server's guess is considered wrong if it doesn't match
5098          * the first algorithm in our list, even if it's still the algorithm
5099          * we end up using.
5100          */
5101         s->guessok = first_in_commasep_string(preferred, str, len);
5102         ssh_pkt_getstring(pktin, &str, &len);    /* host key algorithms */
5103         for (i = 0; i < lenof(hostkey_algs); i++) {
5104             if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
5105                 ssh->hostkey = hostkey_algs[i];
5106                 break;
5107             }
5108         }
5109         s->guessok = s->guessok &&
5110             first_in_commasep_string(hostkey_algs[0]->name, str, len);
5111         ssh_pkt_getstring(pktin, &str, &len);    /* client->server cipher */
5112         for (i = 0; i < s->n_preferred_ciphers; i++) {
5113             const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5114             if (!c) {
5115                 s->warn_cscipher = TRUE;
5116             } else {
5117                 for (j = 0; j < c->nciphers; j++) {
5118                     if (in_commasep_string(c->list[j]->name, str, len)) {
5119                         s->cscipher_tobe = c->list[j];
5120                         break;
5121                     }
5122                 }
5123             }
5124             if (s->cscipher_tobe)
5125                 break;
5126         }
5127         if (!s->cscipher_tobe) {
5128             bombout(("Couldn't agree a client-to-server cipher (available: %s)",
5129                      str ? str : "(null)"));
5130             crStop(0);
5131         }
5132
5133         ssh_pkt_getstring(pktin, &str, &len);    /* server->client cipher */
5134         for (i = 0; i < s->n_preferred_ciphers; i++) {
5135             const struct ssh2_ciphers *c = s->preferred_ciphers[i];
5136             if (!c) {
5137                 s->warn_sccipher = TRUE;
5138             } else {
5139                 for (j = 0; j < c->nciphers; j++) {
5140                     if (in_commasep_string(c->list[j]->name, str, len)) {
5141                         s->sccipher_tobe = c->list[j];
5142                         break;
5143                     }
5144                 }
5145             }
5146             if (s->sccipher_tobe)
5147                 break;
5148         }
5149         if (!s->sccipher_tobe) {
5150             bombout(("Couldn't agree a server-to-client cipher (available: %s)",
5151                      str ? str : "(null)"));
5152             crStop(0);
5153         }
5154
5155         ssh_pkt_getstring(pktin, &str, &len);    /* client->server mac */
5156         for (i = 0; i < s->nmacs; i++) {
5157             if (in_commasep_string(s->maclist[i]->name, str, len)) {
5158                 s->csmac_tobe = s->maclist[i];
5159                 break;
5160             }
5161         }
5162         ssh_pkt_getstring(pktin, &str, &len);    /* server->client mac */
5163         for (i = 0; i < s->nmacs; i++) {
5164             if (in_commasep_string(s->maclist[i]->name, str, len)) {
5165                 s->scmac_tobe = s->maclist[i];
5166                 break;
5167             }
5168         }
5169         ssh_pkt_getstring(pktin, &str, &len);  /* client->server compression */
5170         for (i = 0; i < lenof(compressions) + 1; i++) {
5171             const struct ssh_compress *c =
5172                 i == 0 ? s->preferred_comp : compressions[i - 1];
5173             if (in_commasep_string(c->name, str, len)) {
5174                 s->cscomp_tobe = c;
5175                 break;
5176             }
5177         }
5178         ssh_pkt_getstring(pktin, &str, &len);  /* server->client compression */
5179         for (i = 0; i < lenof(compressions) + 1; i++) {
5180             const struct ssh_compress *c =
5181                 i == 0 ? s->preferred_comp : compressions[i - 1];
5182             if (in_commasep_string(c->name, str, len)) {
5183                 s->sccomp_tobe = c;
5184                 break;
5185             }
5186         }
5187         ssh_pkt_getstring(pktin, &str, &len);  /* client->server language */
5188         ssh_pkt_getstring(pktin, &str, &len);  /* server->client language */
5189         s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
5190
5191         if (s->warn_kex) {
5192             ssh_set_frozen(ssh, 1);
5193             s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
5194                                ssh->kex->name,
5195                                ssh_dialog_callback, ssh);
5196             if (s->dlgret < 0) {
5197                 do {
5198                     crReturn(0);
5199                     if (pktin) {
5200                         bombout(("Unexpected data from server while"
5201                                  " waiting for user response"));
5202                         crStop(0);
5203                     }
5204                 } while (pktin || inlen > 0);
5205                 s->dlgret = ssh->user_response;
5206             }
5207             ssh_set_frozen(ssh, 0);
5208             if (s->dlgret == 0) {
5209                 ssh->close_expected = TRUE;
5210                 ssh_closing((Plug)ssh, NULL, 0, 0);
5211                 crStop(0);
5212             }
5213         }
5214
5215         if (s->warn_cscipher) {
5216             ssh_set_frozen(ssh, 1);
5217             s->dlgret = askalg(ssh->frontend,
5218                                "client-to-server cipher",
5219                                s->cscipher_tobe->name,
5220                                ssh_dialog_callback, ssh);
5221             if (s->dlgret < 0) {
5222                 do {
5223                     crReturn(0);
5224                     if (pktin) {
5225                         bombout(("Unexpected data from server while"
5226                                  " waiting for user response"));
5227                         crStop(0);
5228                     }
5229                 } while (pktin || inlen > 0);
5230                 s->dlgret = ssh->user_response;
5231             }
5232             ssh_set_frozen(ssh, 0);
5233             if (s->dlgret == 0) {
5234                 ssh->close_expected = TRUE;
5235                 ssh_closing((Plug)ssh, NULL, 0, 0);
5236                 crStop(0);
5237             }
5238         }
5239
5240         if (s->warn_sccipher) {
5241             ssh_set_frozen(ssh, 1);
5242             s->dlgret = askalg(ssh->frontend,
5243                                "server-to-client cipher",
5244                                s->sccipher_tobe->name,
5245                                ssh_dialog_callback, ssh);
5246             if (s->dlgret < 0) {
5247                 do {
5248                     crReturn(0);
5249                     if (pktin) {
5250                         bombout(("Unexpected data from server while"
5251                                  " waiting for user response"));
5252                         crStop(0);
5253                     }
5254                 } while (pktin || inlen > 0);
5255                 s->dlgret = ssh->user_response;
5256             }
5257             ssh_set_frozen(ssh, 0);
5258             if (s->dlgret == 0) {
5259                 ssh->close_expected = TRUE;
5260                 ssh_closing((Plug)ssh, NULL, 0, 0);
5261                 crStop(0);
5262             }
5263         }
5264
5265         if (s->ignorepkt) /* first_kex_packet_follows */
5266             crWaitUntil(pktin);                /* Ignore packet */
5267     }
5268
5269     /*
5270      * Work out the number of bits of key we will need from the key
5271      * exchange. We start with the maximum key length of either
5272      * cipher...
5273      */
5274     {
5275         int csbits, scbits;
5276
5277         csbits = s->cscipher_tobe->keylen;
5278         scbits = s->sccipher_tobe->keylen;
5279         s->nbits = (csbits > scbits ? csbits : scbits);
5280     }
5281     /* The keys only have 160-bit entropy, since they're based on
5282      * a SHA-1 hash. So cap the key size at 160 bits. */
5283     if (s->nbits > 160)
5284         s->nbits = 160;
5285
5286     /*
5287      * If we're doing Diffie-Hellman group exchange, start by
5288      * requesting a group.
5289      */
5290     if (!ssh->kex->pdata) {
5291         logevent("Doing Diffie-Hellman group exchange");
5292         ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
5293         /*
5294          * Work out how big a DH group we will need to allow that
5295          * much data.
5296          */
5297         s->pbits = 512 << ((s->nbits - 1) / 64);
5298         s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
5299         ssh2_pkt_adduint32(s->pktout, s->pbits);
5300         ssh2_pkt_send_noqueue(ssh, s->pktout);
5301
5302         crWaitUntil(pktin);
5303         if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
5304             bombout(("expected key exchange group packet from server"));
5305             crStop(0);
5306         }
5307         s->p = ssh2_pkt_getmp(pktin);
5308         s->g = ssh2_pkt_getmp(pktin);
5309         if (!s->p || !s->g) {
5310             bombout(("unable to read mp-ints from incoming group packet"));
5311             crStop(0);
5312         }
5313         ssh->kex_ctx = dh_setup_gex(s->p, s->g);
5314         s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
5315         s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
5316     } else {
5317         ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP;
5318         ssh->kex_ctx = dh_setup_group(ssh->kex);
5319         s->kex_init_value = SSH2_MSG_KEXDH_INIT;
5320         s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
5321         logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
5322                   ssh->kex->groupname);
5323     }
5324
5325     logevent("Doing Diffie-Hellman key exchange");
5326     /*
5327      * Now generate and send e for Diffie-Hellman.
5328      */
5329     set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
5330     s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
5331     s->pktout = ssh2_pkt_init(s->kex_init_value);
5332     ssh2_pkt_addmp(s->pktout, s->e);
5333     ssh2_pkt_send_noqueue(ssh, s->pktout);
5334
5335     set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
5336     crWaitUntil(pktin);
5337     if (pktin->type != s->kex_reply_value) {
5338         bombout(("expected key exchange reply packet from server"));
5339         crStop(0);
5340     }
5341     set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
5342     ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
5343     s->f = ssh2_pkt_getmp(pktin);
5344     if (!s->f) {
5345         bombout(("unable to parse key exchange reply packet"));
5346         crStop(0);
5347     }
5348     ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
5349
5350     s->K = dh_find_K(ssh->kex_ctx, s->f);
5351
5352     /* We assume everything from now on will be quick, and it might
5353      * involve user interaction. */
5354     set_busy_status(ssh->frontend, BUSY_NOT);
5355
5356     sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
5357     if (ssh->kex == &ssh_diffiehellman_gex) {
5358         sha_uint32(&ssh->exhash, s->pbits);
5359         sha_mpint(&ssh->exhash, s->p);
5360         sha_mpint(&ssh->exhash, s->g);
5361     }
5362     sha_mpint(&ssh->exhash, s->e);
5363     sha_mpint(&ssh->exhash, s->f);
5364     sha_mpint(&ssh->exhash, s->K);
5365     SHA_Final(&ssh->exhash, s->exchange_hash);
5366
5367     dh_cleanup(ssh->kex_ctx);
5368     ssh->kex_ctx = NULL;
5369
5370 #if 0
5371     debug(("Exchange hash is:\n"));
5372     dmemdump(s->exchange_hash, 20);
5373 #endif
5374
5375     s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
5376     if (!s->hkey ||
5377         !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
5378                                  (char *)s->exchange_hash, 20)) {
5379         bombout(("Server's host key did not match the signature supplied"));
5380         crStop(0);
5381     }
5382
5383     /*
5384      * Authenticate remote host: verify host key. (We've already
5385      * checked the signature of the exchange hash.)
5386      */
5387     s->keystr = ssh->hostkey->fmtkey(s->hkey);
5388     s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
5389     ssh_set_frozen(ssh, 1);
5390     s->dlgret = verify_ssh_host_key(ssh->frontend,
5391                                     ssh->savedhost, ssh->savedport,
5392                                     ssh->hostkey->keytype, s->keystr,
5393                                     s->fingerprint,
5394                                     ssh_dialog_callback, ssh);
5395     if (s->dlgret < 0) {
5396         do {
5397             crReturn(0);
5398             if (pktin) {
5399                 bombout(("Unexpected data from server while waiting"
5400                          " for user host key response"));
5401                     crStop(0);
5402             }
5403         } while (pktin || inlen > 0);
5404         s->dlgret = ssh->user_response;
5405     }
5406     ssh_set_frozen(ssh, 0);
5407     if (s->dlgret == 0) {
5408         ssh->close_expected = TRUE;
5409         ssh_closing((Plug)ssh, NULL, 0, 0);
5410         crStop(0);
5411     }
5412     if (!s->got_session_id) {     /* don't bother logging this in rekeys */
5413         logevent("Host key fingerprint is:");
5414         logevent(s->fingerprint);
5415     }
5416     sfree(s->fingerprint);
5417     sfree(s->keystr);
5418     ssh->hostkey->freekey(s->hkey);
5419
5420     /*
5421      * The exchange hash from the very first key exchange is also
5422      * the session id, used in session key construction and
5423      * authentication.
5424      */
5425     if (!s->got_session_id) {
5426         memcpy(ssh->v2_session_id, s->exchange_hash,
5427                sizeof(s->exchange_hash));
5428         s->got_session_id = TRUE;
5429     }
5430
5431     /*
5432      * Send SSH2_MSG_NEWKEYS.
5433      */
5434     s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
5435     ssh2_pkt_send_noqueue(ssh, s->pktout);
5436     ssh->outgoing_data_size = 0;       /* start counting from here */
5437
5438     /*
5439      * We've sent client NEWKEYS, so create and initialise
5440      * client-to-server session keys.
5441      */
5442     if (ssh->cs_cipher_ctx)
5443         ssh->cscipher->free_context(ssh->cs_cipher_ctx);
5444     ssh->cscipher = s->cscipher_tobe;
5445     ssh->cs_cipher_ctx = ssh->cscipher->make_context();
5446
5447     if (ssh->cs_mac_ctx)
5448         ssh->csmac->free_context(ssh->cs_mac_ctx);
5449     ssh->csmac = s->csmac_tobe;
5450     ssh->cs_mac_ctx = ssh->csmac->make_context();
5451
5452     if (ssh->cs_comp_ctx)
5453         ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
5454     ssh->cscomp = s->cscomp_tobe;
5455     ssh->cs_comp_ctx = ssh->cscomp->compress_init();
5456
5457     /*
5458      * Set IVs on client-to-server keys. Here we use the exchange
5459      * hash from the _first_ key exchange.
5460      */
5461     {
5462         unsigned char keyspace[40];
5463         ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
5464         ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
5465         ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
5466         ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
5467         ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
5468         ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
5469     }
5470
5471     logeventf(ssh, "Initialised %.200s client->server encryption",
5472               ssh->cscipher->text_name);
5473     logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
5474               ssh->csmac->text_name);
5475     if (ssh->cscomp->text_name)
5476         logeventf(ssh, "Initialised %s compression",
5477                   ssh->cscomp->text_name);
5478
5479     /*
5480      * Now our end of the key exchange is complete, we can send all
5481      * our queued higher-layer packets.
5482      */
5483     ssh->queueing = FALSE;
5484     ssh2_pkt_queuesend(ssh);
5485
5486     /*
5487      * Expect SSH2_MSG_NEWKEYS from server.
5488      */
5489     crWaitUntil(pktin);
5490     if (pktin->type != SSH2_MSG_NEWKEYS) {
5491         bombout(("expected new-keys packet from server"));
5492         crStop(0);
5493     }
5494     ssh->incoming_data_size = 0;       /* start counting from here */
5495
5496     /*
5497      * We've seen server NEWKEYS, so create and initialise
5498      * server-to-client session keys.
5499      */
5500     if (ssh->sc_cipher_ctx)
5501         ssh->sccipher->free_context(ssh->sc_cipher_ctx);
5502     ssh->sccipher = s->sccipher_tobe;
5503     ssh->sc_cipher_ctx = ssh->sccipher->make_context();
5504
5505     if (ssh->sc_mac_ctx)
5506         ssh->scmac->free_context(ssh->sc_mac_ctx);
5507     ssh->scmac = s->scmac_tobe;
5508     ssh->sc_mac_ctx = ssh->scmac->make_context();
5509
5510     if (ssh->sc_comp_ctx)
5511         ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
5512     ssh->sccomp = s->sccomp_tobe;
5513     ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
5514
5515     /*
5516      * Set IVs on server-to-client keys. Here we use the exchange
5517      * hash from the _first_ key exchange.
5518      */
5519     {
5520         unsigned char keyspace[40];
5521         ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
5522         ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
5523         ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
5524         ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
5525         ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
5526         ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
5527     }
5528     logeventf(ssh, "Initialised %.200s server->client encryption",
5529               ssh->sccipher->text_name);
5530     logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
5531               ssh->scmac->text_name);
5532     if (ssh->sccomp->text_name)
5533         logeventf(ssh, "Initialised %s decompression",
5534                   ssh->sccomp->text_name);
5535
5536     /*
5537      * Free key exchange data.
5538      */
5539     freebn(s->f);
5540     freebn(s->K);
5541     if (ssh->kex == &ssh_diffiehellman_gex) {
5542         freebn(s->g);
5543         freebn(s->p);
5544     }
5545
5546     /*
5547      * Key exchange is over. Loop straight back round if we have a
5548      * deferred rekey reason.
5549      */
5550     if (ssh->deferred_rekey_reason) {
5551         logevent(ssh->deferred_rekey_reason);
5552         pktin = NULL;
5553         ssh->deferred_rekey_reason = NULL;
5554         goto begin_key_exchange;
5555     }
5556
5557     /*
5558      * Otherwise, schedule a timer for our next rekey.
5559      */
5560     ssh->kex_in_progress = FALSE;
5561     ssh->last_rekey = GETTICKCOUNT();
5562     if (ssh->cfg.ssh_rekey_time != 0)
5563         ssh->next_rekey = schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
5564                                          ssh2_timer, ssh);
5565
5566     /*
5567      * If this is the first key exchange phase, we must pass the
5568      * SSH2_MSG_NEWKEYS packet to the next layer, not because it
5569      * wants to see it but because it will need time to initialise
5570      * itself before it sees an actual packet. In subsequent key
5571      * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
5572      * it would only confuse the layer above.
5573      */
5574     if (s->activated_authconn) {
5575         crReturn(1);
5576     }
5577     s->activated_authconn = TRUE;
5578
5579     /*
5580      * Now we're encrypting. Begin returning 1 to the protocol main
5581      * function so that other things can run on top of the
5582      * transport. If we ever see a KEXINIT, we must go back to the
5583      * start.
5584      * 
5585      * We _also_ go back to the start if we see pktin==NULL and
5586      * inlen==-1, because this is a special signal meaning
5587      * `initiate client-driven rekey', and `in' contains a message
5588      * giving the reason for the rekey.
5589      */
5590     while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
5591              (!pktin && inlen == -1))) {
5592         wait_for_rekey:
5593         crReturn(1);
5594     }
5595     if (pktin) {
5596         logevent("Server initiated key re-exchange");
5597     } else {
5598         /*
5599          * Special case: if the server bug is set that doesn't
5600          * allow rekeying, we give a different log message and
5601          * continue waiting. (If such a server _initiates_ a rekey,
5602          * we process it anyway!)
5603          */
5604         if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
5605             logeventf(ssh, "Server bug prevents key re-exchange (%s)",
5606                       (char *)in);
5607             /* Reset the counters, so that at least this message doesn't
5608              * hit the event log _too_ often. */
5609             ssh->outgoing_data_size = 0;
5610             ssh->incoming_data_size = 0;
5611             if (ssh->cfg.ssh_rekey_time != 0) {
5612                 ssh->next_rekey =
5613                     schedule_timer(ssh->cfg.ssh_rekey_time*60*TICKSPERSEC,
5614                                    ssh2_timer, ssh);
5615             }
5616             goto wait_for_rekey;       /* this is utterly horrid */
5617         } else {
5618             logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
5619         }
5620     }
5621     goto begin_key_exchange;
5622
5623     crFinish(1);
5624 }
5625
5626 /*
5627  * Add data to an SSH-2 channel output buffer.
5628  */
5629 static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
5630                                   int len)
5631 {
5632     bufchain_add(&c->v.v2.outbuffer, buf, len);
5633 }
5634
5635 /*
5636  * Attempt to send data on an SSH-2 channel.
5637  */
5638 static int ssh2_try_send(struct ssh_channel *c)
5639 {
5640     Ssh ssh = c->ssh;
5641     struct Packet *pktout;
5642
5643     while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
5644         int len;
5645         void *data;
5646         bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
5647         if ((unsigned)len > c->v.v2.remwindow)
5648             len = c->v.v2.remwindow;
5649         if ((unsigned)len > c->v.v2.remmaxpkt)
5650             len = c->v.v2.remmaxpkt;
5651         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
5652         ssh2_pkt_adduint32(pktout, c->remoteid);
5653         dont_log_data(ssh, pktout, PKTLOG_OMIT);
5654         ssh2_pkt_addstring_start(pktout);
5655         ssh2_pkt_addstring_data(pktout, data, len);
5656         end_log_omission(ssh, pktout);
5657         ssh2_pkt_send(ssh, pktout);
5658         bufchain_consume(&c->v.v2.outbuffer, len);
5659         c->v.v2.remwindow -= len;
5660     }
5661
5662     /*
5663      * After having sent as much data as we can, return the amount
5664      * still buffered.
5665      */
5666     return bufchain_size(&c->v.v2.outbuffer);
5667 }
5668
5669 static void ssh2_try_send_and_unthrottle(struct ssh_channel *c)
5670 {
5671     int bufsize;
5672     if (c->closes)
5673         return;                        /* don't send on closing channels */
5674     bufsize = ssh2_try_send(c);
5675     if (bufsize == 0) {
5676         switch (c->type) {
5677           case CHAN_MAINSESSION:
5678             /* stdin need not receive an unthrottle
5679              * notification since it will be polled */
5680             break;
5681           case CHAN_X11:
5682             x11_unthrottle(c->u.x11.s);
5683             break;
5684           case CHAN_AGENT:
5685             /* agent sockets are request/response and need no
5686              * buffer management */
5687             break;
5688           case CHAN_SOCKDATA:
5689             pfd_unthrottle(c->u.pfd.s);
5690             break;
5691         }
5692     }
5693 }
5694
5695 /*
5696  * Potentially enlarge the window on an SSH-2 channel.
5697  */
5698 static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
5699 {
5700     Ssh ssh = c->ssh;
5701
5702     /*
5703      * Never send WINDOW_ADJUST for a channel that the remote side
5704      * already thinks it's closed; there's no point, since it won't
5705      * be sending any more data anyway.
5706      */
5707     if (c->closes != 0)
5708         return;
5709
5710     /*
5711      * Only send a WINDOW_ADJUST if there's significantly more window
5712      * available than the other end thinks there is.  This saves us
5713      * sending a WINDOW_ADJUST for every character in a shell session.
5714      *
5715      * "Significant" is arbitrarily defined as half the window size.
5716      */
5717     if (newwin > c->v.v2.locwindow * 2) {
5718         struct Packet *pktout;
5719
5720         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
5721         ssh2_pkt_adduint32(pktout, c->remoteid);
5722         ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
5723         ssh2_pkt_send(ssh, pktout);
5724         c->v.v2.locwindow = newwin;
5725     }
5726 }
5727
5728 static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
5729 {
5730     unsigned i = ssh_pkt_getuint32(pktin);
5731     struct ssh_channel *c;
5732     c = find234(ssh->channels, &i, ssh_channelfind);
5733     if (c && !c->closes) {
5734         c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
5735         ssh2_try_send_and_unthrottle(c);
5736     }
5737 }
5738
5739 static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
5740 {
5741     char *data;
5742     int length;
5743     unsigned i = ssh_pkt_getuint32(pktin);
5744     struct ssh_channel *c;
5745     c = find234(ssh->channels, &i, ssh_channelfind);
5746     if (!c)
5747         return;                        /* nonexistent channel */
5748     if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
5749         ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
5750         return;                        /* extended but not stderr */
5751     ssh_pkt_getstring(pktin, &data, &length);
5752     if (data) {
5753         int bufsize = 0;
5754         c->v.v2.locwindow -= length;
5755         switch (c->type) {
5756           case CHAN_MAINSESSION:
5757             bufsize =
5758                 from_backend(ssh->frontend, pktin->type ==
5759                              SSH2_MSG_CHANNEL_EXTENDED_DATA,
5760                              data, length);
5761             break;
5762           case CHAN_X11:
5763             bufsize = x11_send(c->u.x11.s, data, length);
5764             break;
5765           case CHAN_SOCKDATA:
5766             bufsize = pfd_send(c->u.pfd.s, data, length);
5767             break;
5768           case CHAN_AGENT:
5769             while (length > 0) {
5770                 if (c->u.a.lensofar < 4) {
5771                     unsigned int l = min(4 - c->u.a.lensofar, length);
5772                     memcpy(c->u.a.msglen + c->u.a.lensofar,
5773                            data, l);
5774                     data += l;
5775                     length -= l;
5776                     c->u.a.lensofar += l;
5777                 }
5778                 if (c->u.a.lensofar == 4) {
5779                     c->u.a.totallen =
5780                         4 + GET_32BIT(c->u.a.msglen);
5781                     c->u.a.message = snewn(c->u.a.totallen,
5782                                            unsigned char);
5783                     memcpy(c->u.a.message, c->u.a.msglen, 4);
5784                 }
5785                 if (c->u.a.lensofar >= 4 && length > 0) {
5786                     unsigned int l =
5787                         min(c->u.a.totallen - c->u.a.lensofar,
5788                             length);
5789                     memcpy(c->u.a.message + c->u.a.lensofar,
5790                            data, l);
5791                     data += l;
5792                     length -= l;
5793                     c->u.a.lensofar += l;
5794                 }
5795                 if (c->u.a.lensofar == c->u.a.totallen) {
5796                     void *reply;
5797                     int replylen;
5798                     if (agent_query(c->u.a.message,
5799                                     c->u.a.totallen,
5800                                     &reply, &replylen,
5801                                     ssh_agentf_callback, c))
5802                         ssh_agentf_callback(c, reply, replylen);
5803                     sfree(c->u.a.message);
5804                     c->u.a.lensofar = 0;
5805                 }
5806             }
5807             bufsize = 0;
5808             break;
5809         }
5810         /*
5811          * If we are not buffering too much data,
5812          * enlarge the window again at the remote side.
5813          */
5814         if (bufsize < OUR_V2_WINSIZE)
5815             ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
5816     }
5817 }
5818
5819 static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
5820 {
5821     unsigned i = ssh_pkt_getuint32(pktin);
5822     struct ssh_channel *c;
5823
5824     c = find234(ssh->channels, &i, ssh_channelfind);
5825     if (!c)
5826         return;                        /* nonexistent channel */
5827
5828     if (c->type == CHAN_X11) {
5829         /*
5830          * Remote EOF on an X11 channel means we should
5831          * wrap up and close the channel ourselves.
5832          */
5833         x11_close(c->u.x11.s);
5834         sshfwd_close(c);
5835     } else if (c->type == CHAN_AGENT) {
5836         sshfwd_close(c);
5837     } else if (c->type == CHAN_SOCKDATA) {
5838         pfd_close(c->u.pfd.s);
5839         sshfwd_close(c);
5840     }
5841 }
5842
5843 static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
5844 {
5845     unsigned i = ssh_pkt_getuint32(pktin);
5846     struct ssh_channel *c;
5847     struct Packet *pktout;
5848
5849     c = find234(ssh->channels, &i, ssh_channelfind);
5850     if (!c || c->halfopen) {
5851         bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
5852                  c ? "half-open" : "nonexistent", i));
5853         return;
5854     }
5855     /* Do pre-close processing on the channel. */
5856     switch (c->type) {
5857       case CHAN_MAINSESSION:
5858         ssh->mainchan = NULL;
5859         update_specials_menu(ssh->frontend);
5860         break;
5861       case CHAN_X11:
5862         if (c->u.x11.s != NULL)
5863             x11_close(c->u.x11.s);
5864         sshfwd_close(c);
5865         break;
5866       case CHAN_AGENT:
5867         sshfwd_close(c);
5868         break;
5869       case CHAN_SOCKDATA:
5870         if (c->u.pfd.s != NULL)
5871             pfd_close(c->u.pfd.s);
5872         sshfwd_close(c);
5873         break;
5874     }
5875     if (c->closes == 0) {
5876         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5877         ssh2_pkt_adduint32(pktout, c->remoteid);
5878         ssh2_pkt_send(ssh, pktout);
5879     }
5880     del234(ssh->channels, c);
5881     bufchain_clear(&c->v.v2.outbuffer);
5882     sfree(c);
5883
5884     /*
5885      * See if that was the last channel left open.
5886      * (This is only our termination condition if we're
5887      * not running in -N mode.)
5888      */
5889     if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
5890         logevent("All channels closed. Disconnecting");
5891 #if 0
5892         /*
5893          * We used to send SSH_MSG_DISCONNECT here,
5894          * because I'd believed that _every_ conforming
5895          * SSH-2 connection had to end with a disconnect
5896          * being sent by at least one side; apparently
5897          * I was wrong and it's perfectly OK to
5898          * unceremoniously slam the connection shut
5899          * when you're done, and indeed OpenSSH feels
5900          * this is more polite than sending a
5901          * DISCONNECT. So now we don't.
5902          */
5903         s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
5904         ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
5905         ssh2_pkt_addstring(s->pktout, "All open channels closed");
5906         ssh2_pkt_addstring(s->pktout, "en");    /* language tag */
5907         ssh2_pkt_send_noqueue(ssh, s->pktout);
5908 #endif
5909         ssh->close_expected = TRUE;
5910         ssh_closing((Plug)ssh, NULL, 0, 0);
5911     }
5912 }
5913
5914 static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
5915 {
5916     unsigned i = ssh_pkt_getuint32(pktin);
5917     struct ssh_channel *c;
5918     struct Packet *pktout;
5919
5920     c = find234(ssh->channels, &i, ssh_channelfind);
5921     if (!c)
5922         return;                        /* nonexistent channel */
5923     if (c->type != CHAN_SOCKDATA_DORMANT)
5924         return;                        /* dunno why they're confirming this */
5925     c->remoteid = ssh_pkt_getuint32(pktin);
5926     c->halfopen = FALSE;
5927     c->type = CHAN_SOCKDATA;
5928     c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
5929     c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
5930     if (c->u.pfd.s)
5931         pfd_confirm(c->u.pfd.s);
5932     if (c->closes) {
5933         /*
5934          * We have a pending close on this channel,
5935          * which we decided on before the server acked
5936          * the channel open. So now we know the
5937          * remoteid, we can close it again.
5938          */
5939         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
5940         ssh2_pkt_adduint32(pktout, c->remoteid);
5941         ssh2_pkt_send(ssh, pktout);
5942     }
5943 }
5944
5945 static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
5946 {
5947     static const char *const reasons[] = {
5948         "<unknown reason code>",
5949             "Administratively prohibited",
5950             "Connect failed",
5951             "Unknown channel type",
5952             "Resource shortage",
5953     };
5954     unsigned i = ssh_pkt_getuint32(pktin);
5955     unsigned reason_code;
5956     char *reason_string;
5957     int reason_length;
5958     struct ssh_channel *c;
5959     c = find234(ssh->channels, &i, ssh_channelfind);
5960     if (!c)
5961         return;                        /* nonexistent channel */
5962     if (c->type != CHAN_SOCKDATA_DORMANT)
5963         return;                        /* dunno why they're failing this */
5964
5965     reason_code = ssh_pkt_getuint32(pktin);
5966     if (reason_code >= lenof(reasons))
5967         reason_code = 0; /* ensure reasons[reason_code] in range */
5968     ssh_pkt_getstring(pktin, &reason_string, &reason_length);
5969     logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
5970               reasons[reason_code], reason_length, reason_string);
5971
5972     pfd_close(c->u.pfd.s);
5973
5974     del234(ssh->channels, c);
5975     sfree(c);
5976 }
5977
5978 static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
5979 {
5980     unsigned localid;
5981     char *type;
5982     int typelen, want_reply;
5983     int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
5984     struct ssh_channel *c;
5985     struct Packet *pktout;
5986
5987     localid = ssh_pkt_getuint32(pktin);
5988     ssh_pkt_getstring(pktin, &type, &typelen);
5989     want_reply = ssh2_pkt_getbool(pktin);
5990
5991     /*
5992      * First, check that the channel exists. Otherwise,
5993      * we can instantly disconnect with a rude message.
5994      */
5995     c = find234(ssh->channels, &localid, ssh_channelfind);
5996     if (!c) {
5997         char buf[80];
5998         sprintf(buf, "Received channel request for nonexistent"
5999                 " channel %d", localid);
6000         logevent(buf);
6001         pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6002         ssh2_pkt_adduint32(pktout, SSH2_DISCONNECT_BY_APPLICATION);
6003         ssh2_pkt_addstring(pktout, buf);
6004         ssh2_pkt_addstring(pktout, "en");       /* language tag */
6005         ssh2_pkt_send_noqueue(ssh, pktout);
6006         connection_fatal(ssh->frontend, "%s", buf);
6007         ssh->close_expected = TRUE;
6008         ssh_closing((Plug)ssh, NULL, 0, 0);
6009         return;
6010     }
6011
6012     /*
6013      * Having got the channel number, we now look at
6014      * the request type string to see if it's something
6015      * we recognise.
6016      */
6017     if (c == ssh->mainchan) {
6018         /*
6019          * We recognise "exit-status" and "exit-signal" on
6020          * the primary channel.
6021          */
6022         if (typelen == 11 &&
6023             !memcmp(type, "exit-status", 11)) {
6024
6025             ssh->exitcode = ssh_pkt_getuint32(pktin);
6026             logeventf(ssh, "Server sent command exit status %d",
6027                       ssh->exitcode);
6028             reply = SSH2_MSG_CHANNEL_SUCCESS;
6029
6030         } else if (typelen == 11 &&
6031                    !memcmp(type, "exit-signal", 11)) {
6032
6033             int is_plausible = TRUE, is_int = FALSE;
6034             char *fmt_sig = "", *fmt_msg = "";
6035             char *msg;
6036             int msglen = 0, core = FALSE;
6037             /* ICK: older versions of OpenSSH (e.g. 3.4p1)
6038              * provide an `int' for the signal, despite its
6039              * having been a `string' in the drafts since at
6040              * least 2001. (Fixed in session.c 1.147.) Try to
6041              * infer which we can safely parse it as. */
6042             {
6043                 unsigned char *p = pktin->body +
6044                     pktin->savedpos;
6045                 long len = pktin->length - pktin->savedpos;
6046                 unsigned long num = GET_32BIT(p); /* what is it? */
6047                 /* If it's 0, it hardly matters; assume string */
6048                 if (num == 0) {
6049                     is_int = FALSE;
6050                 } else {
6051                     int maybe_int = FALSE, maybe_str = FALSE;
6052 #define CHECK_HYPOTHESIS(offset, result) \
6053     do { \
6054         long q = offset; \
6055         if (q >= 0 && q+4 <= len) { \
6056             q = q + 4 + GET_32BIT(p+q); \
6057             if (q >= 0 && q+4 <= len && \
6058                     ((q = q + 4 + GET_32BIT(p+q))!= 0) && q == len) \
6059                 result = TRUE; \
6060         } \
6061     } while(0)
6062                     CHECK_HYPOTHESIS(4+1, maybe_int);
6063                     CHECK_HYPOTHESIS(4+num+1, maybe_str);
6064 #undef CHECK_HYPOTHESIS
6065                     if (maybe_int && !maybe_str)
6066                         is_int = TRUE;
6067                     else if (!maybe_int && maybe_str)
6068                         is_int = FALSE;
6069                     else
6070                         /* Crikey. Either or neither. Panic. */
6071                         is_plausible = FALSE;
6072                 }
6073             }
6074             if (is_plausible) {
6075                 if (is_int) {
6076                     /* Old non-standard OpenSSH. */
6077                     int signum = ssh_pkt_getuint32(pktin);
6078                     fmt_sig = dupprintf(" %d", signum);
6079                 } else {
6080                     /* As per the drafts. */
6081                     char *sig;
6082                     int siglen;
6083                     ssh_pkt_getstring(pktin, &sig, &siglen);
6084                     /* Signal name isn't supposed to be blank, but
6085                      * let's cope gracefully if it is. */
6086                     if (siglen) {
6087                         fmt_sig = dupprintf(" \"%.*s\"",
6088                                             siglen, sig);
6089                     }
6090                 }
6091                 core = ssh2_pkt_getbool(pktin);
6092                 ssh_pkt_getstring(pktin, &msg, &msglen);
6093                 if (msglen) {
6094                     fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
6095                 }
6096                 /* ignore lang tag */
6097             } /* else don't attempt to parse */
6098             logeventf(ssh, "Server exited on signal%s%s%s",
6099                       fmt_sig, core ? " (core dumped)" : "",
6100                       fmt_msg);
6101             if (*fmt_sig) sfree(fmt_sig);
6102             if (*fmt_msg) sfree(fmt_msg);
6103             reply = SSH2_MSG_CHANNEL_SUCCESS;
6104
6105         }
6106     } else {
6107         /*
6108          * This is a channel request we don't know
6109          * about, so we now either ignore the request
6110          * or respond with CHANNEL_FAILURE, depending
6111          * on want_reply.
6112          */
6113         reply = SSH2_MSG_CHANNEL_FAILURE;
6114     }
6115     if (want_reply) {
6116         pktout = ssh2_pkt_init(reply);
6117         ssh2_pkt_adduint32(pktout, c->remoteid);
6118         ssh2_pkt_send(ssh, pktout);
6119     }
6120 }
6121
6122 static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
6123 {
6124     char *type;
6125     int typelen, want_reply;
6126     struct Packet *pktout;
6127
6128     ssh_pkt_getstring(pktin, &type, &typelen);
6129     want_reply = ssh2_pkt_getbool(pktin);
6130
6131     /*
6132      * We currently don't support any global requests
6133      * at all, so we either ignore the request or
6134      * respond with REQUEST_FAILURE, depending on
6135      * want_reply.
6136      */
6137     if (want_reply) {
6138         pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
6139         ssh2_pkt_send(ssh, pktout);
6140     }
6141 }
6142
6143 static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
6144 {
6145     char *type;
6146     int typelen;
6147     char *peeraddr;
6148     int peeraddrlen;
6149     int peerport;
6150     char *error = NULL;
6151     struct ssh_channel *c;
6152     unsigned remid, winsize, pktsize;
6153     struct Packet *pktout;
6154
6155     ssh_pkt_getstring(pktin, &type, &typelen);
6156     c = snew(struct ssh_channel);
6157     c->ssh = ssh;
6158
6159     remid = ssh_pkt_getuint32(pktin);
6160     winsize = ssh_pkt_getuint32(pktin);
6161     pktsize = ssh_pkt_getuint32(pktin);
6162
6163     if (typelen == 3 && !memcmp(type, "x11", 3)) {
6164         char *addrstr;
6165
6166         ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6167         addrstr = snewn(peeraddrlen+1, char);
6168         memcpy(addrstr, peeraddr, peeraddrlen);
6169         addrstr[peeraddrlen] = '\0';
6170         peerport = ssh_pkt_getuint32(pktin);
6171
6172         logeventf(ssh, "Received X11 connect request from %s:%d",
6173                   addrstr, peerport);
6174
6175         if (!ssh->X11_fwd_enabled)
6176             error = "X11 forwarding is not enabled";
6177         else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
6178                           ssh->x11auth, addrstr, peerport,
6179                           &ssh->cfg) != NULL) {
6180             error = "Unable to open an X11 connection";
6181         } else {
6182             logevent("Opening X11 forward connection succeeded");
6183             c->type = CHAN_X11;
6184         }
6185
6186         sfree(addrstr);
6187     } else if (typelen == 15 &&
6188                !memcmp(type, "forwarded-tcpip", 15)) {
6189         struct ssh_rportfwd pf, *realpf;
6190         char *dummy;
6191         int dummylen;
6192         ssh_pkt_getstring(pktin, &dummy, &dummylen);/* skip address */
6193         pf.sport = ssh_pkt_getuint32(pktin);
6194         ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
6195         peerport = ssh_pkt_getuint32(pktin);
6196         realpf = find234(ssh->rportfwds, &pf, NULL);
6197         logeventf(ssh, "Received remote port %d open request "
6198                   "from %s:%d", pf.sport, peeraddr, peerport);
6199         if (realpf == NULL) {
6200             error = "Remote port is not recognised";
6201         } else {
6202             const char *e = pfd_newconnect(&c->u.pfd.s,
6203                                            realpf->dhost,
6204                                            realpf->dport, c,
6205                                            &ssh->cfg,
6206                                            realpf->pfrec->addressfamily);
6207             logeventf(ssh, "Attempting to forward remote port to "
6208                       "%s:%d", realpf->dhost, realpf->dport);
6209             if (e != NULL) {
6210                 logeventf(ssh, "Port open failed: %s", e);
6211                 error = "Port open failed";
6212             } else {
6213                 logevent("Forwarded port opened successfully");
6214                 c->type = CHAN_SOCKDATA;
6215             }
6216         }
6217     } else if (typelen == 22 &&
6218                !memcmp(type, "auth-agent@openssh.com", 3)) {
6219         if (!ssh->agentfwd_enabled)
6220             error = "Agent forwarding is not enabled";
6221         else {
6222             c->type = CHAN_AGENT;       /* identify channel type */
6223             c->u.a.lensofar = 0;
6224         }
6225     } else {
6226         error = "Unsupported channel type requested";
6227     }
6228
6229     c->remoteid = remid;
6230     c->halfopen = FALSE;
6231     if (error) {
6232         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
6233         ssh2_pkt_adduint32(pktout, c->remoteid);
6234         ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
6235         ssh2_pkt_addstring(pktout, error);
6236         ssh2_pkt_addstring(pktout, "en");       /* language tag */
6237         ssh2_pkt_send(ssh, pktout);
6238         logeventf(ssh, "Rejected channel open: %s", error);
6239         sfree(c);
6240     } else {
6241         c->localid = alloc_channel_id(ssh);
6242         c->closes = 0;
6243         c->v.v2.locwindow = OUR_V2_WINSIZE;
6244         c->v.v2.remwindow = winsize;
6245         c->v.v2.remmaxpkt = pktsize;
6246         bufchain_init(&c->v.v2.outbuffer);
6247         add234(ssh->channels, c);
6248         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
6249         ssh2_pkt_adduint32(pktout, c->remoteid);
6250         ssh2_pkt_adduint32(pktout, c->localid);
6251         ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
6252         ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT);      /* our max pkt size */
6253         ssh2_pkt_send(ssh, pktout);
6254     }
6255 }
6256
6257 /*
6258  * Handle the SSH-2 userauth and connection layers.
6259  */
6260 static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen,
6261                              struct Packet *pktin)
6262 {
6263     struct do_ssh2_authconn_state {
6264         enum {
6265             AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
6266                 AUTH_PASSWORD,
6267                 AUTH_KEYBOARD_INTERACTIVE
6268         } method;
6269         enum {
6270             AUTH_TYPE_NONE,
6271                 AUTH_TYPE_PUBLICKEY,
6272                 AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
6273                 AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
6274                 AUTH_TYPE_PASSWORD,
6275                 AUTH_TYPE_KEYBOARD_INTERACTIVE,
6276                 AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
6277         } type;
6278         int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
6279         int tried_pubkey_config, tried_agent;
6280         int kbd_inter_running, kbd_inter_refused;
6281         int we_are_in;
6282         int num_prompts, curr_prompt, echo;
6283         char username[100];
6284         int got_username;
6285         char pwprompt[512];
6286         char password[100];
6287         void *publickey_blob;
6288         int publickey_bloblen;
6289         unsigned char request[5], *response, *p;
6290         int responselen;
6291         int keyi, nkeys;
6292         int authed;
6293         char *pkblob, *alg, *commentp;
6294         int pklen, alglen, commentlen;
6295         int siglen, retlen, len;
6296         char *q, *agentreq, *ret;
6297         int try_send;
6298         int num_env, env_left, env_ok;
6299         struct Packet *pktout;
6300     };
6301     crState(do_ssh2_authconn_state);
6302
6303     crBegin(ssh->do_ssh2_authconn_crstate);
6304
6305     /*
6306      * Request userauth protocol, and await a response to it.
6307      */
6308     s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
6309     ssh2_pkt_addstring(s->pktout, "ssh-userauth");
6310     ssh2_pkt_send(ssh, s->pktout);
6311     crWaitUntilV(pktin);
6312     if (pktin->type != SSH2_MSG_SERVICE_ACCEPT) {
6313         bombout(("Server refused user authentication protocol"));
6314         crStopV;
6315     }
6316
6317     /*
6318      * We repeat this whole loop, including the username prompt,
6319      * until we manage a successful authentication. If the user
6320      * types the wrong _password_, they can be sent back to the
6321      * beginning to try another username, if this is configured on.
6322      * (If they specify a username in the config, they are never
6323      * asked, even if they do give a wrong password.)
6324      * 
6325      * I think this best serves the needs of
6326      * 
6327      *  - the people who have no configuration, no keys, and just
6328      *    want to try repeated (username,password) pairs until they
6329      *    type both correctly
6330      * 
6331      *  - people who have keys and configuration but occasionally
6332      *    need to fall back to passwords
6333      * 
6334      *  - people with a key held in Pageant, who might not have
6335      *    logged in to a particular machine before; so they want to
6336      *    type a username, and then _either_ their key will be
6337      *    accepted, _or_ they will type a password. If they mistype
6338      *    the username they will want to be able to get back and
6339      *    retype it!
6340      */
6341     s->username[0] = '\0';
6342     s->got_username = FALSE;
6343     do {
6344         /*
6345          * Get a username.
6346          */
6347         if (s->got_username && !ssh->cfg.change_username) {
6348             /*
6349              * We got a username last time round this loop, and
6350              * with change_username turned off we don't try to get
6351              * it again.
6352              */
6353         } else if (!*ssh->cfg.username) {
6354             if (ssh_get_line && !ssh_getline_pw_only) {
6355                 if (!ssh_get_line("login as: ",
6356                                   s->username, sizeof(s->username), FALSE)) {
6357                     /*
6358                      * get_line failed to get a username.
6359                      * Terminate.
6360                      */
6361                     logevent("No username provided. Abandoning session.");
6362                     ssh->close_expected = TRUE;
6363                     ssh_closing((Plug)ssh, NULL, 0, 0);
6364                     crStopV;
6365                 }
6366             } else {
6367                 int ret;               /* need not be saved across crReturn */
6368                 c_write_str(ssh, "login as: ");
6369                 ssh->send_ok = 1;
6370                 setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
6371                 do {
6372                     crWaitUntilV(!pktin);
6373                     ret = process_userpass_input(ssh, in, inlen);
6374                 } while (ret == 0);
6375                 if (ret < 0)
6376                     cleanup_exit(0);
6377                 c_write_str(ssh, "\r\n");
6378             }
6379             s->username[strcspn(s->username, "\n\r")] = '\0';
6380         } else {
6381             char *stuff;
6382             strncpy(s->username, ssh->cfg.username, sizeof(s->username));
6383             s->username[sizeof(s->username)-1] = '\0';
6384             if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
6385                 stuff = dupprintf("Using username \"%s\".\r\n", s->username);
6386                 c_write_str(ssh, stuff);
6387                 sfree(stuff);
6388             }
6389         }
6390         s->got_username = TRUE;
6391
6392         /*
6393          * Send an authentication request using method "none": (a)
6394          * just in case it succeeds, and (b) so that we know what
6395          * authentication methods we can usefully try next.
6396          */
6397         ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6398
6399         s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6400         ssh2_pkt_addstring(s->pktout, s->username);
6401         ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
6402         ssh2_pkt_addstring(s->pktout, "none");    /* method */
6403         ssh2_pkt_send(ssh, s->pktout);
6404         s->type = AUTH_TYPE_NONE;
6405         s->gotit = FALSE;
6406         s->we_are_in = FALSE;
6407
6408         s->tried_pubkey_config = FALSE;
6409         s->tried_agent = FALSE;
6410         s->kbd_inter_running = FALSE;
6411         s->kbd_inter_refused = FALSE;
6412         /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
6413         if (!filename_is_null(ssh->cfg.keyfile)) {
6414             int keytype;
6415             logeventf(ssh, "Reading private key file \"%.150s\"",
6416                       filename_to_str(&ssh->cfg.keyfile));
6417             keytype = key_type(&ssh->cfg.keyfile);
6418             if (keytype == SSH_KEYTYPE_SSH2) {
6419                 s->publickey_blob =
6420                     ssh2_userkey_loadpub(&ssh->cfg.keyfile, NULL,
6421                                          &s->publickey_bloblen, NULL);
6422             } else {
6423                 char *msgbuf;
6424                 logeventf(ssh, "Unable to use this key file (%s)",
6425                           key_type_to_str(keytype));
6426                 msgbuf = dupprintf("Unable to use key file \"%.150s\""
6427                                    " (%s)\r\n",
6428                                    filename_to_str(&ssh->cfg.keyfile),
6429                                    key_type_to_str(keytype));
6430                 c_write_str(ssh, msgbuf);
6431                 sfree(msgbuf);
6432                 s->publickey_blob = NULL;
6433             }
6434         } else
6435             s->publickey_blob = NULL;
6436
6437         while (1) {
6438             /*
6439              * Wait for the result of the last authentication request.
6440              */
6441             if (!s->gotit)
6442                 crWaitUntilV(pktin);
6443             while (pktin->type == SSH2_MSG_USERAUTH_BANNER) {
6444                 char *banner;
6445                 int size;
6446                 /*
6447                  * Don't show the banner if we're operating in
6448                  * non-verbose non-interactive mode. (It's probably
6449                  * a script, which means nobody will read the
6450                  * banner _anyway_, and moreover the printing of
6451                  * the banner will screw up processing on the
6452                  * output of (say) plink.)
6453                  */
6454                 if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
6455                     ssh_pkt_getstring(pktin, &banner, &size);
6456                     if (banner)
6457                         c_write_untrusted(ssh, banner, size);
6458                 }
6459                 crWaitUntilV(pktin);
6460             }
6461             if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
6462                 logevent("Access granted");
6463                 s->we_are_in = TRUE;
6464                 break;
6465             }
6466
6467             if (s->kbd_inter_running &&
6468                 pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
6469                 /*
6470                  * This is either a further set-of-prompts packet
6471                  * in keyboard-interactive authentication, or it's
6472                  * the same one and we came back here with `gotit'
6473                  * set. In the former case, we must reset the
6474                  * curr_prompt variable.
6475                  */
6476                 if (!s->gotit)
6477                     s->curr_prompt = 0;
6478             } else if (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
6479                 /* FIXME: perhaps we should support this? */
6480                 bombout(("PASSWD_CHANGEREQ not yet supported"));
6481                 crStopV;
6482             } else if (pktin->type != SSH2_MSG_USERAUTH_FAILURE) {
6483                 bombout(("Strange packet received during authentication: type %d",
6484                          pktin->type));
6485                 crStopV;
6486             }
6487
6488             s->gotit = FALSE;
6489
6490             /*
6491              * OK, we're now sitting on a USERAUTH_FAILURE message, so
6492              * we can look at the string in it and know what we can
6493              * helpfully try next.
6494              */
6495             if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
6496                 char *methods;
6497                 int methlen;
6498                 ssh_pkt_getstring(pktin, &methods, &methlen);
6499                 s->kbd_inter_running = FALSE;
6500                 if (!ssh2_pkt_getbool(pktin)) {
6501                     /*
6502                      * We have received an unequivocal Access
6503                      * Denied. This can translate to a variety of
6504                      * messages:
6505                      * 
6506                      *  - if we'd just tried "none" authentication,
6507                      *    it's not worth printing anything at all
6508                      * 
6509                      *  - if we'd just tried a public key _offer_,
6510                      *    the message should be "Server refused our
6511                      *    key" (or no message at all if the key
6512                      *    came from Pageant)
6513                      * 
6514                      *  - if we'd just tried anything else, the
6515                      *    message really should be "Access denied".
6516                      * 
6517                      * Additionally, if we'd just tried password
6518                      * authentication, we should break out of this
6519                      * whole loop so as to go back to the username
6520                      * prompt (iff we're configured to allow
6521                      * username change attempts).
6522                      */
6523                     if (s->type == AUTH_TYPE_NONE) {
6524                         /* do nothing */
6525                     } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
6526                                s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
6527                         if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
6528                             c_write_str(ssh, "Server refused our key\r\n");
6529                         logevent("Server refused public key");
6530                     } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
6531                         /* server declined keyboard-interactive; ignore */
6532                     } else {
6533                         c_write_str(ssh, "Access denied\r\n");
6534                         logevent("Access denied");
6535                         if (s->type == AUTH_TYPE_PASSWORD &&
6536                             ssh->cfg.change_username) {
6537                             /* XXX perhaps we should allow
6538                              * keyboard-interactive to do this too? */
6539                             s->we_are_in = FALSE;
6540                             break;
6541                         }
6542                     }
6543                 } else {
6544                     c_write_str(ssh, "Further authentication required\r\n");
6545                     logevent("Further authentication required");
6546                 }
6547
6548                 s->can_pubkey =
6549                     in_commasep_string("publickey", methods, methlen);
6550                 s->can_passwd =
6551                     in_commasep_string("password", methods, methlen);
6552                 s->can_keyb_inter = ssh->cfg.try_ki_auth &&
6553                     in_commasep_string("keyboard-interactive", methods, methlen);
6554             }
6555
6556             s->method = 0;
6557             ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6558             s->need_pw = FALSE;
6559
6560             /*
6561              * Most password/passphrase prompts will be
6562              * non-echoing, so we set this to 0 by default.
6563              * Exception is that some keyboard-interactive prompts
6564              * can be echoing, in which case we'll set this to 1.
6565              */
6566             s->echo = 0;
6567
6568             if (!s->method && s->can_pubkey &&
6569                 agent_exists() && !s->tried_agent) {
6570                 /*
6571                  * Attempt public-key authentication using Pageant.
6572                  */
6573                 void *r;
6574                 s->authed = FALSE;
6575
6576                 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6577                 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
6578
6579                 s->tried_agent = TRUE;
6580
6581                 logevent("Pageant is running. Requesting keys.");
6582
6583                 /* Request the keys held by the agent. */
6584                 PUT_32BIT(s->request, 1);
6585                 s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
6586                 if (!agent_query(s->request, 5, &r, &s->responselen,
6587                                  ssh_agent_callback, ssh)) {
6588                     do {
6589                         crReturnV;
6590                         if (pktin) {
6591                             bombout(("Unexpected data from server while"
6592                                      " waiting for agent response"));
6593                             crStopV;
6594                         }
6595                     } while (pktin || inlen > 0);
6596                     r = ssh->agent_response;
6597                     s->responselen = ssh->agent_response_len;
6598                 }
6599                 s->response = (unsigned char *) r;
6600                 if (s->response && s->responselen >= 5 &&
6601                     s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
6602                     s->p = s->response + 5;
6603                     s->nkeys = GET_32BIT(s->p);
6604                     s->p += 4;
6605                     logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
6606                     for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
6607                         void *vret;
6608
6609                         logeventf(ssh, "Trying Pageant key #%d", s->keyi);
6610                         s->pklen = GET_32BIT(s->p);
6611                         s->p += 4;
6612                         if (s->publickey_blob &&
6613                             s->pklen == s->publickey_bloblen &&
6614                             !memcmp(s->p, s->publickey_blob,
6615                                     s->publickey_bloblen)) {
6616                             logevent("This key matches configured key file");
6617                             s->tried_pubkey_config = 1;
6618                         }
6619                         s->pkblob = (char *)s->p;
6620                         s->p += s->pklen;
6621                         s->alglen = GET_32BIT(s->pkblob);
6622                         s->alg = s->pkblob + 4;
6623                         s->commentlen = GET_32BIT(s->p);
6624                         s->p += 4;
6625                         s->commentp = (char *)s->p;
6626                         s->p += s->commentlen;
6627                         s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6628                         ssh2_pkt_addstring(s->pktout, s->username);
6629                         ssh2_pkt_addstring(s->pktout, "ssh-connection");        /* service requested */
6630                         ssh2_pkt_addstring(s->pktout, "publickey");     /* method */
6631                         ssh2_pkt_addbool(s->pktout, FALSE);     /* no signature included */
6632                         ssh2_pkt_addstring_start(s->pktout);
6633                         ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
6634                         ssh2_pkt_addstring_start(s->pktout);
6635                         ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
6636                         ssh2_pkt_send(ssh, s->pktout);
6637
6638                         crWaitUntilV(pktin);
6639                         if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
6640                             logevent("Key refused");
6641                             continue;
6642                         }
6643
6644                         if (flags & FLAG_VERBOSE) {
6645                             c_write_str(ssh, "Authenticating with "
6646                                         "public key \"");
6647                             c_write(ssh, s->commentp, s->commentlen);
6648                             c_write_str(ssh, "\" from agent\r\n");
6649                         }
6650
6651                         /*
6652                          * Server is willing to accept the key.
6653                          * Construct a SIGN_REQUEST.
6654                          */
6655                         s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6656                         ssh2_pkt_addstring(s->pktout, s->username);
6657                         ssh2_pkt_addstring(s->pktout, "ssh-connection");        /* service requested */
6658                         ssh2_pkt_addstring(s->pktout, "publickey");     /* method */
6659                         ssh2_pkt_addbool(s->pktout, TRUE);
6660                         ssh2_pkt_addstring_start(s->pktout);
6661                         ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
6662                         ssh2_pkt_addstring_start(s->pktout);
6663                         ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
6664
6665                         s->siglen = s->pktout->length - 5 + 4 + 20;
6666                         if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
6667                             s->siglen -= 4;
6668                         s->len = 1;       /* message type */
6669                         s->len += 4 + s->pklen; /* key blob */
6670                         s->len += 4 + s->siglen;        /* data to sign */
6671                         s->len += 4;      /* flags */
6672                         s->agentreq = snewn(4 + s->len, char);
6673                         PUT_32BIT(s->agentreq, s->len);
6674                         s->q = s->agentreq + 4;
6675                         *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
6676                         PUT_32BIT(s->q, s->pklen);
6677                         s->q += 4;
6678                         memcpy(s->q, s->pkblob, s->pklen);
6679                         s->q += s->pklen;
6680                         PUT_32BIT(s->q, s->siglen);
6681                         s->q += 4;
6682                         /* Now the data to be signed... */
6683                         if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
6684                             PUT_32BIT(s->q, 20);
6685                             s->q += 4;
6686                         }
6687                         memcpy(s->q, ssh->v2_session_id, 20);
6688                         s->q += 20;
6689                         memcpy(s->q, s->pktout->data + 5,
6690                                s->pktout->length - 5);
6691                         s->q += s->pktout->length - 5;
6692                         /* And finally the (zero) flags word. */
6693                         PUT_32BIT(s->q, 0);
6694                         if (!agent_query(s->agentreq, s->len + 4,
6695                                          &vret, &s->retlen,
6696                                          ssh_agent_callback, ssh)) {
6697                             do {
6698                                 crReturnV;
6699                                 if (pktin) {
6700                                     bombout(("Unexpected data from server"
6701                                              " while waiting for agent"
6702                                              " response"));
6703                                     crStopV;
6704                                 }
6705                             } while (pktin || inlen > 0);
6706                             vret = ssh->agent_response;
6707                             s->retlen = ssh->agent_response_len;
6708                         }
6709                         s->ret = vret;
6710                         sfree(s->agentreq);
6711                         if (s->ret) {
6712                             if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
6713                                 logevent("Sending Pageant's response");
6714                                 ssh2_add_sigblob(ssh, s->pktout,
6715                                                  s->pkblob, s->pklen,
6716                                                  s->ret + 9,
6717                                                  GET_32BIT(s->ret + 5));
6718                                 ssh2_pkt_send(ssh, s->pktout);
6719                                 s->authed = TRUE;
6720                                 break;
6721                             } else {
6722                                 logevent
6723                                     ("Pageant failed to answer challenge");
6724                                 sfree(s->ret);
6725                             }
6726                         }
6727                     }
6728                     if (s->authed)
6729                         continue;
6730                 }
6731                 sfree(s->response);
6732             }
6733
6734             if (!s->method && s->can_pubkey && s->publickey_blob
6735                 && !s->tried_pubkey_config) {
6736                 unsigned char *pub_blob;
6737                 char *algorithm, *comment;
6738                 int pub_blob_len;
6739
6740                 s->tried_pubkey_config = TRUE;
6741
6742                 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6743                 ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
6744
6745                 /*
6746                  * Try the public key supplied in the configuration.
6747                  *
6748                  * First, offer the public blob to see if the server is
6749                  * willing to accept it.
6750                  */
6751                 pub_blob =
6752                     (unsigned char *)ssh2_userkey_loadpub(&ssh->cfg.keyfile,
6753                                                           &algorithm,
6754                                                           &pub_blob_len,
6755                                                           NULL);
6756                 if (pub_blob) {
6757                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6758                     ssh2_pkt_addstring(s->pktout, s->username);
6759                     ssh2_pkt_addstring(s->pktout, "ssh-connection");    /* service requested */
6760                     ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6761                     ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
6762                     ssh2_pkt_addstring(s->pktout, algorithm);
6763                     ssh2_pkt_addstring_start(s->pktout);
6764                     ssh2_pkt_addstring_data(s->pktout, (char *)pub_blob,
6765                                             pub_blob_len);
6766                     ssh2_pkt_send(ssh, s->pktout);
6767                     logevent("Offered public key");
6768
6769                     crWaitUntilV(pktin);
6770                     if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
6771                         s->gotit = TRUE;
6772                         s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
6773                         continue;      /* key refused; give up on it */
6774                     }
6775
6776                     logevent("Offer of public key accepted");
6777                     /*
6778                      * Actually attempt a serious authentication using
6779                      * the key.
6780                      */
6781                     if (ssh2_userkey_encrypted(&ssh->cfg.keyfile, &comment)) {
6782                         sprintf(s->pwprompt,
6783                                 "Passphrase for key \"%.100s\": ",
6784                                 comment);
6785                         s->need_pw = TRUE;
6786                     } else {
6787                         s->need_pw = FALSE;
6788                     }
6789                     if (flags & FLAG_VERBOSE) {
6790                         c_write_str(ssh, "Authenticating with public key \"");
6791                         c_write_str(ssh, comment);
6792                         c_write_str(ssh, "\"\r\n");
6793                     }
6794                     s->method = AUTH_PUBLICKEY_FILE;
6795                 }
6796             }
6797
6798             if (!s->method && s->can_keyb_inter && !s->kbd_inter_refused &&
6799                 !s->kbd_inter_running) {
6800                 s->method = AUTH_KEYBOARD_INTERACTIVE;
6801                 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6802
6803                 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6804                 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6805
6806                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6807                 ssh2_pkt_addstring(s->pktout, s->username);
6808                 ssh2_pkt_addstring(s->pktout, "ssh-connection");        /* service requested */
6809                 ssh2_pkt_addstring(s->pktout, "keyboard-interactive");  /* method */
6810                 ssh2_pkt_addstring(s->pktout, ""); /* lang */
6811                 ssh2_pkt_addstring(s->pktout, "");
6812                 ssh2_pkt_send(ssh, s->pktout);
6813
6814                 crWaitUntilV(pktin);
6815                 if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
6816                     if (pktin->type == SSH2_MSG_USERAUTH_FAILURE)
6817                         s->gotit = TRUE;
6818                     logevent("Keyboard-interactive authentication refused");
6819                     s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
6820                     s->kbd_inter_refused = TRUE; /* don't try it again */
6821                     continue;
6822                 }
6823
6824                 c_write_str(ssh, "Using keyboard-interactive authentication.\r\n");
6825                 s->kbd_inter_running = TRUE;
6826                 s->curr_prompt = 0;
6827             }
6828
6829             if (s->kbd_inter_running) {
6830                 s->method = AUTH_KEYBOARD_INTERACTIVE;
6831                 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
6832
6833                 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6834                 ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
6835
6836                 if (s->curr_prompt == 0) {
6837                     /*
6838                      * We've got a fresh USERAUTH_INFO_REQUEST.
6839                      * Display header data, and start going through
6840                      * the prompts.
6841                      */
6842                     char *name, *inst, *lang;
6843                     int name_len, inst_len, lang_len;
6844
6845                     ssh_pkt_getstring(pktin, &name, &name_len);
6846                     ssh_pkt_getstring(pktin, &inst, &inst_len);
6847                     ssh_pkt_getstring(pktin, &lang, &lang_len);
6848                     if (name_len > 0) {
6849                         c_write_untrusted(ssh, name, name_len);
6850                         c_write_str(ssh, "\r\n");
6851                     }
6852                     if (inst_len > 0) {
6853                         c_write_untrusted(ssh, inst, inst_len);
6854                         c_write_str(ssh, "\r\n");
6855                     }
6856                     s->num_prompts = ssh_pkt_getuint32(pktin);
6857                 }
6858
6859                 /*
6860                  * If there are prompts remaining in the packet,
6861                  * display one and get a response.
6862                  */
6863                 if (s->curr_prompt < s->num_prompts) {
6864                     char *prompt;
6865                     int prompt_len;
6866
6867                     ssh_pkt_getstring(pktin, &prompt, &prompt_len);
6868                     if (prompt_len > 0) {
6869                         static const char trunc[] = "<prompt truncated>: ";
6870                         static const int prlen = sizeof(s->pwprompt) -
6871                                                  lenof(trunc);
6872                         if (prompt_len > prlen) {
6873                             memcpy(s->pwprompt, prompt, prlen);
6874                             strcpy(s->pwprompt + prlen, trunc);
6875                         } else {
6876                             memcpy(s->pwprompt, prompt, prompt_len);
6877                             s->pwprompt[prompt_len] = '\0';
6878                         }
6879                     } else {
6880                         strcpy(s->pwprompt,
6881                                "<server failed to send prompt>: ");
6882                     }
6883                     s->echo = ssh2_pkt_getbool(pktin);
6884                     s->need_pw = TRUE;
6885                 } else
6886                     s->need_pw = FALSE;
6887             }
6888
6889             if (!s->method && s->can_passwd) {
6890                 s->method = AUTH_PASSWORD;
6891                 ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
6892                 ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
6893                 sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
6894                         ssh->savedhost);
6895                 s->need_pw = TRUE;
6896             }
6897
6898             if (s->need_pw) {
6899                 if (ssh_get_line) {
6900                     if (!ssh_get_line(s->pwprompt, s->password,
6901                                       sizeof(s->password), TRUE)) {
6902                         /*
6903                          * get_line failed to get a password (for
6904                          * example because one was supplied on the
6905                          * command line which has already failed to
6906                          * work). Terminate.
6907                          */
6908                         s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
6909                         ssh2_pkt_adduint32(s->pktout,SSH2_DISCONNECT_BY_APPLICATION);
6910                         ssh2_pkt_addstring(s->pktout, "No more passwords available"
6911                                            " to try");
6912                         ssh2_pkt_addstring(s->pktout, "en");    /* language tag */
6913                         ssh2_pkt_send_noqueue(ssh, s->pktout);
6914                         logevent("Unable to authenticate");
6915                         connection_fatal(ssh->frontend,
6916                                          "Unable to authenticate");
6917                         ssh->close_expected = TRUE;
6918                         ssh_closing((Plug)ssh, NULL, 0, 0);
6919                         crStopV;
6920                     }
6921                 } else {
6922                     int ret;           /* need not be saved across crReturn */
6923                     c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
6924                     ssh->send_ok = 1;
6925
6926                     setup_userpass_input(ssh, s->password,
6927                                          sizeof(s->password), s->echo);
6928                     do {
6929                         crWaitUntilV(!pktin);
6930                         ret = process_userpass_input(ssh, in, inlen);
6931                     } while (ret == 0);
6932                     if (ret < 0)
6933                         cleanup_exit(0);
6934                     c_write_str(ssh, "\r\n");
6935                 }
6936             }
6937
6938             if (s->method == AUTH_PUBLICKEY_FILE) {
6939                 /*
6940                  * We have our passphrase. Now try the actual authentication.
6941                  */
6942                 struct ssh2_userkey *key;
6943                 const char *error = NULL;
6944
6945                 key = ssh2_load_userkey(&ssh->cfg.keyfile, s->password,
6946                                         &error);
6947                 if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
6948                     if (key == SSH2_WRONG_PASSPHRASE) {
6949                         c_write_str(ssh, "Wrong passphrase\r\n");
6950                         s->tried_pubkey_config = FALSE;
6951                     } else {
6952                         c_write_str(ssh, "Unable to load private key (");
6953                         c_write_str(ssh, error);
6954                         c_write_str(ssh, ")\r\n");
6955                         s->tried_pubkey_config = TRUE;
6956                     }
6957                     /* Send a spurious AUTH_NONE to return to the top. */
6958                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6959                     ssh2_pkt_addstring(s->pktout, s->username);
6960                     ssh2_pkt_addstring(s->pktout, "ssh-connection");    /* service requested */
6961                     ssh2_pkt_addstring(s->pktout, "none");      /* method */
6962                     ssh2_pkt_send(ssh, s->pktout);
6963                     s->type = AUTH_TYPE_NONE;
6964                 } else {
6965                     unsigned char *pkblob, *sigblob, *sigdata;
6966                     int pkblob_len, sigblob_len, sigdata_len;
6967                     int p;
6968
6969                     /*
6970                      * We have loaded the private key and the server
6971                      * has announced that it's willing to accept it.
6972                      * Hallelujah. Generate a signature and send it.
6973                      */
6974                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
6975                     ssh2_pkt_addstring(s->pktout, s->username);
6976                     ssh2_pkt_addstring(s->pktout, "ssh-connection");    /* service requested */
6977                     ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
6978                     ssh2_pkt_addbool(s->pktout, TRUE);
6979                     ssh2_pkt_addstring(s->pktout, key->alg->name);
6980                     pkblob = key->alg->public_blob(key->data, &pkblob_len);
6981                     ssh2_pkt_addstring_start(s->pktout);
6982                     ssh2_pkt_addstring_data(s->pktout, (char *)pkblob, pkblob_len);
6983
6984                     /*
6985                      * The data to be signed is:
6986                      *
6987                      *   string  session-id
6988                      *
6989                      * followed by everything so far placed in the
6990                      * outgoing packet.
6991                      */
6992                     sigdata_len = s->pktout->length - 5 + 4 + 20;
6993                     if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
6994                         sigdata_len -= 4;
6995                     sigdata = snewn(sigdata_len, unsigned char);
6996                     p = 0;
6997                     if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
6998                         PUT_32BIT(sigdata+p, 20);
6999                         p += 4;
7000                     }
7001                     memcpy(sigdata+p, ssh->v2_session_id, 20); p += 20;
7002                     memcpy(sigdata+p, s->pktout->data + 5,
7003                            s->pktout->length - 5);
7004                     p += s->pktout->length - 5;
7005                     assert(p == sigdata_len);
7006                     sigblob = key->alg->sign(key->data, (char *)sigdata,
7007                                              sigdata_len, &sigblob_len);
7008                     ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
7009                                      sigblob, sigblob_len);
7010                     sfree(pkblob);
7011                     sfree(sigblob);
7012                     sfree(sigdata);
7013
7014                     ssh2_pkt_send(ssh, s->pktout);
7015                     s->type = AUTH_TYPE_PUBLICKEY;
7016                     key->alg->freekey(key->data);
7017                 }
7018             } else if (s->method == AUTH_PASSWORD) {
7019                 /*
7020                  * We pad out the password packet to 256 bytes to make
7021                  * it harder for an attacker to find the length of the
7022                  * user's password.
7023                  *
7024                  * Anyone using a password longer than 256 bytes
7025                  * probably doesn't have much to worry about from
7026                  * people who find out how long their password is!
7027                  */
7028                 s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
7029                 s->pktout->forcepad = 256;
7030                 ssh2_pkt_addstring(s->pktout, s->username);
7031                 ssh2_pkt_addstring(s->pktout, "ssh-connection");        /* service requested */
7032                 ssh2_pkt_addstring(s->pktout, "password");
7033                 ssh2_pkt_addbool(s->pktout, FALSE);
7034                 dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
7035                 ssh2_pkt_addstring(s->pktout, s->password);
7036                 memset(s->password, 0, sizeof(s->password));
7037                 end_log_omission(ssh, s->pktout);
7038                 ssh2_pkt_send(ssh, s->pktout);
7039                 logevent("Sent password");
7040                 s->type = AUTH_TYPE_PASSWORD;
7041             } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
7042                 if (s->curr_prompt == 0) {
7043                     s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
7044                     s->pktout->forcepad = 256;
7045                     ssh2_pkt_adduint32(s->pktout, s->num_prompts);
7046                 }
7047                 if (s->need_pw) {      /* only add pw if we just got one! */
7048                     dont_log_password(ssh, s->pktout, PKTLOG_BLANK);
7049                     ssh2_pkt_addstring(s->pktout, s->password);
7050                     memset(s->password, 0, sizeof(s->password));
7051                     end_log_omission(ssh, s->pktout);
7052                     s->curr_prompt++;
7053                 }
7054                 if (s->curr_prompt >= s->num_prompts) {
7055                     ssh2_pkt_send(ssh, s->pktout);
7056                 } else {
7057                     /*
7058                      * If there are prompts remaining, we set
7059                      * `gotit' so that we won't attempt to get
7060                      * another packet. Then we go back round the
7061                      * loop and will end up retrieving another
7062                      * prompt out of the existing packet. Funky or
7063                      * what?
7064                      */
7065                     s->gotit = TRUE;
7066                 }
7067                 s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
7068             } else {
7069                 c_write_str(ssh, "No supported authentication methods"
7070                             " left to try!\r\n");
7071                 logevent("No supported authentications offered."
7072                          " Disconnecting");
7073                 s->pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
7074                 ssh2_pkt_adduint32(s->pktout, SSH2_DISCONNECT_BY_APPLICATION);
7075                 ssh2_pkt_addstring(s->pktout, "No supported authentication"
7076                                    " methods available");
7077                 ssh2_pkt_addstring(s->pktout, "en");    /* language tag */
7078                 ssh2_pkt_send_noqueue(ssh, s->pktout);
7079                 ssh->close_expected = TRUE;
7080                 ssh_closing((Plug)ssh, NULL, 0, 0);
7081                 crStopV;
7082             }
7083         }
7084     } while (!s->we_are_in);
7085
7086     /*
7087      * Now we're authenticated for the connection protocol. The
7088      * connection protocol will automatically have started at this
7089      * point; there's no need to send SERVICE_REQUEST.
7090      */
7091
7092     ssh->channels = newtree234(ssh_channelcmp);
7093
7094     /*
7095      * Set up handlers for some connection protocol messages, so we
7096      * don't have to handle them repeatedly in this coroutine.
7097      */
7098     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
7099         ssh2_msg_channel_window_adjust;
7100     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
7101         ssh2_msg_global_request;
7102
7103     /*
7104      * Create the main session channel.
7105      */
7106     if (!ssh->cfg.ssh_no_shell) {
7107         ssh->mainchan = snew(struct ssh_channel);
7108         ssh->mainchan->ssh = ssh;
7109         ssh->mainchan->localid = alloc_channel_id(ssh);
7110         s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
7111         ssh2_pkt_addstring(s->pktout, "session");
7112         ssh2_pkt_adduint32(s->pktout, ssh->mainchan->localid);
7113         ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
7114         ssh2_pkt_adduint32(s->pktout, ssh->mainchan->v.v2.locwindow);/* our window size */
7115         ssh2_pkt_adduint32(s->pktout, OUR_V2_MAXPKT);    /* our max pkt size */
7116         ssh2_pkt_send(ssh, s->pktout);
7117         crWaitUntilV(pktin);
7118         if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
7119             bombout(("Server refused to open a session"));
7120             crStopV;
7121             /* FIXME: error data comes back in FAILURE packet */
7122         }
7123         if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
7124             bombout(("Server's channel confirmation cited wrong channel"));
7125             crStopV;
7126         }
7127         ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
7128         ssh->mainchan->halfopen = FALSE;
7129         ssh->mainchan->type = CHAN_MAINSESSION;
7130         ssh->mainchan->closes = 0;
7131         ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
7132         ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
7133         bufchain_init(&ssh->mainchan->v.v2.outbuffer);
7134         add234(ssh->channels, ssh->mainchan);
7135         update_specials_menu(ssh->frontend);
7136         logevent("Opened channel for session");
7137     } else
7138         ssh->mainchan = NULL;
7139
7140     /*
7141      * Now we have a channel, make dispatch table entries for
7142      * general channel-based messages.
7143      */
7144     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
7145     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
7146         ssh2_msg_channel_data;
7147     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
7148     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
7149     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
7150         ssh2_msg_channel_open_confirmation;
7151     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
7152         ssh2_msg_channel_open_failure;
7153     ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
7154         ssh2_msg_channel_request;
7155     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
7156         ssh2_msg_channel_open;
7157
7158     /*
7159      * Potentially enable X11 forwarding.
7160      */
7161     if (ssh->mainchan && ssh->cfg.x11_forward) {
7162         char proto[20], data[64];
7163         logevent("Requesting X11 forwarding");
7164         ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
7165                                        data, sizeof(data), ssh->cfg.x11_auth);
7166         x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
7167         s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7168         ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
7169         ssh2_pkt_addstring(s->pktout, "x11-req");
7170         ssh2_pkt_addbool(s->pktout, 1);        /* want reply */
7171         ssh2_pkt_addbool(s->pktout, 0);        /* many connections */
7172         ssh2_pkt_addstring(s->pktout, proto);
7173         ssh2_pkt_addstring(s->pktout, data);
7174         ssh2_pkt_adduint32(s->pktout, x11_get_screen_number(ssh->cfg.x11_display));
7175         ssh2_pkt_send(ssh, s->pktout);
7176
7177         crWaitUntilV(pktin);
7178
7179         if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7180             if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7181                 bombout(("Unexpected response to X11 forwarding request:"
7182                          " packet type %d", pktin->type));
7183                 crStopV;
7184             }
7185             logevent("X11 forwarding refused");
7186         } else {
7187             logevent("X11 forwarding enabled");
7188             ssh->X11_fwd_enabled = TRUE;
7189         }
7190     }
7191
7192     /*
7193      * Enable port forwardings.
7194      */
7195     ssh_setup_portfwd(ssh, &ssh->cfg);
7196
7197     /*
7198      * Potentially enable agent forwarding.
7199      */
7200     if (ssh->mainchan && ssh->cfg.agentfwd && agent_exists()) {
7201         logevent("Requesting OpenSSH-style agent forwarding");
7202         s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7203         ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
7204         ssh2_pkt_addstring(s->pktout, "auth-agent-req@openssh.com");
7205         ssh2_pkt_addbool(s->pktout, 1);        /* want reply */
7206         ssh2_pkt_send(ssh, s->pktout);
7207
7208         crWaitUntilV(pktin);
7209
7210         if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7211             if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7212                 bombout(("Unexpected response to agent forwarding request:"
7213                          " packet type %d", pktin->type));
7214                 crStopV;
7215             }
7216             logevent("Agent forwarding refused");
7217         } else {
7218             logevent("Agent forwarding enabled");
7219             ssh->agentfwd_enabled = TRUE;
7220         }
7221     }
7222
7223     /*
7224      * Now allocate a pty for the session.
7225      */
7226     if (ssh->mainchan && !ssh->cfg.nopty) {
7227         /* Unpick the terminal-speed string. */
7228         /* XXX perhaps we should allow no speeds to be sent. */
7229         ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
7230         sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
7231         /* Build the pty request. */
7232         s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7233         ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
7234         ssh2_pkt_addstring(s->pktout, "pty-req");
7235         ssh2_pkt_addbool(s->pktout, 1);        /* want reply */
7236         ssh2_pkt_addstring(s->pktout, ssh->cfg.termtype);
7237         ssh2_pkt_adduint32(s->pktout, ssh->term_width);
7238         ssh2_pkt_adduint32(s->pktout, ssh->term_height);
7239         ssh2_pkt_adduint32(s->pktout, 0);              /* pixel width */
7240         ssh2_pkt_adduint32(s->pktout, 0);              /* pixel height */
7241         ssh2_pkt_addstring_start(s->pktout);
7242         ssh2_pkt_addbyte(s->pktout, 128);              /* TTY_OP_ISPEED */
7243         ssh2_pkt_adduint32(s->pktout, ssh->ispeed);
7244         ssh2_pkt_addbyte(s->pktout, 129);              /* TTY_OP_OSPEED */
7245         ssh2_pkt_adduint32(s->pktout, ssh->ospeed);
7246         ssh2_pkt_addstring_data(s->pktout, "\0", 1); /* TTY_OP_END */
7247         ssh2_pkt_send(ssh, s->pktout);
7248         ssh->state = SSH_STATE_INTERMED;
7249
7250         crWaitUntilV(pktin);
7251
7252         if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7253             if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7254                 bombout(("Unexpected response to pty request:"
7255                          " packet type %d", pktin->type));
7256                 crStopV;
7257             }
7258             c_write_str(ssh, "Server refused to allocate pty\r\n");
7259             ssh->editing = ssh->echoing = 1;
7260         } else {
7261             logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
7262                       ssh->ospeed, ssh->ispeed);
7263         }
7264     } else {
7265         ssh->editing = ssh->echoing = 1;
7266     }
7267
7268     /*
7269      * Send environment variables.
7270      * 
7271      * Simplest thing here is to send all the requests at once, and
7272      * then wait for a whole bunch of successes or failures.
7273      */
7274     if (ssh->mainchan && *ssh->cfg.environmt) {
7275         char *e = ssh->cfg.environmt;
7276         char *var, *varend, *val;
7277
7278         s->num_env = 0;
7279
7280         while (*e) {
7281             var = e;
7282             while (*e && *e != '\t') e++;
7283             varend = e;
7284             if (*e == '\t') e++;
7285             val = e;
7286             while (*e) e++;
7287             e++;
7288
7289             s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7290             ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid);
7291             ssh2_pkt_addstring(s->pktout, "env");
7292             ssh2_pkt_addbool(s->pktout, 1);            /* want reply */
7293             ssh2_pkt_addstring_start(s->pktout);
7294             ssh2_pkt_addstring_data(s->pktout, var, varend-var);
7295             ssh2_pkt_addstring(s->pktout, val);
7296             ssh2_pkt_send(ssh, s->pktout);
7297
7298             s->num_env++;
7299         }
7300
7301         logeventf(ssh, "Sent %d environment variables", s->num_env);
7302
7303         s->env_ok = 0;
7304         s->env_left = s->num_env;
7305
7306         while (s->env_left > 0) {
7307             crWaitUntilV(pktin);
7308
7309             if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7310                 if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7311                     bombout(("Unexpected response to environment request:"
7312                              " packet type %d", pktin->type));
7313                     crStopV;
7314                 }
7315             } else {
7316                 s->env_ok++;
7317             }
7318
7319             s->env_left--;
7320         }
7321
7322         if (s->env_ok == s->num_env) {
7323             logevent("All environment variables successfully set");
7324         } else if (s->env_ok == 0) {
7325             logevent("All environment variables refused");
7326             c_write_str(ssh, "Server refused to set environment variables\r\n");
7327         } else {
7328             logeventf(ssh, "%d environment variables refused",
7329                       s->num_env - s->env_ok);
7330             c_write_str(ssh, "Server refused to set all environment variables\r\n");
7331         }
7332     }
7333
7334     /*
7335      * Start a shell or a remote command. We may have to attempt
7336      * this twice if the config data has provided a second choice
7337      * of command.
7338      */
7339     if (ssh->mainchan) while (1) {
7340         int subsys;
7341         char *cmd;
7342
7343         if (ssh->fallback_cmd) {
7344             subsys = ssh->cfg.ssh_subsys2;
7345             cmd = ssh->cfg.remote_cmd_ptr2;
7346         } else {
7347             subsys = ssh->cfg.ssh_subsys;
7348             cmd = ssh->cfg.remote_cmd_ptr;
7349             if (!cmd) cmd = ssh->cfg.remote_cmd;
7350         }
7351
7352         s->pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7353         ssh2_pkt_adduint32(s->pktout, ssh->mainchan->remoteid); /* recipient channel */
7354         if (subsys) {
7355             ssh2_pkt_addstring(s->pktout, "subsystem");
7356             ssh2_pkt_addbool(s->pktout, 1);            /* want reply */
7357             ssh2_pkt_addstring(s->pktout, cmd);
7358         } else if (*cmd) {
7359             ssh2_pkt_addstring(s->pktout, "exec");
7360             ssh2_pkt_addbool(s->pktout, 1);            /* want reply */
7361             ssh2_pkt_addstring(s->pktout, cmd);
7362         } else {
7363             ssh2_pkt_addstring(s->pktout, "shell");
7364             ssh2_pkt_addbool(s->pktout, 1);            /* want reply */
7365         }
7366         ssh2_pkt_send(ssh, s->pktout);
7367
7368         crWaitUntilV(pktin);
7369
7370         if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
7371             if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
7372                 bombout(("Unexpected response to shell/command request:"
7373                          " packet type %d", pktin->type));
7374                 crStopV;
7375             }
7376             /*
7377              * We failed to start the command. If this is the
7378              * fallback command, we really are finished; if it's
7379              * not, and if the fallback command exists, try falling
7380              * back to it before complaining.
7381              */
7382             if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
7383                 logevent("Primary command failed; attempting fallback");
7384                 ssh->fallback_cmd = TRUE;
7385                 continue;
7386             }
7387             bombout(("Server refused to start a shell/command"));
7388             crStopV;
7389         } else {
7390             logevent("Started a shell/command");
7391         }
7392         break;
7393     }
7394
7395     ssh->state = SSH_STATE_SESSION;
7396     if (ssh->size_needed)
7397         ssh_size(ssh, ssh->term_width, ssh->term_height);
7398     if (ssh->eof_needed)
7399         ssh_special(ssh, TS_EOF);
7400
7401     /*
7402      * Transfer data!
7403      */
7404     if (ssh->ldisc)
7405         ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
7406     if (ssh->mainchan)
7407         ssh->send_ok = 1;
7408     while (1) {
7409         crReturnV;
7410         s->try_send = FALSE;
7411         if (pktin) {
7412
7413             /*
7414              * _All_ the connection-layer packets we expect to
7415              * receive are now handled by the dispatch table.
7416              * Anything that reaches here must be bogus.
7417              */
7418
7419             bombout(("Strange packet received: type %d", pktin->type));
7420             crStopV;
7421         } else if (ssh->mainchan) {
7422             /*
7423              * We have spare data. Add it to the channel buffer.
7424              */
7425             ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
7426             s->try_send = TRUE;
7427         }
7428         if (s->try_send) {
7429             int i;
7430             struct ssh_channel *c;
7431             /*
7432              * Try to send data on all channels if we can.
7433              */
7434             for (i = 0; NULL != (c = index234(ssh->channels, i)); i++)
7435                 ssh2_try_send_and_unthrottle(c);
7436         }
7437     }
7438
7439     crFinishV;
7440 }
7441
7442 /*
7443  * Handlers for SSH-2 messages that might arrive at any moment.
7444  */
7445 static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
7446 {
7447     /* log reason code in disconnect message */
7448     char *buf, *msg;
7449     int nowlen, reason, msglen;
7450
7451     reason = ssh_pkt_getuint32(pktin);
7452     ssh_pkt_getstring(pktin, &msg, &msglen);
7453
7454     if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
7455         buf = dupprintf("Received disconnect message (%s)",
7456                         ssh2_disconnect_reasons[reason]);
7457     } else {
7458         buf = dupprintf("Received disconnect message (unknown"
7459                         " type %d)", reason);
7460     }
7461     logevent(buf);
7462     sfree(buf);
7463     buf = dupprintf("Disconnection message text: %n%.*s",
7464                     &nowlen, msglen, msg);
7465     logevent(buf);
7466     bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
7467              reason,
7468              (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
7469              ssh2_disconnect_reasons[reason] : "unknown",
7470              buf+nowlen));
7471     sfree(buf);
7472 }
7473
7474 static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
7475 {
7476     /* log the debug message */
7477     char *msg;
7478     int msglen;
7479     int always_display;
7480
7481     /* XXX maybe we should actually take notice of this */
7482     always_display = ssh2_pkt_getbool(pktin);
7483     ssh_pkt_getstring(pktin, &msg, &msglen);
7484
7485     logeventf(ssh, "Remote debug message: %.*s", msglen, msg);
7486 }
7487
7488 static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
7489 {
7490     struct Packet *pktout;
7491     pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
7492     ssh2_pkt_adduint32(pktout, pktin->sequence);
7493     /*
7494      * UNIMPLEMENTED messages MUST appear in the same order as the
7495      * messages they respond to. Hence, never queue them.
7496      */
7497     ssh2_pkt_send_noqueue(ssh, pktout);
7498 }
7499
7500 /*
7501  * Handle the top-level SSH-2 protocol.
7502  */
7503 static void ssh2_protocol_setup(Ssh ssh)
7504 {
7505     int i;
7506
7507     /*
7508      * Most messages cause SSH2_MSG_UNIMPLEMENTED.
7509      */
7510     for (i = 0; i < 256; i++)
7511         ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
7512
7513     /*
7514      * Any message we actually understand, we set to NULL so that
7515      * the coroutines will get it.
7516      */
7517     ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = NULL;
7518     ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = NULL;
7519     ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = NULL;
7520     ssh->packet_dispatch[SSH2_MSG_KEXINIT] = NULL;
7521     ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = NULL;
7522     ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = NULL;
7523     ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = NULL;
7524     /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = NULL; duplicate case value */
7525     /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = NULL; duplicate case value */
7526     ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = NULL;
7527     ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = NULL;
7528     ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = NULL;
7529     ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = NULL;
7530     ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = NULL;
7531     ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
7532     ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = NULL;
7533     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = NULL; duplicate case value */
7534     /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = NULL; duplicate case value */
7535     ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = NULL;
7536     ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = NULL;
7537     ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = NULL;
7538     ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = NULL;
7539     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = NULL;
7540     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = NULL;
7541     ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = NULL;
7542     ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = NULL;
7543     ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = NULL;
7544     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = NULL;
7545     ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = NULL;
7546     ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = NULL;
7547     ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = NULL;
7548     ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = NULL;
7549     ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = NULL;
7550
7551     /*
7552      * These special message types we install handlers for.
7553      */
7554     ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
7555     ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
7556     ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
7557 }
7558
7559 static void ssh2_timer(void *ctx, long now)
7560 {
7561     Ssh ssh = (Ssh)ctx;
7562
7563     if (ssh->state == SSH_STATE_CLOSED)
7564         return;
7565
7566     if (!ssh->kex_in_progress && ssh->cfg.ssh_rekey_time != 0 &&
7567         now - ssh->next_rekey >= 0) {
7568         do_ssh2_transport(ssh, "timeout", -1, NULL);
7569     }
7570 }
7571
7572 static void ssh2_protocol(Ssh ssh, void *vin, int inlen,
7573                           struct Packet *pktin)
7574 {
7575     unsigned char *in = (unsigned char *)vin;
7576     if (ssh->state == SSH_STATE_CLOSED)
7577         return;
7578
7579     if (pktin) {
7580         ssh->incoming_data_size += pktin->encrypted_len;
7581         if (!ssh->kex_in_progress &&
7582             ssh->max_data_size != 0 &&
7583             ssh->incoming_data_size > ssh->max_data_size)
7584             do_ssh2_transport(ssh, "too much data received", -1, NULL);
7585     }
7586
7587     if (pktin && ssh->packet_dispatch[pktin->type]) {
7588         ssh->packet_dispatch[pktin->type](ssh, pktin);
7589         return;
7590     }
7591
7592     if (!ssh->protocol_initial_phase_done ||
7593         (pktin && pktin->type >= 20 && pktin->type < 50)) {
7594         if (do_ssh2_transport(ssh, in, inlen, pktin) &&
7595             !ssh->protocol_initial_phase_done) {
7596             ssh->protocol_initial_phase_done = TRUE;
7597             /*
7598              * Allow authconn to initialise itself.
7599              */
7600             do_ssh2_authconn(ssh, NULL, 0, NULL);
7601         }
7602     } else {
7603         do_ssh2_authconn(ssh, in, inlen, pktin);
7604     }
7605 }
7606
7607 /*
7608  * Called to set up the connection.
7609  *
7610  * Returns an error message, or NULL on success.
7611  */
7612 static const char *ssh_init(void *frontend_handle, void **backend_handle,
7613                             Config *cfg,
7614                             char *host, int port, char **realhost, int nodelay,
7615                             int keepalive)
7616 {
7617     const char *p;
7618     Ssh ssh;
7619
7620     ssh = snew(struct ssh_tag);
7621     ssh->cfg = *cfg;                   /* STRUCTURE COPY */
7622     ssh->version = 0;                  /* when not ready yet */
7623     ssh->s = NULL;
7624     ssh->cipher = NULL;
7625     ssh->v1_cipher_ctx = NULL;
7626     ssh->crcda_ctx = NULL;
7627     ssh->cscipher = NULL;
7628     ssh->cs_cipher_ctx = NULL;
7629     ssh->sccipher = NULL;
7630     ssh->sc_cipher_ctx = NULL;
7631     ssh->csmac = NULL;
7632     ssh->cs_mac_ctx = NULL;
7633     ssh->scmac = NULL;
7634     ssh->sc_mac_ctx = NULL;
7635     ssh->cscomp = NULL;
7636     ssh->cs_comp_ctx = NULL;
7637     ssh->sccomp = NULL;
7638     ssh->sc_comp_ctx = NULL;
7639     ssh->kex = NULL;
7640     ssh->kex_ctx = NULL;
7641     ssh->hostkey = NULL;
7642     ssh->exitcode = -1;
7643     ssh->close_expected = FALSE;
7644     ssh->state = SSH_STATE_PREPACKET;
7645     ssh->size_needed = FALSE;
7646     ssh->eof_needed = FALSE;
7647     ssh->ldisc = NULL;
7648     ssh->logctx = NULL;
7649     ssh->deferred_send_data = NULL;
7650     ssh->deferred_len = 0;
7651     ssh->deferred_size = 0;
7652     ssh->fallback_cmd = 0;
7653     ssh->pkt_ctx = 0;
7654     ssh->x11auth = NULL;
7655     ssh->v1_compressing = FALSE;
7656     ssh->v2_outgoing_sequence = 0;
7657     ssh->ssh1_rdpkt_crstate = 0;
7658     ssh->ssh2_rdpkt_crstate = 0;
7659     ssh->do_ssh_init_crstate = 0;
7660     ssh->ssh_gotdata_crstate = 0;
7661     ssh->do_ssh1_connection_crstate = 0;
7662     ssh->do_ssh1_login_crstate = 0;
7663     ssh->do_ssh2_transport_crstate = 0;
7664     ssh->do_ssh2_authconn_crstate = 0;
7665     ssh->do_ssh_init_state = NULL;
7666     ssh->do_ssh1_login_state = NULL;
7667     ssh->do_ssh2_transport_state = NULL;
7668     ssh->do_ssh2_authconn_state = NULL;
7669     ssh->mainchan = NULL;
7670     ssh->throttled_all = 0;
7671     ssh->v1_stdout_throttling = 0;
7672     ssh->queue = NULL;
7673     ssh->queuelen = ssh->queuesize = 0;
7674     ssh->queueing = FALSE;
7675     ssh->qhead = ssh->qtail = NULL;
7676     ssh->deferred_rekey_reason = NULL;
7677     bufchain_init(&ssh->queued_incoming_data);
7678     ssh->frozen = FALSE;
7679
7680     *backend_handle = ssh;
7681
7682 #ifdef MSCRYPTOAPI
7683     if (crypto_startup() == 0)
7684         return "Microsoft high encryption pack not installed!";
7685 #endif
7686
7687     ssh->frontend = frontend_handle;
7688     ssh->term_width = ssh->cfg.width;
7689     ssh->term_height = ssh->cfg.height;
7690
7691     ssh->channels = NULL;
7692     ssh->rportfwds = NULL;
7693     ssh->portfwds = NULL;
7694
7695     ssh->send_ok = 0;
7696     ssh->editing = 0;
7697     ssh->echoing = 0;
7698     ssh->v1_throttle_count = 0;
7699     ssh->overall_bufsize = 0;
7700     ssh->fallback_cmd = 0;
7701
7702     ssh->protocol = NULL;
7703
7704     ssh->protocol_initial_phase_done = FALSE;
7705
7706     ssh->pinger = NULL;
7707
7708     ssh->incoming_data_size = ssh->outgoing_data_size =
7709         ssh->deferred_data_size = 0L;
7710     ssh->max_data_size = parse_blocksize(ssh->cfg.ssh_rekey_data);
7711     ssh->kex_in_progress = FALSE;
7712
7713     p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
7714     if (p != NULL)
7715         return p;
7716
7717     random_ref();
7718
7719     return NULL;
7720 }
7721
7722 static void ssh_free(void *handle)
7723 {
7724     Ssh ssh = (Ssh) handle;
7725     struct ssh_channel *c;
7726     struct ssh_rportfwd *pf;
7727
7728     if (ssh->v1_cipher_ctx)
7729         ssh->cipher->free_context(ssh->v1_cipher_ctx);
7730     if (ssh->cs_cipher_ctx)
7731         ssh->cscipher->free_context(ssh->cs_cipher_ctx);
7732     if (ssh->sc_cipher_ctx)
7733         ssh->sccipher->free_context(ssh->sc_cipher_ctx);
7734     if (ssh->cs_mac_ctx)
7735         ssh->csmac->free_context(ssh->cs_mac_ctx);
7736     if (ssh->sc_mac_ctx)
7737         ssh->scmac->free_context(ssh->sc_mac_ctx);
7738     if (ssh->cs_comp_ctx) {
7739         if (ssh->cscomp)
7740             ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
7741         else
7742             zlib_compress_cleanup(ssh->cs_comp_ctx);
7743     }
7744     if (ssh->sc_comp_ctx) {
7745         if (ssh->sccomp)
7746             ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
7747         else
7748             zlib_decompress_cleanup(ssh->sc_comp_ctx);
7749     }
7750     if (ssh->kex_ctx)
7751         dh_cleanup(ssh->kex_ctx);
7752     sfree(ssh->savedhost);
7753
7754     while (ssh->queuelen-- > 0)
7755         ssh_free_packet(ssh->queue[ssh->queuelen]);
7756     sfree(ssh->queue);
7757
7758     while (ssh->qhead) {
7759         struct queued_handler *qh = ssh->qhead;
7760         ssh->qhead = qh->next;
7761         sfree(ssh->qhead);
7762     }
7763     ssh->qhead = ssh->qtail = NULL;
7764
7765     if (ssh->channels) {
7766         while ((c = delpos234(ssh->channels, 0)) != NULL) {
7767             switch (c->type) {
7768               case CHAN_X11:
7769                 if (c->u.x11.s != NULL)
7770                     x11_close(c->u.x11.s);
7771                 break;
7772               case CHAN_SOCKDATA:
7773                 if (c->u.pfd.s != NULL)
7774                     pfd_close(c->u.pfd.s);
7775                 break;
7776             }
7777             sfree(c);
7778         }
7779         freetree234(ssh->channels);
7780         ssh->channels = NULL;
7781     }
7782
7783     if (ssh->rportfwds) {
7784         while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
7785             sfree(pf);
7786         freetree234(ssh->rportfwds);
7787         ssh->rportfwds = NULL;
7788     }
7789     sfree(ssh->deferred_send_data);
7790     if (ssh->x11auth)
7791         x11_free_auth(ssh->x11auth);
7792     sfree(ssh->do_ssh_init_state);
7793     sfree(ssh->do_ssh1_login_state);
7794     sfree(ssh->do_ssh2_transport_state);
7795     sfree(ssh->do_ssh2_authconn_state);
7796     if (ssh->crcda_ctx) {
7797         crcda_free_context(ssh->crcda_ctx);
7798         ssh->crcda_ctx = NULL;
7799     }
7800     if (ssh->s)
7801         ssh_do_close(ssh, TRUE);
7802     expire_timer_context(ssh);
7803     if (ssh->pinger)
7804         pinger_free(ssh->pinger);
7805     bufchain_clear(&ssh->queued_incoming_data);
7806     sfree(ssh);
7807
7808     random_unref();
7809 }
7810
7811 /*
7812  * Reconfigure the SSH backend.
7813  */
7814 static void ssh_reconfig(void *handle, Config *cfg)
7815 {
7816     Ssh ssh = (Ssh) handle;
7817     char *rekeying = NULL, rekey_mandatory = FALSE;
7818     unsigned long old_max_data_size;
7819
7820     pinger_reconfig(ssh->pinger, &ssh->cfg, cfg);
7821     ssh_setup_portfwd(ssh, cfg);
7822
7823     if (ssh->cfg.ssh_rekey_time != cfg->ssh_rekey_time &&
7824         cfg->ssh_rekey_time != 0) {
7825         long new_next = ssh->last_rekey + cfg->ssh_rekey_time*60*TICKSPERSEC;
7826         long now = GETTICKCOUNT();
7827
7828         if (new_next - now < 0) {
7829             rekeying = "timeout shortened";
7830         } else {
7831             ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
7832         }
7833     }
7834
7835     old_max_data_size = ssh->max_data_size;
7836     ssh->max_data_size = parse_blocksize(cfg->ssh_rekey_data);
7837     if (old_max_data_size != ssh->max_data_size &&
7838         ssh->max_data_size != 0) {
7839         if (ssh->outgoing_data_size > ssh->max_data_size ||
7840             ssh->incoming_data_size > ssh->max_data_size)
7841             rekeying = "data limit lowered";
7842     }
7843
7844     if (ssh->cfg.compression != cfg->compression) {
7845         rekeying = "compression setting changed";
7846         rekey_mandatory = TRUE;
7847     }
7848
7849     if (ssh->cfg.ssh2_des_cbc != cfg->ssh2_des_cbc ||
7850         memcmp(ssh->cfg.ssh_cipherlist, cfg->ssh_cipherlist,
7851                sizeof(ssh->cfg.ssh_cipherlist))) {
7852         rekeying = "cipher settings changed";
7853         rekey_mandatory = TRUE;
7854     }
7855
7856     ssh->cfg = *cfg;                   /* STRUCTURE COPY */
7857
7858     if (rekeying) {
7859         if (!ssh->kex_in_progress) {
7860             do_ssh2_transport(ssh, rekeying, -1, NULL);
7861         } else if (rekey_mandatory) {
7862             ssh->deferred_rekey_reason = rekeying;
7863         }
7864     }
7865 }
7866
7867 /*
7868  * Called to send data down the Telnet connection.
7869  */
7870 static int ssh_send(void *handle, char *buf, int len)
7871 {
7872     Ssh ssh = (Ssh) handle;
7873
7874     if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7875         return 0;
7876
7877     ssh->protocol(ssh, (unsigned char *)buf, len, 0);
7878
7879     return ssh_sendbuffer(ssh);
7880 }
7881
7882 /*
7883  * Called to query the current amount of buffered stdin data.
7884  */
7885 static int ssh_sendbuffer(void *handle)
7886 {
7887     Ssh ssh = (Ssh) handle;
7888     int override_value;
7889
7890     if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
7891         return 0;
7892
7893     /*
7894      * If the SSH socket itself has backed up, add the total backup
7895      * size on that to any individual buffer on the stdin channel.
7896      */
7897     override_value = 0;
7898     if (ssh->throttled_all)
7899         override_value = ssh->overall_bufsize;
7900
7901     if (ssh->version == 1) {
7902         return override_value;
7903     } else if (ssh->version == 2) {
7904         if (!ssh->mainchan || ssh->mainchan->closes > 0)
7905             return override_value;
7906         else
7907             return (override_value +
7908                     bufchain_size(&ssh->mainchan->v.v2.outbuffer));
7909     }
7910
7911     return 0;
7912 }
7913
7914 /*
7915  * Called to set the size of the window from SSH's POV.
7916  */
7917 static void ssh_size(void *handle, int width, int height)
7918 {
7919     Ssh ssh = (Ssh) handle;
7920     struct Packet *pktout;
7921
7922     ssh->term_width = width;
7923     ssh->term_height = height;
7924
7925     switch (ssh->state) {
7926       case SSH_STATE_BEFORE_SIZE:
7927       case SSH_STATE_PREPACKET:
7928       case SSH_STATE_CLOSED:
7929         break;                         /* do nothing */
7930       case SSH_STATE_INTERMED:
7931         ssh->size_needed = TRUE;       /* buffer for later */
7932         break;
7933       case SSH_STATE_SESSION:
7934         if (!ssh->cfg.nopty) {
7935             if (ssh->version == 1) {
7936                 send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
7937                             PKT_INT, ssh->term_height,
7938                             PKT_INT, ssh->term_width,
7939                             PKT_INT, 0, PKT_INT, 0, PKT_END);
7940             } else if (ssh->mainchan) {
7941                 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
7942                 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
7943                 ssh2_pkt_addstring(pktout, "window-change");
7944                 ssh2_pkt_addbool(pktout, 0);
7945                 ssh2_pkt_adduint32(pktout, ssh->term_width);
7946                 ssh2_pkt_adduint32(pktout, ssh->term_height);
7947                 ssh2_pkt_adduint32(pktout, 0);
7948                 ssh2_pkt_adduint32(pktout, 0);
7949                 ssh2_pkt_send(ssh, pktout);
7950             }
7951         }
7952         break;
7953     }
7954 }
7955
7956 /*
7957  * Return a list of the special codes that make sense in this
7958  * protocol.
7959  */
7960 static const struct telnet_special *ssh_get_specials(void *handle)
7961 {
7962     static const struct telnet_special ssh1_ignore_special[] = {
7963         {"IGNORE message", TS_NOP}
7964     };
7965     static const struct telnet_special ssh2_transport_specials[] = {
7966         {"IGNORE message", TS_NOP},
7967         {"Repeat key exchange", TS_REKEY},
7968     };
7969     static const struct telnet_special ssh2_session_specials[] = {
7970         {NULL, TS_SEP},
7971         {"Break", TS_BRK},
7972         /* These are the signal names defined by draft-ietf-secsh-connect-23.
7973          * They include all the ISO C signals, but are a subset of the POSIX
7974          * required signals. */
7975         {"SIGINT (Interrupt)", TS_SIGINT},
7976         {"SIGTERM (Terminate)", TS_SIGTERM},
7977         {"SIGKILL (Kill)", TS_SIGKILL},
7978         {"SIGQUIT (Quit)", TS_SIGQUIT},
7979         {"SIGHUP (Hangup)", TS_SIGHUP},
7980         {"More signals", TS_SUBMENU},
7981           {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
7982           {"SIGFPE",  TS_SIGFPE},  {"SIGILL",  TS_SIGILL},
7983           {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
7984           {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
7985         {NULL, TS_EXITMENU}
7986     };
7987     static const struct telnet_special specials_end[] = {
7988         {NULL, TS_EXITMENU}
7989     };
7990     /* XXX review this length for any changes: */
7991     static struct telnet_special ssh_specials[lenof(ssh2_transport_specials) +
7992                                               lenof(ssh2_session_specials) +
7993                                               lenof(specials_end)];
7994     Ssh ssh = (Ssh) handle;
7995     int i = 0;
7996 #define ADD_SPECIALS(name) \
7997     do { \
7998         assert((i + lenof(name)) <= lenof(ssh_specials)); \
7999         memcpy(&ssh_specials[i], name, sizeof name); \
8000         i += lenof(name); \
8001     } while(0)
8002
8003     if (ssh->version == 1) {
8004         /* Don't bother offering IGNORE if we've decided the remote
8005          * won't cope with it, since we wouldn't bother sending it if
8006          * asked anyway. */
8007         if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
8008             ADD_SPECIALS(ssh1_ignore_special);
8009     } else if (ssh->version == 2) {
8010         ADD_SPECIALS(ssh2_transport_specials);
8011         if (ssh->mainchan)
8012             ADD_SPECIALS(ssh2_session_specials);
8013     } /* else we're not ready yet */
8014
8015     if (i) {
8016         ADD_SPECIALS(specials_end);
8017         return ssh_specials;
8018     } else {
8019         return NULL;
8020     }
8021 #undef ADD_SPECIALS
8022 }
8023
8024 /*
8025  * Send Telnet special codes. TS_EOF is useful for `plink', so you
8026  * can send an EOF and collect resulting output (e.g. `plink
8027  * hostname sort').
8028  */
8029 static void ssh_special(void *handle, Telnet_Special code)
8030 {
8031     Ssh ssh = (Ssh) handle;
8032     struct Packet *pktout;
8033
8034     if (code == TS_EOF) {
8035         if (ssh->state != SSH_STATE_SESSION) {
8036             /*
8037              * Buffer the EOF in case we are pre-SESSION, so we can
8038              * send it as soon as we reach SESSION.
8039              */
8040             if (code == TS_EOF)
8041                 ssh->eof_needed = TRUE;
8042             return;
8043         }
8044         if (ssh->version == 1) {
8045             send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
8046         } else if (ssh->mainchan) {
8047             struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
8048             ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8049             ssh2_pkt_send(ssh, pktout);
8050             ssh->send_ok = 0;          /* now stop trying to read from stdin */
8051         }
8052         logevent("Sent EOF message");
8053     } else if (code == TS_PING || code == TS_NOP) {
8054         if (ssh->state == SSH_STATE_CLOSED
8055             || ssh->state == SSH_STATE_PREPACKET) return;
8056         if (ssh->version == 1) {
8057             if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
8058                 send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
8059         } else {
8060             pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
8061             ssh2_pkt_addstring_start(pktout);
8062             ssh2_pkt_send_noqueue(ssh, pktout);
8063         }
8064     } else if (code == TS_REKEY) {
8065         if (!ssh->kex_in_progress && ssh->version == 2) {
8066             do_ssh2_transport(ssh, "at user request", -1, NULL);
8067         }
8068     } else if (code == TS_BRK) {
8069         if (ssh->state == SSH_STATE_CLOSED
8070             || ssh->state == SSH_STATE_PREPACKET) return;
8071         if (ssh->version == 1) {
8072             logevent("Unable to send BREAK signal in SSH-1");
8073         } else if (ssh->mainchan) {
8074             pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8075             ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8076             ssh2_pkt_addstring(pktout, "break");
8077             ssh2_pkt_addbool(pktout, 0);
8078             ssh2_pkt_adduint32(pktout, 0);   /* default break length */
8079             ssh2_pkt_send(ssh, pktout);
8080         }
8081     } else {
8082         /* Is is a POSIX signal? */
8083         char *signame = NULL;
8084         if (code == TS_SIGABRT) signame = "ABRT";
8085         if (code == TS_SIGALRM) signame = "ALRM";
8086         if (code == TS_SIGFPE)  signame = "FPE";
8087         if (code == TS_SIGHUP)  signame = "HUP";
8088         if (code == TS_SIGILL)  signame = "ILL";
8089         if (code == TS_SIGINT)  signame = "INT";
8090         if (code == TS_SIGKILL) signame = "KILL";
8091         if (code == TS_SIGPIPE) signame = "PIPE";
8092         if (code == TS_SIGQUIT) signame = "QUIT";
8093         if (code == TS_SIGSEGV) signame = "SEGV";
8094         if (code == TS_SIGTERM) signame = "TERM";
8095         if (code == TS_SIGUSR1) signame = "USR1";
8096         if (code == TS_SIGUSR2) signame = "USR2";
8097         /* The SSH-2 protocol does in principle support arbitrary named
8098          * signals, including signame@domain, but we don't support those. */
8099         if (signame) {
8100             /* It's a signal. */
8101             if (ssh->version == 2 && ssh->mainchan) {
8102                 pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
8103                 ssh2_pkt_adduint32(pktout, ssh->mainchan->remoteid);
8104                 ssh2_pkt_addstring(pktout, "signal");
8105                 ssh2_pkt_addbool(pktout, 0);
8106                 ssh2_pkt_addstring(pktout, signame);
8107                 ssh2_pkt_send(ssh, pktout);
8108                 logeventf(ssh, "Sent signal SIG%s", signame);
8109             }
8110         } else {
8111             /* Never heard of it. Do nothing */
8112         }
8113     }
8114 }
8115
8116 void *new_sock_channel(void *handle, Socket s)
8117 {
8118     Ssh ssh = (Ssh) handle;
8119     struct ssh_channel *c;
8120     c = snew(struct ssh_channel);
8121     c->ssh = ssh;
8122
8123     if (c) {
8124         c->halfopen = TRUE;
8125         c->localid = alloc_channel_id(ssh);
8126         c->closes = 0;
8127         c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
8128         c->u.pfd.s = s;
8129         bufchain_init(&c->v.v2.outbuffer);
8130         add234(ssh->channels, c);
8131     }
8132     return c;
8133 }
8134
8135 /*
8136  * This is called when stdout/stderr (the entity to which
8137  * from_backend sends data) manages to clear some backlog.
8138  */
8139 static void ssh_unthrottle(void *handle, int bufsize)
8140 {
8141     Ssh ssh = (Ssh) handle;
8142     if (ssh->version == 1) {
8143         if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
8144             ssh->v1_stdout_throttling = 0;
8145             ssh1_throttle(ssh, -1);
8146         }
8147     } else {
8148         if (ssh->mainchan && ssh->mainchan->closes == 0)
8149             ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
8150     }
8151 }
8152
8153 void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
8154 {
8155     struct ssh_channel *c = (struct ssh_channel *)channel;
8156     Ssh ssh = c->ssh;
8157     struct Packet *pktout;
8158
8159     logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
8160
8161     if (ssh->version == 1) {
8162         send_packet(ssh, SSH1_MSG_PORT_OPEN,
8163                     PKT_INT, c->localid,
8164                     PKT_STR, hostname,
8165                     PKT_INT, port,
8166                     /* PKT_STR, <org:orgport>, */
8167                     PKT_END);
8168     } else {
8169         pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
8170         ssh2_pkt_addstring(pktout, "direct-tcpip");
8171         ssh2_pkt_adduint32(pktout, c->localid);
8172         c->v.v2.locwindow = OUR_V2_WINSIZE;
8173         ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
8174         ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT);      /* our max pkt size */
8175         ssh2_pkt_addstring(pktout, hostname);
8176         ssh2_pkt_adduint32(pktout, port);
8177         /*
8178          * We make up values for the originator data; partly it's
8179          * too much hassle to keep track, and partly I'm not
8180          * convinced the server should be told details like that
8181          * about my local network configuration.
8182          */
8183         ssh2_pkt_addstring(pktout, "client-side-connection");
8184         ssh2_pkt_adduint32(pktout, 0);
8185         ssh2_pkt_send(ssh, pktout);
8186     }
8187 }
8188
8189 static Socket ssh_socket(void *handle)
8190 {
8191     Ssh ssh = (Ssh) handle;
8192     return ssh->s;
8193 }
8194
8195 static int ssh_sendok(void *handle)
8196 {
8197     Ssh ssh = (Ssh) handle;
8198     return ssh->send_ok;
8199 }
8200
8201 static int ssh_ldisc(void *handle, int option)
8202 {
8203     Ssh ssh = (Ssh) handle;
8204     if (option == LD_ECHO)
8205         return ssh->echoing;
8206     if (option == LD_EDIT)
8207         return ssh->editing;
8208     return FALSE;
8209 }
8210
8211 static void ssh_provide_ldisc(void *handle, void *ldisc)
8212 {
8213     Ssh ssh = (Ssh) handle;
8214     ssh->ldisc = ldisc;
8215 }
8216
8217 static void ssh_provide_logctx(void *handle, void *logctx)
8218 {
8219     Ssh ssh = (Ssh) handle;
8220     ssh->logctx = logctx;
8221 }
8222
8223 static int ssh_return_exitcode(void *handle)
8224 {
8225     Ssh ssh = (Ssh) handle;
8226     if (ssh->s != NULL)
8227         return -1;
8228     else
8229         return (ssh->exitcode >= 0 ? ssh->exitcode : 0);
8230 }
8231
8232 /*
8233  * cfg_info for SSH is the currently running version of the
8234  * protocol. (1 for 1; 2 for 2; 0 for not-decided-yet.)
8235  */
8236 static int ssh_cfg_info(void *handle)
8237 {
8238     Ssh ssh = (Ssh) handle;
8239     return ssh->version;
8240 }
8241
8242 /*
8243  * Gross hack: pscp will try to start SFTP but fall back to scp1 if
8244  * that fails. This variable is the means by which scp.c can reach
8245  * into the SSH code and find out which one it got.
8246  */
8247 extern int ssh_fallback_cmd(void *handle)
8248 {
8249     Ssh ssh = (Ssh) handle;
8250     return ssh->fallback_cmd;
8251 }
8252
8253 Backend ssh_backend = {
8254     ssh_init,
8255     ssh_free,
8256     ssh_reconfig,
8257     ssh_send,
8258     ssh_sendbuffer,
8259     ssh_size,
8260     ssh_special,
8261     ssh_get_specials,
8262     ssh_socket,
8263     ssh_return_exitcode,
8264     ssh_sendok,
8265     ssh_ldisc,
8266     ssh_provide_ldisc,
8267     ssh_provide_logctx,
8268     ssh_unthrottle,
8269     ssh_cfg_info,
8270     22
8271 };