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