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