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