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