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