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