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