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