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