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