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