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