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