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