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