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