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