]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - ssh.c
Remove the special hooks in ssh.c for pscp. pscp now uses the standard
[PuTTY.git] / ssh.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include <assert.h>
5 #ifndef AUTO_WINSOCK
6 #ifdef WINSOCK_TWO
7 #include <winsock2.h>
8 #else
9 #include <winsock.h>
10 #endif
11 #endif
12
13 #include "putty.h"
14 #include "tree234.h"
15 #include "ssh.h"
16
17 #ifndef FALSE
18 #define FALSE 0
19 #endif
20 #ifndef TRUE
21 #define TRUE 1
22 #endif
23
24 #define logevent(s) { logevent(s); \
25                       if ((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)) \
26                       fprintf(stderr, "%s\n", s); }
27
28 #define bombout(msg) ( ssh_state == SSH_STATE_CLOSED, closesocket(s), \
29                        s = INVALID_SOCKET, connection_fatal msg )
30
31 #define SSH1_MSG_DISCONNECT                       1    /* 0x1 */
32 #define SSH1_SMSG_PUBLIC_KEY                      2    /* 0x2 */
33 #define SSH1_CMSG_SESSION_KEY                     3    /* 0x3 */
34 #define SSH1_CMSG_USER                            4    /* 0x4 */
35 #define SSH1_CMSG_AUTH_RSA                        6    /* 0x6 */
36 #define SSH1_SMSG_AUTH_RSA_CHALLENGE              7    /* 0x7 */
37 #define SSH1_CMSG_AUTH_RSA_RESPONSE               8    /* 0x8 */
38 #define SSH1_CMSG_AUTH_PASSWORD                   9    /* 0x9 */
39 #define SSH1_CMSG_REQUEST_PTY                     10   /* 0xa */
40 #define SSH1_CMSG_WINDOW_SIZE                     11   /* 0xb */
41 #define SSH1_CMSG_EXEC_SHELL                      12   /* 0xc */
42 #define SSH1_CMSG_EXEC_CMD                        13   /* 0xd */
43 #define SSH1_SMSG_SUCCESS                         14   /* 0xe */
44 #define SSH1_SMSG_FAILURE                         15   /* 0xf */
45 #define SSH1_CMSG_STDIN_DATA                      16   /* 0x10 */
46 #define SSH1_SMSG_STDOUT_DATA                     17   /* 0x11 */
47 #define SSH1_SMSG_STDERR_DATA                     18   /* 0x12 */
48 #define SSH1_CMSG_EOF                             19   /* 0x13 */
49 #define SSH1_SMSG_EXIT_STATUS                     20   /* 0x14 */
50 #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION        21   /* 0x15 */
51 #define SSH1_MSG_CHANNEL_OPEN_FAILURE             22   /* 0x16 */
52 #define SSH1_MSG_CHANNEL_DATA                     23   /* 0x17 */
53 #define SSH1_MSG_CHANNEL_CLOSE                    24   /* 0x18 */
54 #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION       25   /* 0x19 */
55 #define SSH1_CMSG_AGENT_REQUEST_FORWARDING        30   /* 0x1e */
56 #define SSH1_SMSG_AGENT_OPEN                      31   /* 0x1f */
57 #define SSH1_CMSG_EXIT_CONFIRMATION               33   /* 0x21 */
58 #define SSH1_MSG_IGNORE                           32   /* 0x20 */
59 #define SSH1_MSG_DEBUG                            36   /* 0x24 */
60 #define SSH1_CMSG_AUTH_TIS                        39   /* 0x27 */
61 #define SSH1_SMSG_AUTH_TIS_CHALLENGE              40   /* 0x28 */
62 #define SSH1_CMSG_AUTH_TIS_RESPONSE               41   /* 0x29 */
63 #define SSH1_CMSG_AUTH_CCARD                      70   /* 0x46 */
64 #define SSH1_SMSG_AUTH_CCARD_CHALLENGE            71   /* 0x47 */
65 #define SSH1_CMSG_AUTH_CCARD_RESPONSE             72   /* 0x48 */
66
67 #define SSH1_AUTH_TIS                             5    /* 0x5 */
68 #define SSH1_AUTH_CCARD                           16   /* 0x10 */
69
70 #define SSH_AGENTC_REQUEST_RSA_IDENTITIES         1    /* 0x1 */
71 #define SSH_AGENT_RSA_IDENTITIES_ANSWER           2    /* 0x2 */
72 #define SSH_AGENTC_RSA_CHALLENGE                  3    /* 0x3 */
73 #define SSH_AGENT_RSA_RESPONSE                    4    /* 0x4 */
74 #define SSH_AGENT_FAILURE                         5    /* 0x5 */
75 #define SSH_AGENT_SUCCESS                         6    /* 0x6 */
76 #define SSH_AGENTC_ADD_RSA_IDENTITY               7    /* 0x7 */
77 #define SSH_AGENTC_REMOVE_RSA_IDENTITY            8    /* 0x8 */
78
79 #define SSH2_MSG_DISCONNECT                       1    /* 0x1 */
80 #define SSH2_MSG_IGNORE                           2    /* 0x2 */
81 #define SSH2_MSG_UNIMPLEMENTED                    3    /* 0x3 */
82 #define SSH2_MSG_DEBUG                            4    /* 0x4 */
83 #define SSH2_MSG_SERVICE_REQUEST                  5    /* 0x5 */
84 #define SSH2_MSG_SERVICE_ACCEPT                   6    /* 0x6 */
85 #define SSH2_MSG_KEXINIT                          20   /* 0x14 */
86 #define SSH2_MSG_NEWKEYS                          21   /* 0x15 */
87 #define SSH2_MSG_KEXDH_INIT                       30   /* 0x1e */
88 #define SSH2_MSG_KEXDH_REPLY                      31   /* 0x1f */
89 #define SSH2_MSG_USERAUTH_REQUEST                 50   /* 0x32 */
90 #define SSH2_MSG_USERAUTH_FAILURE                 51   /* 0x33 */
91 #define SSH2_MSG_USERAUTH_SUCCESS                 52   /* 0x34 */
92 #define SSH2_MSG_USERAUTH_BANNER                  53   /* 0x35 */
93 #define SSH2_MSG_USERAUTH_PK_OK                   60   /* 0x3c */
94 #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ        60   /* 0x3c */
95 #define SSH2_MSG_GLOBAL_REQUEST                   80   /* 0x50 */
96 #define SSH2_MSG_REQUEST_SUCCESS                  81   /* 0x51 */
97 #define SSH2_MSG_REQUEST_FAILURE                  82   /* 0x52 */
98 #define SSH2_MSG_CHANNEL_OPEN                     90   /* 0x5a */
99 #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION        91   /* 0x5b */
100 #define SSH2_MSG_CHANNEL_OPEN_FAILURE             92   /* 0x5c */
101 #define SSH2_MSG_CHANNEL_WINDOW_ADJUST            93   /* 0x5d */
102 #define SSH2_MSG_CHANNEL_DATA                     94   /* 0x5e */
103 #define SSH2_MSG_CHANNEL_EXTENDED_DATA            95   /* 0x5f */
104 #define SSH2_MSG_CHANNEL_EOF                      96   /* 0x60 */
105 #define SSH2_MSG_CHANNEL_CLOSE                    97   /* 0x61 */
106 #define SSH2_MSG_CHANNEL_REQUEST                  98   /* 0x62 */
107 #define SSH2_MSG_CHANNEL_SUCCESS                  99   /* 0x63 */
108 #define SSH2_MSG_CHANNEL_FAILURE                  100  /* 0x64 */
109
110 #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED     1    /* 0x1 */
111 #define SSH2_OPEN_CONNECT_FAILED                  2    /* 0x2 */
112 #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE            3    /* 0x3 */
113 #define SSH2_OPEN_RESOURCE_SHORTAGE               4    /* 0x4 */
114
115 #define SSH2_EXTENDED_DATA_STDERR                 1    /* 0x1 */
116
117 #define GET_32BIT(cp) \
118     (((unsigned long)(unsigned char)(cp)[0] << 24) | \
119     ((unsigned long)(unsigned char)(cp)[1] << 16) | \
120     ((unsigned long)(unsigned char)(cp)[2] << 8) | \
121     ((unsigned long)(unsigned char)(cp)[3]))
122
123 #define PUT_32BIT(cp, value) { \
124     (cp)[0] = (unsigned char)((value) >> 24); \
125     (cp)[1] = (unsigned char)((value) >> 16); \
126     (cp)[2] = (unsigned char)((value) >> 8); \
127     (cp)[3] = (unsigned char)(value); }
128
129 enum { PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM };
130
131 /* Coroutine mechanics for the sillier bits of the code */
132 #define crBegin1        static int crLine = 0;
133 #define crBegin2        switch(crLine) { case 0:;
134 #define crBegin         crBegin1; crBegin2;
135 #define crFinish(z)     } crLine = 0; return (z)
136 #define crFinishV       } crLine = 0; return
137 #define crReturn(z)     \
138         do {\
139             crLine=__LINE__; return (z); case __LINE__:;\
140         } while (0)
141 #define crReturnV       \
142         do {\
143             crLine=__LINE__; return; case __LINE__:;\
144         } while (0)
145 #define crStop(z)       do{ crLine = 0; return (z); }while(0)
146 #define crStopV         do{ crLine = 0; return; }while(0)
147 #define crWaitUntil(c)  do { crReturn(0); } while (!(c))
148 #define crWaitUntilV(c) do { crReturnV; } while (!(c))
149
150 extern struct ssh_cipher ssh_3des;
151 extern struct ssh_cipher ssh_3des_ssh2;
152 extern struct ssh_cipher ssh_des;
153 extern struct ssh_cipher ssh_blowfish_ssh1;
154 extern struct ssh_cipher ssh_blowfish_ssh2;
155
156 /*
157  * Ciphers for SSH2. We miss out single-DES because it isn't
158  * supported; also 3DES and Blowfish are both done differently from
159  * SSH1. (3DES uses outer chaining; Blowfish has the opposite
160  * endianness and different-sized keys.)
161  *
162  * The first entry in this array is set up to be whatever the user
163  * asks for as a cipher. Thereafter there is a fixed preference
164  * order of fallback ciphers.
165  */
166 struct ssh_cipher *ciphers[] = { NULL, &ssh_blowfish_ssh2, &ssh_3des_ssh2 };
167
168 extern struct ssh_kex ssh_diffiehellman;
169 struct ssh_kex *kex_algs[] = { &ssh_diffiehellman };
170
171 extern struct ssh_hostkey ssh_dss;
172 struct ssh_hostkey *hostkey_algs[] = { &ssh_dss };
173
174 extern struct ssh_mac ssh_sha1;
175
176 static SHA_State exhash;
177
178 static void nullmac_key(unsigned char *key) { }
179 static void nullmac_generate(unsigned char *blk, int len, unsigned long seq) { }
180 static int nullmac_verify(unsigned char *blk, int len, unsigned long seq) { return 1; }
181 struct ssh_mac ssh_mac_none = {
182     nullmac_key, nullmac_key, nullmac_generate, nullmac_verify, "none", 0
183 };
184 struct ssh_mac *macs[] = { &ssh_sha1, &ssh_mac_none };
185
186 struct ssh_compress ssh_comp_none = {
187     "none"
188 };
189 struct ssh_compress *compressions[] = { &ssh_comp_none };
190
191 static SOCKET s = INVALID_SOCKET;
192
193 static unsigned char session_key[32];
194 static struct ssh_cipher *cipher = NULL;
195 static struct ssh_cipher *cscipher = NULL;
196 static struct ssh_cipher *sccipher = NULL;
197 static struct ssh_mac *csmac = NULL;
198 static struct ssh_mac *scmac = NULL;
199 static struct ssh_compress *cscomp = NULL;
200 static struct ssh_compress *sccomp = NULL;
201 static struct ssh_kex *kex = NULL;
202 static struct ssh_hostkey *hostkey = NULL;
203 int (*ssh_get_password)(const char *prompt, char *str, int maxlen) = NULL;
204
205 static char *savedhost;
206 static int ssh_send_ok;
207
208 /*
209  * 2-3-4 tree storing channels.
210  */
211 struct ssh_channel {
212     unsigned remoteid, localid;
213     int type;
214     int closes;
215     union {
216         struct ssh_agent_channel {
217             unsigned char *message;
218             unsigned char msglen[4];
219             int lensofar, totallen;
220         } a;
221         struct ssh2_data_channel {
222             unsigned char *outbuffer;
223             unsigned outbuflen, outbufsize;
224             unsigned remwindow, remmaxpkt;
225         } v2;
226     } u;
227 };
228 static tree234 *ssh_channels;           /* indexed by local id */
229 static int ssh_channelcmp(void *av, void *bv) {
230     struct ssh_channel *a = (struct ssh_channel *)av;
231     struct ssh_channel *b = (struct ssh_channel *)bv;
232     if (a->localid < b->localid) return -1;
233     if (a->localid > b->localid) return +1;
234     return 0;
235 }
236 static int ssh_channelfind(void *av, void *bv) {
237     unsigned *a = (unsigned *)av;
238     struct ssh_channel *b = (struct ssh_channel *)bv;
239     if (*a < b->localid) return -1;
240     if (*a > b->localid) return +1;
241     return 0;
242 }
243
244 static struct ssh_channel *mainchan;   /* primary session channel */
245
246 static enum {
247     SSH_STATE_BEFORE_SIZE,
248     SSH_STATE_INTERMED,
249     SSH_STATE_SESSION,
250     SSH_STATE_CLOSED
251 } ssh_state = SSH_STATE_BEFORE_SIZE;
252
253 static int size_needed = FALSE;
254
255 static void s_write (char *buf, int len) {
256     while (len > 0) {
257         int i = send (s, buf, len, 0);
258         noise_ultralight(i);
259         if (i <= 0) {
260             bombout(("Lost connection while sending"));
261             return;
262         }
263         if (i > 0)
264             len -= i, buf += i;
265     }
266 }
267
268 static int s_read (char *buf, int len) {
269     int ret = 0;
270     while (len > 0) {
271         int i = recv (s, buf, len, 0);
272         noise_ultralight(i);
273         if (i > 0)
274             len -= i, buf += i, ret += i;
275         else
276             return i;
277     }
278     return ret;
279 }
280
281 static void c_write (char *buf, int len) {
282     if ((flags & FLAG_STDERR)) {
283         int i;
284         for (i = 0; i < len; i++)
285             if (buf[i] != '\r')
286                 fputc(buf[i], stderr);
287         return;
288     }
289     while (len--) 
290         c_write1(*buf++);
291 }
292
293 static void c_writedata (char *buf, int len) {
294     while (len--)
295         c_write1(*buf++);
296 }
297
298 struct Packet {
299     long length;
300     int type;
301     unsigned char *data;
302     unsigned char *body;
303     long savedpos;
304     long maxlen;
305 };
306
307 static struct Packet pktin = { 0, 0, NULL, NULL, 0 };
308 static struct Packet pktout = { 0, 0, NULL, NULL, 0 };
309
310 static int ssh_version;
311 static void (*ssh_protocol)(unsigned char *in, int inlen, int ispkt);
312 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt);
313 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt);
314 static void ssh_size(void);
315
316 static int (*s_rdpkt)(unsigned char **data, int *datalen);
317
318 /*
319  * Collect incoming data in the incoming packet buffer.
320  * Decipher and verify the packet when it is completely read.
321  * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
322  * Update the *data and *datalen variables.
323  * Return the additional nr of bytes needed, or 0 when
324  * a complete packet is available.
325  */
326 static int ssh1_rdpkt(unsigned char **data, int *datalen)
327 {
328     static long len, pad, biglen, to_read;
329     static unsigned long realcrc, gotcrc;
330     static unsigned char *p;
331     static int i;
332
333     crBegin;
334
335 next_packet:
336
337     pktin.type = 0;
338     pktin.length = 0;
339
340     for (i = len = 0; i < 4; i++) {
341         while ((*datalen) == 0)
342             crReturn(4-i);
343         len = (len << 8) + **data;
344         (*data)++, (*datalen)--;
345     }
346
347 #ifdef FWHACK
348     if (len == 0x52656d6f) {       /* "Remo"te server has closed ... */
349         len = 0x300;               /* big enough to carry to end */
350     }
351 #endif
352
353     pad = 8 - (len % 8);
354     biglen = len + pad;
355     pktin.length = len - 5;
356
357     if (pktin.maxlen < biglen) {
358         pktin.maxlen = biglen;
359         pktin.data = (pktin.data == NULL ? malloc(biglen+APIEXTRA) :
360                       realloc(pktin.data, biglen+APIEXTRA));
361         if (!pktin.data)
362             fatalbox("Out of memory");
363     }
364
365     to_read = biglen;
366     p = pktin.data;
367     while (to_read > 0) {
368         static int chunk;
369         chunk = to_read;
370         while ((*datalen) == 0)
371             crReturn(to_read);
372         if (chunk > (*datalen))
373             chunk = (*datalen);
374         memcpy(p, *data, chunk);
375         *data += chunk;
376         *datalen -= chunk;
377         p += chunk;
378         to_read -= chunk;
379     }
380
381     if (cipher)
382         cipher->decrypt(pktin.data, biglen);
383
384     pktin.type = pktin.data[pad];
385     pktin.body = pktin.data + pad + 1;
386
387     realcrc = crc32(pktin.data, biglen-4);
388     gotcrc = GET_32BIT(pktin.data+biglen-4);
389     if (gotcrc != realcrc) {
390         bombout(("Incorrect CRC received on packet"));
391         crReturn(0);
392     }
393
394     if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
395         pktin.type == SSH1_SMSG_STDERR_DATA ||
396         pktin.type == SSH1_MSG_DEBUG ||
397         pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
398         pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
399         long strlen = GET_32BIT(pktin.body);
400         if (strlen + 4 != pktin.length) {
401             bombout(("Received data packet with bogus string length"));
402             crReturn(0);
403         }
404     }
405
406     if (pktin.type == SSH1_MSG_DEBUG) {
407         /* log debug message */
408         char buf[80];
409         int strlen = GET_32BIT(pktin.body);
410         strcpy(buf, "Remote: ");
411         if (strlen > 70) strlen = 70;
412         memcpy(buf+8, pktin.body+4, strlen);
413         buf[8+strlen] = '\0';
414         logevent(buf);
415         goto next_packet;
416     } else if (pktin.type == SSH1_MSG_IGNORE) {
417         /* do nothing */
418         goto next_packet;
419     }
420
421     crFinish(0);
422 }
423
424 static int ssh2_rdpkt(unsigned char **data, int *datalen)
425 {
426     static long len, pad, payload, packetlen, maclen;
427     static int i;
428     static int cipherblk;
429     static unsigned long incoming_sequence = 0;
430
431     crBegin;
432
433 next_packet:
434
435     pktin.type = 0;
436     pktin.length = 0;
437
438     if (cipher)
439         cipherblk = cipher->blksize;
440     else
441         cipherblk = 8;
442     if (cipherblk < 8)
443         cipherblk = 8;
444
445     if (pktin.maxlen < cipherblk) {
446         pktin.maxlen = cipherblk;
447         pktin.data = (pktin.data == NULL ? malloc(cipherblk+APIEXTRA) :
448                       realloc(pktin.data, cipherblk+APIEXTRA));
449         if (!pktin.data)
450             fatalbox("Out of memory");
451     }
452
453     /*
454      * Acquire and decrypt the first block of the packet. This will
455      * contain the length and padding details.
456      */
457      for (i = len = 0; i < cipherblk; i++) {
458         while ((*datalen) == 0)
459             crReturn(cipherblk-i);
460         pktin.data[i] = *(*data)++;
461         (*datalen)--;
462     }
463 #ifdef FWHACK
464     if (!memcmp(pktin.data, "Remo", 4)) {/* "Remo"te server has closed ... */
465         /* FIXME */
466     }
467 #endif
468     if (sccipher)
469         sccipher->decrypt(pktin.data, cipherblk);
470
471     /*
472      * Now get the length and padding figures.
473      */
474     len = GET_32BIT(pktin.data);
475     pad = pktin.data[4];
476
477     /*
478      * This enables us to deduce the payload length.
479      */
480     payload = len - pad - 1;
481
482     pktin.length = payload + 5;
483
484     /*
485      * So now we can work out the total packet length.
486      */
487     packetlen = len + 4;
488     maclen = scmac ? scmac->len : 0;
489
490     /*
491      * Adjust memory allocation if packet is too big.
492      */
493     if (pktin.maxlen < packetlen+maclen) {
494         pktin.maxlen = packetlen+maclen;
495         pktin.data = (pktin.data == NULL ? malloc(pktin.maxlen+APIEXTRA) :
496                       realloc(pktin.data, pktin.maxlen+APIEXTRA));
497         if (!pktin.data)
498             fatalbox("Out of memory");
499     }
500
501     /*
502      * Read and decrypt the remainder of the packet.
503      */
504     for (i = cipherblk; i < packetlen + maclen; i++) {
505         while ((*datalen) == 0)
506             crReturn(packetlen + maclen - i);
507         pktin.data[i] = *(*data)++;
508         (*datalen)--;
509     }
510     /* Decrypt everything _except_ the MAC. */
511     if (sccipher)
512         sccipher->decrypt(pktin.data + cipherblk, packetlen - cipherblk);
513
514 #if 0
515     debug(("Got packet len=%d pad=%d\r\n", len, pad));
516     for (i = 0; i < packetlen; i++)
517         debug(("  %02x", (unsigned char)pktin.data[i]));
518     debug(("\r\n"));
519 #endif
520
521     /*
522      * Check the MAC.
523      */
524     if (scmac && !scmac->verify(pktin.data, len+4, incoming_sequence)) {
525         bombout(("Incorrect MAC received on packet"));
526         crReturn(0);
527     }
528     incoming_sequence++;               /* whether or not we MACed */
529
530     pktin.savedpos = 6;
531     pktin.type = pktin.data[5];
532
533     if (pktin.type == SSH2_MSG_IGNORE || pktin.type == SSH2_MSG_DEBUG)
534         goto next_packet;              /* FIXME: print DEBUG message */
535
536     crFinish(0);
537 }
538
539 static void ssh_gotdata(unsigned char *data, int datalen)
540 {
541     while (datalen > 0) {
542         if ( s_rdpkt(&data, &datalen) == 0 ) {
543             ssh_protocol(NULL, 0, 1);
544             if (ssh_state == SSH_STATE_CLOSED) {
545                 return;
546             }
547         }
548     }
549 }
550
551
552 static void s_wrpkt_start(int type, int len) {
553     int pad, biglen;
554
555     len += 5;                          /* type and CRC */
556     pad = 8 - (len%8);
557     biglen = len + pad;
558
559     pktout.length = len-5;
560     if (pktout.maxlen < biglen) {
561         pktout.maxlen = biglen;
562 #ifdef MSCRYPTOAPI
563         /* Allocate enough buffer space for extra block
564          * for MS CryptEncrypt() */
565         pktout.data = (pktout.data == NULL ? malloc(biglen+12) :
566                        realloc(pktout.data, biglen+12));
567 #else
568         pktout.data = (pktout.data == NULL ? malloc(biglen+4) :
569                        realloc(pktout.data, biglen+4));
570 #endif
571         if (!pktout.data)
572             fatalbox("Out of memory");
573     }
574
575     pktout.type = type;
576     pktout.body = pktout.data+4+pad+1;
577 }
578
579 static void s_wrpkt(void) {
580     int pad, len, biglen, i;
581     unsigned long crc;
582
583     len = pktout.length + 5;           /* type and CRC */
584     pad = 8 - (len%8);
585     biglen = len + pad;
586
587     pktout.body[-1] = pktout.type;
588     for (i=0; i<pad; i++)
589         pktout.data[i+4] = random_byte();
590     crc = crc32(pktout.data+4, biglen-4);
591     PUT_32BIT(pktout.data+biglen, crc);
592     PUT_32BIT(pktout.data, len);
593
594     if (cipher)
595         cipher->encrypt(pktout.data+4, biglen);
596
597     s_write(pktout.data, biglen+4);
598 }
599
600 /*
601  * Construct a packet with the specified contents and
602  * send it to the server.
603  */
604 static void send_packet(int pkttype, ...)
605 {
606     va_list args;
607     unsigned char *p, *argp, argchar;
608     unsigned long argint;
609     int pktlen, argtype, arglen;
610     Bignum bn;
611
612     pktlen = 0;
613     va_start(args, pkttype);
614     while ((argtype = va_arg(args, int)) != PKT_END) {
615         switch (argtype) {
616           case PKT_INT:
617             (void) va_arg(args, int);
618             pktlen += 4;
619             break;
620           case PKT_CHAR:
621             (void) va_arg(args, char);
622             pktlen++;
623             break;
624           case PKT_DATA:
625             (void) va_arg(args, unsigned char *);
626             arglen = va_arg(args, int);
627             pktlen += arglen;
628             break;
629           case PKT_STR:
630             argp = va_arg(args, unsigned char *);
631             arglen = strlen(argp);
632             pktlen += 4 + arglen;
633             break;
634           case PKT_BIGNUM:
635             bn = va_arg(args, Bignum);
636             pktlen += ssh1_bignum_length(bn);
637             break;
638           default:
639             assert(0);
640         }
641     }
642     va_end(args);
643
644     s_wrpkt_start(pkttype, pktlen);
645     p = pktout.body;
646
647     va_start(args, pkttype);
648     while ((argtype = va_arg(args, int)) != PKT_END) {
649         switch (argtype) {
650           case PKT_INT:
651             argint = va_arg(args, int);
652             PUT_32BIT(p, argint);
653             p += 4;
654             break;
655           case PKT_CHAR:
656             argchar = va_arg(args, unsigned char);
657             *p = argchar;
658             p++;
659             break;
660           case PKT_DATA:
661             argp = va_arg(args, unsigned char *);
662             arglen = va_arg(args, int);
663             memcpy(p, argp, arglen);
664             p += arglen;
665             break;
666           case PKT_STR:
667             argp = va_arg(args, unsigned char *);
668             arglen = strlen(argp);
669             PUT_32BIT(p, arglen);
670             memcpy(p + 4, argp, arglen);
671             p += 4 + arglen;
672             break;
673           case PKT_BIGNUM:
674             bn = va_arg(args, Bignum);
675             p += ssh1_write_bignum(p, bn);
676             break;
677         }
678     }
679     va_end(args);
680
681     s_wrpkt();
682 }
683
684
685 /*
686  * Connect to specified host and port.
687  * Returns an error message, or NULL on success.
688  * Also places the canonical host name into `realhost'.
689  */
690 static char *connect_to_host(char *host, int port, char **realhost)
691 {
692     SOCKADDR_IN addr;
693     struct hostent *h;
694     unsigned long a;
695 #ifdef FWHACK
696     char *FWhost;
697     int FWport;
698 #endif
699
700     savedhost = malloc(1+strlen(host));
701     if (!savedhost)
702         fatalbox("Out of memory");
703     strcpy(savedhost, host);
704
705     if (port < 0)
706         port = 22;                     /* default ssh port */
707
708 #ifdef FWHACK
709     FWhost = host;
710     FWport = port;
711     host = FWSTR;
712     port = 23;
713 #endif
714
715     /*
716      * Try to find host.
717      */
718     if ( (a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
719         if ( (h = gethostbyname(host)) == NULL)
720             switch (WSAGetLastError()) {
721               case WSAENETDOWN: return "Network is down";
722               case WSAHOST_NOT_FOUND: case WSANO_DATA:
723                 return "Host does not exist";
724               case WSATRY_AGAIN: return "Host not found";
725               default: return "gethostbyname: unknown error";
726             }
727         memcpy (&a, h->h_addr, sizeof(a));
728         *realhost = h->h_name;
729     } else
730         *realhost = host;
731 #ifdef FWHACK
732     *realhost = FWhost;
733 #endif
734     a = ntohl(a);
735
736     /*
737      * Open socket.
738      */
739     s = socket(AF_INET, SOCK_STREAM, 0);
740     if (s == INVALID_SOCKET)
741         switch (WSAGetLastError()) {
742           case WSAENETDOWN: return "Network is down";
743           case WSAEAFNOSUPPORT: return "TCP/IP support not present";
744           default: return "socket(): unknown error";
745         }
746
747     /*
748      * Bind to local address.
749      */
750     addr.sin_family = AF_INET;
751     addr.sin_addr.s_addr = htonl(INADDR_ANY);
752     addr.sin_port = htons(0);
753     if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
754         switch (WSAGetLastError()) {
755           case WSAENETDOWN: return "Network is down";
756           default: return "bind(): unknown error";
757         }
758
759     /*
760      * Connect to remote address.
761      */
762     addr.sin_addr.s_addr = htonl(a);
763     addr.sin_port = htons((short)port);
764     if (connect (s, (struct sockaddr *)&addr, sizeof(addr)) == SOCKET_ERROR)
765         switch (WSAGetLastError()) {
766           case WSAENETDOWN: return "Network is down";
767           case WSAECONNREFUSED: return "Connection refused";
768           case WSAENETUNREACH: return "Network is unreachable";
769           case WSAEHOSTUNREACH: return "No route to host";
770           default: return "connect(): unknown error";
771         }
772
773 #ifdef FWHACK
774     send(s, "connect ", 8, 0);
775     send(s, FWhost, strlen(FWhost), 0);
776     {
777         char buf[20];
778         sprintf(buf, " %d\n", FWport);
779         send (s, buf, strlen(buf), 0);
780     }
781 #endif
782
783     return NULL;
784 }
785
786 static int ssh_versioncmp(char *a, char *b) {
787     char *ae, *be;
788     unsigned long av, bv;
789
790     av = strtoul(a, &ae, 10);
791     bv = strtoul(b, &be, 10);
792     if (av != bv) return (av < bv ? -1 : +1);
793     if (*ae == '.') ae++;
794     if (*be == '.') be++;
795     av = strtoul(ae, &ae, 10);
796     bv = strtoul(be, &be, 10);
797     if (av != bv) return (av < bv ? -1 : +1);
798     return 0;
799 }
800
801
802 /*
803  * Utility routine for putting an SSH-protocol `string' into a SHA
804  * state.
805  */
806 #include <stdio.h>
807 void sha_string(SHA_State *s, void *str, int len) {
808     unsigned char lenblk[4];
809     PUT_32BIT(lenblk, len);
810     SHA_Bytes(s, lenblk, 4);
811     SHA_Bytes(s, str, len);
812 }
813
814 /*
815  * SSH2 packet construction functions.
816  */
817 void ssh2_pkt_adddata(void *data, int len) {
818     pktout.length += len;
819     if (pktout.maxlen < pktout.length) {
820         pktout.maxlen = pktout.length + 256;
821         pktout.data = (pktout.data == NULL ? malloc(pktout.maxlen+APIEXTRA) :
822                        realloc(pktout.data, pktout.maxlen+APIEXTRA));
823         if (!pktout.data)
824             fatalbox("Out of memory");
825     }
826     memcpy(pktout.data+pktout.length-len, data, len);
827 }
828 void ssh2_pkt_addbyte(unsigned char byte) {
829     ssh2_pkt_adddata(&byte, 1);
830 }
831 void ssh2_pkt_init(int pkt_type) {
832     pktout.length = 5;
833     ssh2_pkt_addbyte((unsigned char)pkt_type);
834 }
835 void ssh2_pkt_addbool(unsigned char value) {
836     ssh2_pkt_adddata(&value, 1);
837 }
838 void ssh2_pkt_adduint32(unsigned long value) {
839     unsigned char x[4];
840     PUT_32BIT(x, value);
841     ssh2_pkt_adddata(x, 4);
842 }
843 void ssh2_pkt_addstring_start(void) {
844     ssh2_pkt_adduint32(0);
845     pktout.savedpos = pktout.length;
846 }
847 void ssh2_pkt_addstring_str(char *data) {
848     ssh2_pkt_adddata(data, strlen(data));
849     PUT_32BIT(pktout.data + pktout.savedpos - 4,
850               pktout.length - pktout.savedpos);
851 }
852 void ssh2_pkt_addstring_data(char *data, int len) {
853     ssh2_pkt_adddata(data, len);
854     PUT_32BIT(pktout.data + pktout.savedpos - 4,
855               pktout.length - pktout.savedpos);
856 }
857 void ssh2_pkt_addstring(char *data) {
858     ssh2_pkt_addstring_start();
859     ssh2_pkt_addstring_str(data);
860 }
861 char *ssh2_mpint_fmt(Bignum b, int *len) {
862     unsigned char *p;
863     int i, n = b[0];
864     p = malloc(n * 2 + 1);
865     if (!p)
866         fatalbox("out of memory");
867     p[0] = 0;
868     for (i = 0; i < n; i++) {
869         p[i*2+1] = (b[n-i] >> 8) & 0xFF;
870         p[i*2+2] = (b[n-i]     ) & 0xFF;
871     }
872     i = 0;
873     while (p[i] == 0 && (p[i+1] & 0x80) == 0)
874         i++;
875     memmove(p, p+i, n*2+1-i);
876     *len = n*2+1-i;
877     return p;
878 }
879 void ssh2_pkt_addmp(Bignum b) {
880     unsigned char *p;
881     int len;
882     p = ssh2_mpint_fmt(b, &len);
883     ssh2_pkt_addstring_start();
884     ssh2_pkt_addstring_data(p, len);
885     free(p);
886 }
887 void ssh2_pkt_send(void) {
888     int cipherblk, maclen, padding, i;
889     static unsigned long outgoing_sequence = 0;
890
891     /*
892      * Add padding. At least four bytes, and must also bring total
893      * length (minus MAC) up to a multiple of the block size.
894      */
895     cipherblk = cipher ? cipher->blksize : 8;   /* block size */
896     cipherblk = cipherblk < 8 ? 8 : cipherblk;   /* or 8 if blksize < 8 */
897     padding = 4;
898     padding += (cipherblk - (pktout.length + padding) % cipherblk) % cipherblk;
899     pktout.data[4] = padding;
900     for (i = 0; i < padding; i++)
901         pktout.data[pktout.length + i] = random_byte();
902     PUT_32BIT(pktout.data, pktout.length + padding - 4);
903     if (csmac)
904         csmac->generate(pktout.data, pktout.length + padding,
905                         outgoing_sequence);
906     outgoing_sequence++;               /* whether or not we MACed */
907
908 #if 0
909     debug(("Sending packet len=%d\r\n", pktout.length+padding));
910     for (i = 0; i < pktout.length+padding; i++)
911         debug(("  %02x", (unsigned char)pktout.data[i]));
912     debug(("\r\n"));
913 #endif
914
915     if (cscipher)
916         cscipher->encrypt(pktout.data, pktout.length + padding);
917     maclen = csmac ? csmac->len : 0;
918
919     s_write(pktout.data, pktout.length + padding + maclen);
920 }
921
922 #if 0
923 void bndebug(char *string, Bignum b) {
924     unsigned char *p;
925     int i, len;
926     p = ssh2_mpint_fmt(b, &len);
927     debug(("%s", string));
928     for (i = 0; i < len; i++)
929         debug((" %02x", p[i]));
930     debug(("\r\n"));
931     free(p);
932 }
933 #endif
934
935 void sha_mpint(SHA_State *s, Bignum b) {
936     unsigned char *p;
937     int len;
938     p = ssh2_mpint_fmt(b, &len);
939     sha_string(s, p, len);
940     free(p);
941 }
942
943 /*
944  * SSH2 packet decode functions.
945  */
946 unsigned long ssh2_pkt_getuint32(void) {
947     unsigned long value;
948     if (pktin.length - pktin.savedpos < 4)
949         return 0;                      /* arrgh, no way to decline (FIXME?) */
950     value = GET_32BIT(pktin.data+pktin.savedpos);
951     pktin.savedpos += 4;
952     return value;
953 }
954 void ssh2_pkt_getstring(char **p, int *length) {
955     *p = NULL;
956     if (pktin.length - pktin.savedpos < 4)
957         return;
958     *length = GET_32BIT(pktin.data+pktin.savedpos);
959     pktin.savedpos += 4;
960     if (pktin.length - pktin.savedpos < *length)
961         return;
962     *p = pktin.data+pktin.savedpos;
963     pktin.savedpos += *length;
964 }
965 Bignum ssh2_pkt_getmp(void) {
966     char *p;
967     int i, j, length;
968     Bignum b;
969
970     ssh2_pkt_getstring(&p, &length);
971     if (!p)
972         return NULL;
973     if (p[0] & 0x80) {
974         bombout(("internal error: Can't handle negative mpints"));
975         return NULL;
976     }
977     b = newbn((length+1)/2);
978     for (i = 0; i < length; i++) {
979         j = length - 1 - i;
980         if (j & 1)
981             b[j/2+1] |= ((unsigned char)p[i]) << 8;
982         else
983             b[j/2+1] |= ((unsigned char)p[i]);
984     }
985     return b;
986 }
987
988 static int do_ssh_init(void) {
989     char c, *vsp;
990     char version[10];
991     char vstring[80];
992     char vlog[sizeof(vstring)+20];
993     int i;
994
995 #ifdef FWHACK
996     i = 0;
997     while (s_read(&c, 1) == 1) {
998         if (c == 'S' && i < 2) i++;
999         else if (c == 'S' && i == 2) i = 2;
1000         else if (c == 'H' && i == 2) break;
1001         else i = 0;
1002     }
1003 #else
1004     if (s_read(&c,1) != 1 || c != 'S') return 0;
1005     if (s_read(&c,1) != 1 || c != 'S') return 0;
1006     if (s_read(&c,1) != 1 || c != 'H') return 0;
1007 #endif
1008     strcpy(vstring, "SSH-");
1009     vsp = vstring+4;
1010     if (s_read(&c,1) != 1 || c != '-') return 0;
1011     i = 0;
1012     while (1) {
1013         if (s_read(&c,1) != 1)
1014             return 0;
1015         if (vsp < vstring+sizeof(vstring)-1)
1016             *vsp++ = c;
1017         if (i >= 0) {
1018             if (c == '-') {
1019                 version[i] = '\0';
1020                 i = -1;
1021             } else if (i < sizeof(version)-1)
1022                 version[i++] = c;
1023         }
1024         else if (c == '\n')
1025             break;
1026     }
1027
1028     *vsp = 0;
1029     sprintf(vlog, "Server version: %s", vstring);
1030     vlog[strcspn(vlog, "\r\n")] = '\0';
1031     logevent(vlog);
1032
1033     /*
1034      * Server version "1.99" means we can choose whether we use v1
1035      * or v2 protocol. Choice is based on cfg.sshprot.
1036      */
1037     if (ssh_versioncmp(version, cfg.sshprot == 1 ? "2.0" : "1.99") >= 0) {
1038         /*
1039          * This is a v2 server. Begin v2 protocol.
1040          */
1041         char *verstring = "SSH-2.0-PuTTY";
1042         SHA_Init(&exhash);
1043         /*
1044          * Hash our version string and their version string.
1045          */
1046         sha_string(&exhash, verstring, strlen(verstring));
1047         sha_string(&exhash, vstring, strcspn(vstring, "\r\n"));
1048         sprintf(vstring, "%s\n", verstring);
1049         sprintf(vlog, "We claim version: %s", verstring);
1050         logevent(vlog);
1051         logevent("Using SSH protocol version 2");
1052         s_write(vstring, strlen(vstring));
1053         ssh_protocol = ssh2_protocol;
1054         ssh_version = 2;
1055         s_rdpkt = ssh2_rdpkt;
1056     } else {
1057         /*
1058          * This is a v1 server. Begin v1 protocol.
1059          */
1060         sprintf(vstring, "SSH-%s-PuTTY\n",
1061                 (ssh_versioncmp(version, "1.5") <= 0 ? version : "1.5"));
1062         sprintf(vlog, "We claim version: %s", vstring);
1063         vlog[strcspn(vlog, "\r\n")] = '\0';
1064         logevent(vlog);
1065         logevent("Using SSH protocol version 1");
1066         s_write(vstring, strlen(vstring));
1067         ssh_protocol = ssh1_protocol;
1068         ssh_version = 1;
1069         s_rdpkt = ssh1_rdpkt;
1070     }
1071     ssh_send_ok = 0;
1072     return 1;
1073 }
1074
1075 /*
1076  * Handle the key exchange and user authentication phases.
1077  */
1078 static int do_ssh1_login(unsigned char *in, int inlen, int ispkt)
1079 {
1080     int i, j, len;
1081     unsigned char *rsabuf, *keystr1, *keystr2;
1082     unsigned char cookie[8];
1083     struct RSAKey servkey, hostkey;
1084     struct MD5Context md5c;
1085     static unsigned long supported_ciphers_mask, supported_auths_mask;
1086     static int tried_publickey;
1087     static unsigned char session_id[16];
1088     int cipher_type;
1089
1090     crBegin;
1091
1092     if (!ispkt) crWaitUntil(ispkt);
1093
1094     if (pktin.type != SSH1_SMSG_PUBLIC_KEY) {
1095         bombout(("Public key packet not received"));
1096         crReturn(0);
1097     }
1098
1099     logevent("Received public keys");
1100
1101     memcpy(cookie, pktin.body, 8);
1102
1103     i = makekey(pktin.body+8, &servkey, &keystr1, 0);
1104     j = makekey(pktin.body+8+i, &hostkey, &keystr2, 0);
1105
1106     /*
1107      * Log the host key fingerprint.
1108      */
1109     {
1110         char logmsg[80];
1111         logevent("Host key fingerprint is:");
1112         strcpy(logmsg, "      ");
1113         hostkey.comment = NULL;
1114         rsa_fingerprint(logmsg+strlen(logmsg), sizeof(logmsg)-strlen(logmsg),
1115                         &hostkey);
1116         logevent(logmsg);
1117     }
1118
1119     supported_ciphers_mask = GET_32BIT(pktin.body+12+i+j);
1120     supported_auths_mask = GET_32BIT(pktin.body+16+i+j);
1121
1122     MD5Init(&md5c);
1123     MD5Update(&md5c, keystr2, hostkey.bytes);
1124     MD5Update(&md5c, keystr1, servkey.bytes);
1125     MD5Update(&md5c, pktin.body, 8);
1126     MD5Final(session_id, &md5c);
1127
1128     for (i=0; i<32; i++)
1129         session_key[i] = random_byte();
1130
1131     len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
1132
1133     rsabuf = malloc(len);
1134     if (!rsabuf)
1135         fatalbox("Out of memory");
1136
1137     /*
1138      * Verify the host key.
1139      */
1140     {
1141         /*
1142          * First format the key into a string.
1143          */
1144         int len = rsastr_len(&hostkey);
1145         char *keystr = malloc(len);
1146         if (!keystr)
1147             fatalbox("Out of memory");
1148         rsastr_fmt(keystr, &hostkey);
1149         verify_ssh_host_key(savedhost, keystr);
1150         free(keystr);
1151     }
1152
1153     for (i=0; i<32; i++) {
1154         rsabuf[i] = session_key[i];
1155         if (i < 16)
1156             rsabuf[i] ^= session_id[i];
1157     }
1158
1159     if (hostkey.bytes > servkey.bytes) {
1160         rsaencrypt(rsabuf, 32, &servkey);
1161         rsaencrypt(rsabuf, servkey.bytes, &hostkey);
1162     } else {
1163         rsaencrypt(rsabuf, 32, &hostkey);
1164         rsaencrypt(rsabuf, hostkey.bytes, &servkey);
1165     }
1166
1167     logevent("Encrypted session key");
1168
1169     cipher_type = cfg.cipher == CIPHER_BLOWFISH ? SSH_CIPHER_BLOWFISH :
1170                   cfg.cipher == CIPHER_DES ? SSH_CIPHER_DES : 
1171                   SSH_CIPHER_3DES;
1172     if ((supported_ciphers_mask & (1 << cipher_type)) == 0) {
1173         c_write("Selected cipher not supported, falling back to 3DES\r\n", 53);
1174         cipher_type = SSH_CIPHER_3DES;
1175     }
1176     switch (cipher_type) {
1177       case SSH_CIPHER_3DES: logevent("Using 3DES encryption"); break;
1178       case SSH_CIPHER_DES: logevent("Using single-DES encryption"); break;
1179       case SSH_CIPHER_BLOWFISH: logevent("Using Blowfish encryption"); break;
1180     }
1181
1182     send_packet(SSH1_CMSG_SESSION_KEY,
1183                 PKT_CHAR, cipher_type,
1184                 PKT_DATA, cookie, 8,
1185                 PKT_CHAR, (len*8) >> 8, PKT_CHAR, (len*8) & 0xFF,
1186                 PKT_DATA, rsabuf, len,
1187                 PKT_INT, 0,
1188                 PKT_END);
1189
1190     logevent("Trying to enable encryption...");
1191
1192     free(rsabuf);
1193
1194     cipher = cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
1195              cipher_type == SSH_CIPHER_DES ? &ssh_des :
1196              &ssh_3des;
1197     cipher->sesskey(session_key);
1198
1199     crWaitUntil(ispkt);
1200
1201     if (pktin.type != SSH1_SMSG_SUCCESS) {
1202         bombout(("Encryption not successfully enabled"));
1203         crReturn(0);
1204     }
1205
1206     logevent("Successfully started encryption");
1207
1208     fflush(stdout);
1209     {
1210         static char username[100];
1211         static int pos = 0;
1212         static char c;
1213         if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
1214             c_write("login as: ", 10);
1215             ssh_send_ok = 1;
1216             while (pos >= 0) {
1217                 crWaitUntil(!ispkt);
1218                 while (inlen--) switch (c = *in++) {
1219                   case 10: case 13:
1220                     username[pos] = 0;
1221                     pos = -1;
1222                     break;
1223                   case 8: case 127:
1224                     if (pos > 0) {
1225                         c_write("\b \b", 3);
1226                         pos--;
1227                     }
1228                     break;
1229                   case 21: case 27:
1230                     while (pos > 0) {
1231                         c_write("\b \b", 3);
1232                         pos--;
1233                     }
1234                     break;
1235                   case 3: case 4:
1236                     random_save_seed();
1237                     exit(0);
1238                     break;
1239                   default:
1240                     if (((c >= ' ' && c <= '~') ||
1241                          ((unsigned char)c >= 160)) && pos < 40) {
1242                         username[pos++] = c;
1243                         c_write(&c, 1);
1244                     }
1245                     break;
1246                 }
1247             }
1248             c_write("\r\n", 2);
1249             username[strcspn(username, "\n\r")] = '\0';
1250         } else {
1251             char stuff[200];
1252             strncpy(username, cfg.username, 99);
1253             username[99] = '\0';
1254             if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
1255                 sprintf(stuff, "Sent username \"%s\".\r\n", username);
1256                 c_write(stuff, strlen(stuff));
1257             }
1258         }
1259
1260         send_packet(SSH1_CMSG_USER, PKT_STR, username, PKT_END);
1261         {
1262             char userlog[20+sizeof(username)];
1263             sprintf(userlog, "Sent username \"%s\"", username);
1264             logevent(userlog);
1265         }
1266     }
1267
1268     crWaitUntil(ispkt);
1269
1270     tried_publickey = 0;
1271
1272     while (pktin.type == SSH1_SMSG_FAILURE) {
1273         static char password[100];
1274         static char prompt[200];
1275         static int pos;
1276         static char c;
1277         static int pwpkt_type;
1278         /*
1279          * Show password prompt, having first obtained it via a TIS
1280          * or CryptoCard exchange if we're doing TIS or CryptoCard
1281          * authentication.
1282          */
1283         pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
1284         if (agent_exists()) {
1285             /*
1286              * Attempt RSA authentication using Pageant.
1287              */
1288             static unsigned char request[5], *response, *p;
1289             static int responselen;
1290             static int i, nkeys;
1291             static int authed = FALSE;
1292             void *r;
1293
1294             logevent("Pageant is running. Requesting keys.");
1295
1296             /* Request the keys held by the agent. */
1297             PUT_32BIT(request, 1);
1298             request[4] = SSH_AGENTC_REQUEST_RSA_IDENTITIES;
1299             agent_query(request, 5, &r, &responselen);
1300             response = (unsigned char *)r;
1301             if (response) {
1302                 p = response + 5;
1303                 nkeys = GET_32BIT(p); p += 4;
1304                 { char buf[64]; sprintf(buf, "Pageant has %d keys", nkeys);
1305                     logevent(buf); }
1306                 for (i = 0; i < nkeys; i++) {
1307                     static struct RSAKey key;
1308                     static Bignum challenge;
1309                     static char *commentp;
1310                     static int commentlen;
1311
1312                     { char buf[64]; sprintf(buf, "Trying Pageant key #%d", i);
1313                         logevent(buf); }
1314                     p += 4;
1315                     p += ssh1_read_bignum(p, &key.exponent);
1316                     p += ssh1_read_bignum(p, &key.modulus);
1317                     commentlen = GET_32BIT(p); p += 4;
1318                     commentp = p; p += commentlen;
1319                     send_packet(SSH1_CMSG_AUTH_RSA,
1320                                 PKT_BIGNUM, key.modulus, PKT_END);
1321                     crWaitUntil(ispkt);
1322                     if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1323                         logevent("Key refused");
1324                         continue;
1325                     }
1326                     logevent("Received RSA challenge");
1327                     ssh1_read_bignum(pktin.body, &challenge);
1328                     {
1329                         char *agentreq, *q, *ret;
1330                         int len, retlen;
1331                         len = 1 + 4;   /* message type, bit count */
1332                         len += ssh1_bignum_length(key.exponent);
1333                         len += ssh1_bignum_length(key.modulus);
1334                         len += ssh1_bignum_length(challenge);
1335                         len += 16;     /* session id */
1336                         len += 4;      /* response format */
1337                         agentreq = malloc(4 + len);
1338                         PUT_32BIT(agentreq, len);
1339                         q = agentreq + 4;
1340                         *q++ = SSH_AGENTC_RSA_CHALLENGE;
1341                         PUT_32BIT(q, ssh1_bignum_bitcount(key.modulus));
1342                         q += 4;
1343                         q += ssh1_write_bignum(q, key.exponent);
1344                         q += ssh1_write_bignum(q, key.modulus);
1345                         q += ssh1_write_bignum(q, challenge);
1346                         memcpy(q, session_id, 16); q += 16;
1347                         PUT_32BIT(q, 1);   /* response format */
1348                         agent_query(agentreq, len+4, &ret, &retlen);
1349                         free(agentreq);
1350                         if (ret) {
1351                             if (ret[4] == SSH_AGENT_RSA_RESPONSE) {
1352                                 logevent("Sending Pageant's response");
1353                                 send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1354                                             PKT_DATA, ret+5, 16, PKT_END);
1355                                 free(ret);
1356                                 crWaitUntil(ispkt);
1357                                 if (pktin.type == SSH1_SMSG_SUCCESS) {
1358                                     logevent("Pageant's response accepted");
1359                                     if (flags & FLAG_VERBOSE) {
1360                                         c_write("Authenticated using RSA key \"",
1361                                                 29);
1362                                         c_write(commentp, commentlen);
1363                                         c_write("\" from agent\r\n", 14);
1364                                     }
1365                                     authed = TRUE;
1366                                 } else
1367                                     logevent("Pageant's response not accepted");
1368                             } else {
1369                                 logevent("Pageant failed to answer challenge");
1370                                 free(ret);
1371                             }
1372                         } else {
1373                             logevent("No reply received from Pageant");
1374                         }
1375                     }
1376                     freebn(key.exponent);
1377                     freebn(key.modulus);
1378                     freebn(challenge);
1379                     if (authed)
1380                         break;
1381                 }
1382             }
1383             if (authed)
1384                 break;
1385         }
1386         if (*cfg.keyfile && !tried_publickey)
1387             pwpkt_type = SSH1_CMSG_AUTH_RSA;
1388
1389         if (pktin.type == SSH1_SMSG_FAILURE &&
1390             cfg.try_tis_auth &&
1391             (supported_auths_mask & (1<<SSH1_AUTH_TIS))) {
1392             pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
1393             logevent("Requested TIS authentication");
1394             send_packet(SSH1_CMSG_AUTH_TIS, PKT_END);
1395             crWaitUntil(ispkt);
1396             if (pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
1397                 logevent("TIS authentication declined");
1398                 if (flags & FLAG_INTERACTIVE)
1399                     c_write("TIS authentication refused.\r\n", 29);
1400             } else {
1401                 int challengelen = ((pktin.body[0] << 24) |
1402                                     (pktin.body[1] << 16) |
1403                                     (pktin.body[2] << 8) |
1404                                     (pktin.body[3]));
1405                 logevent("Received TIS challenge");
1406                 if (challengelen > sizeof(prompt)-1)
1407                     challengelen = sizeof(prompt)-1;   /* prevent overrun */
1408                 memcpy(prompt, pktin.body+4, challengelen);
1409                 prompt[challengelen] = '\0';
1410             }
1411         }
1412         if (pktin.type == SSH1_SMSG_FAILURE &&
1413             cfg.try_tis_auth &&
1414             (supported_auths_mask & (1<<SSH1_AUTH_CCARD))) {
1415             pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
1416             logevent("Requested CryptoCard authentication");
1417             send_packet(SSH1_CMSG_AUTH_CCARD, PKT_END);
1418             crWaitUntil(ispkt);
1419             if (pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
1420                 logevent("CryptoCard authentication declined");
1421                 c_write("CryptoCard authentication refused.\r\n", 29);
1422             } else {
1423                 int challengelen = ((pktin.body[0] << 24) |
1424                                     (pktin.body[1] << 16) |
1425                                     (pktin.body[2] << 8) |
1426                                     (pktin.body[3]));
1427                 logevent("Received CryptoCard challenge");
1428                 if (challengelen > sizeof(prompt)-1)
1429                     challengelen = sizeof(prompt)-1;   /* prevent overrun */
1430                 memcpy(prompt, pktin.body+4, challengelen);
1431                 strncpy(prompt + challengelen, "\r\nResponse : ",
1432                         sizeof(prompt)-challengelen);
1433                 prompt[sizeof(prompt)-1] = '\0';
1434             }
1435         }
1436         if (pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
1437             sprintf(prompt, "%.90s@%.90s's password: ",
1438                     cfg.username, savedhost);
1439         }
1440         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1441             char *comment = NULL;
1442             if (flags & FLAG_VERBOSE)
1443                 c_write("Trying public key authentication.\r\n", 35);
1444             if (!rsakey_encrypted(cfg.keyfile, &comment)) {
1445                 if (flags & FLAG_VERBOSE)
1446                     c_write("No passphrase required.\r\n", 25);
1447                 goto tryauth;
1448             }
1449             sprintf(prompt, "Passphrase for key \"%.100s\": ", comment);
1450             free(comment);
1451         }
1452
1453         if (!(flags & FLAG_INTERACTIVE)) {
1454             if (!ssh_get_password(prompt, password, sizeof(password))) {
1455                 /*
1456                  * get_password failed to get a password (for
1457                  * example because one was supplied on the command
1458                  * line which has already failed to work).
1459                  * Terminate.
1460                  */
1461                 logevent("No more passwords to try");
1462                 ssh_state = SSH_STATE_CLOSED;
1463                 crReturn(1);
1464             }
1465         } else {
1466             c_write(prompt, strlen(prompt));
1467             pos = 0;
1468             ssh_send_ok = 1;
1469             while (pos >= 0) {
1470                 crWaitUntil(!ispkt);
1471                 while (inlen--) switch (c = *in++) {
1472                   case 10: case 13:
1473                     password[pos] = 0;
1474                     pos = -1;
1475                     break;
1476                   case 8: case 127:
1477                     if (pos > 0)
1478                         pos--;
1479                     break;
1480                   case 21: case 27:
1481                     pos = 0;
1482                     break;
1483                   case 3: case 4:
1484                     random_save_seed();
1485                     exit(0);
1486                     break;
1487                   default:
1488                     if (((c >= ' ' && c <= '~') ||
1489                          ((unsigned char)c >= 160)) && pos < sizeof(password))
1490                         password[pos++] = c;
1491                     break;
1492                 }
1493             }
1494             c_write("\r\n", 2);
1495         }
1496
1497         tryauth:
1498         if (pwpkt_type == SSH1_CMSG_AUTH_RSA) {
1499             /*
1500              * Try public key authentication with the specified
1501              * key file.
1502              */
1503             static struct RSAKey pubkey;
1504             static Bignum challenge, response;
1505             static int i;
1506             static unsigned char buffer[32];
1507
1508             tried_publickey = 1;
1509             i = loadrsakey(cfg.keyfile, &pubkey, password);
1510             if (i == 0) {
1511                 c_write("Couldn't load public key from ", 30);
1512                 c_write(cfg.keyfile, strlen(cfg.keyfile));
1513                 c_write(".\r\n", 3);
1514                 continue;              /* go and try password */
1515             }
1516             if (i == -1) {
1517                 c_write("Wrong passphrase.\r\n", 19);
1518                 tried_publickey = 0;
1519                 continue;              /* try again */
1520             }
1521
1522             /*
1523              * Send a public key attempt.
1524              */
1525             send_packet(SSH1_CMSG_AUTH_RSA,
1526                         PKT_BIGNUM, pubkey.modulus, PKT_END);
1527
1528             crWaitUntil(ispkt);
1529             if (pktin.type == SSH1_SMSG_FAILURE) {
1530                 c_write("Server refused our public key.\r\n", 32);
1531                 continue;              /* go and try password */
1532             }
1533             if (pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
1534                 bombout(("Bizarre response to offer of public key"));
1535                 crReturn(0);
1536             }
1537             ssh1_read_bignum(pktin.body, &challenge);
1538             response = rsadecrypt(challenge, &pubkey);
1539             freebn(pubkey.private_exponent);   /* burn the evidence */
1540
1541             for (i = 0; i < 32; i += 2) {
1542                 buffer[i] = response[16-i/2] >> 8;
1543                 buffer[i+1] = response[16-i/2] & 0xFF;
1544             }
1545
1546             MD5Init(&md5c);
1547             MD5Update(&md5c, buffer, 32);
1548             MD5Update(&md5c, session_id, 16);
1549             MD5Final(buffer, &md5c);
1550
1551             send_packet(SSH1_CMSG_AUTH_RSA_RESPONSE,
1552                         PKT_DATA, buffer, 16, PKT_END);
1553
1554             crWaitUntil(ispkt);
1555             if (pktin.type == SSH1_SMSG_FAILURE) {
1556                 if (flags & FLAG_VERBOSE)
1557                     c_write("Failed to authenticate with our public key.\r\n",
1558                             45);
1559                 continue;              /* go and try password */
1560             } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1561                 bombout(("Bizarre response to RSA authentication response"));
1562                 crReturn(0);
1563             }
1564
1565             break;                     /* we're through! */
1566         } else {
1567             send_packet(pwpkt_type, PKT_STR, password, PKT_END);
1568         }
1569         logevent("Sent password");
1570         memset(password, 0, strlen(password));
1571         crWaitUntil(ispkt);
1572         if (pktin.type == SSH1_SMSG_FAILURE) {
1573             if (flags & FLAG_VERBOSE)
1574                 c_write("Access denied\r\n", 15);
1575             logevent("Authentication refused");
1576         } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1577             logevent("Received disconnect request");
1578             ssh_state = SSH_STATE_CLOSED;
1579             crReturn(1);
1580         } else if (pktin.type != SSH1_SMSG_SUCCESS) {
1581             bombout(("Strange packet received, type %d", pktin.type));
1582             crReturn(0);
1583         }
1584     }
1585
1586     logevent("Authentication successful");
1587
1588     crFinish(1);
1589 }
1590
1591 static void ssh1_protocol(unsigned char *in, int inlen, int ispkt) {
1592     crBegin;
1593
1594     random_init();
1595
1596     while (!do_ssh1_login(in, inlen, ispkt)) {
1597         crReturnV;
1598     }
1599     if (ssh_state == SSH_STATE_CLOSED)
1600         crReturnV;
1601
1602     if (cfg.agentfwd && agent_exists()) {
1603         logevent("Requesting agent forwarding");
1604         send_packet(SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
1605         do { crReturnV; } while (!ispkt);
1606         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1607             bombout(("Protocol confusion"));
1608             crReturnV;
1609         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1610             logevent("Agent forwarding refused");
1611         } else
1612             logevent("Agent forwarding enabled");
1613     }
1614
1615     if (!cfg.nopty) {
1616         send_packet(SSH1_CMSG_REQUEST_PTY,
1617                     PKT_STR, cfg.termtype,
1618                     PKT_INT, rows, PKT_INT, cols,
1619                     PKT_INT, 0, PKT_INT, 0,
1620                     PKT_CHAR, 0,
1621                     PKT_END);
1622         ssh_state = SSH_STATE_INTERMED;
1623         do { crReturnV; } while (!ispkt);
1624         if (pktin.type != SSH1_SMSG_SUCCESS && pktin.type != SSH1_SMSG_FAILURE) {
1625             bombout(("Protocol confusion"));
1626             crReturnV;
1627         } else if (pktin.type == SSH1_SMSG_FAILURE) {
1628             c_write("Server refused to allocate pty\r\n", 32);
1629         }
1630         logevent("Allocated pty");
1631     }
1632
1633     if (*cfg.remote_cmd)
1634         send_packet(SSH1_CMSG_EXEC_CMD, PKT_STR, cfg.remote_cmd, PKT_END);
1635     else
1636         send_packet(SSH1_CMSG_EXEC_SHELL, PKT_END);
1637     logevent("Started session");
1638
1639     ssh_state = SSH_STATE_SESSION;
1640     if (size_needed)
1641         ssh_size();
1642
1643     ssh_send_ok = 1;
1644     ssh_channels = newtree234(ssh_channelcmp);
1645     begin_session();
1646     while (1) {
1647         crReturnV;
1648         if (ispkt) {
1649             if (pktin.type == SSH1_SMSG_STDOUT_DATA ||
1650                 pktin.type == SSH1_SMSG_STDERR_DATA) {
1651                 long len = GET_32BIT(pktin.body);
1652                 c_writedata(pktin.body+4, len);
1653             } else if (pktin.type == SSH1_MSG_DISCONNECT) {
1654                 ssh_state = SSH_STATE_CLOSED;
1655                 logevent("Received disconnect request");
1656             } else if (pktin.type == SSH1_SMSG_AGENT_OPEN) {
1657                 /* Remote side is trying to open a channel to talk to our
1658                  * agent. Give them back a local channel number. */
1659                 unsigned i = 1;
1660                 struct ssh_channel *c;
1661                 enum234 e;
1662                 for (c = first234(ssh_channels, &e); c; c = next234(&e)) {
1663                     if (c->localid > i)
1664                         break;         /* found a free number */
1665                     i = c->localid + 1;
1666                 }
1667                 c = malloc(sizeof(struct ssh_channel));
1668                 c->remoteid = GET_32BIT(pktin.body);
1669                 c->localid = i;
1670                 c->closes = 0;
1671                 c->type = SSH1_SMSG_AGENT_OPEN;   /* identify channel type */
1672                 c->u.a.lensofar = 0;
1673                 add234(ssh_channels, c);
1674                 send_packet(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
1675                             PKT_INT, c->remoteid, PKT_INT, c->localid,
1676                             PKT_END);
1677             } else if (pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
1678                        pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
1679                 /* Remote side closes a channel. */
1680                 unsigned i = GET_32BIT(pktin.body);
1681                 struct ssh_channel *c;
1682                 c = find234(ssh_channels, &i, ssh_channelfind);
1683                 if (c) {
1684                     int closetype;
1685                     closetype = (pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
1686                     send_packet(pktin.type, PKT_INT, c->remoteid, PKT_END);
1687                     c->closes |= closetype;
1688                     if (c->closes == 3) {
1689                         del234(ssh_channels, c);
1690                         free(c);
1691                     }
1692                 }
1693             } else if (pktin.type == SSH1_MSG_CHANNEL_DATA) {
1694                 /* Data sent down one of our channels. */
1695                 int i = GET_32BIT(pktin.body);
1696                 int len = GET_32BIT(pktin.body+4);
1697                 unsigned char *p = pktin.body+8;
1698                 struct ssh_channel *c;
1699                 c = find234(ssh_channels, &i, ssh_channelfind);
1700                 if (c) {
1701                     switch(c->type) {
1702                       case SSH1_SMSG_AGENT_OPEN:
1703                         /* Data for an agent message. Buffer it. */
1704                         while (len > 0) {
1705                             if (c->u.a.lensofar < 4) {
1706                                 int l = min(4 - c->u.a.lensofar, len);
1707                                 memcpy(c->u.a.msglen + c->u.a.lensofar, p, l);
1708                                 p += l; len -= l; c->u.a.lensofar += l;
1709                             }
1710                             if (c->u.a.lensofar == 4) {
1711                                 c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
1712                                 c->u.a.message = malloc(c->u.a.totallen);
1713                                 memcpy(c->u.a.message, c->u.a.msglen, 4);
1714                             }
1715                             if (c->u.a.lensofar >= 4 && len > 0) {
1716                                 int l = min(c->u.a.totallen - c->u.a.lensofar, len);
1717                                 memcpy(c->u.a.message + c->u.a.lensofar, p, l);
1718                                 p += l; len -= l; c->u.a.lensofar += l;
1719                             }
1720                             if (c->u.a.lensofar == c->u.a.totallen) {
1721                                 void *reply, *sentreply;
1722                                 int replylen;
1723                                 agent_query(c->u.a.message, c->u.a.totallen,
1724                                             &reply, &replylen);
1725                                 if (reply)
1726                                     sentreply = reply;
1727                                 else {
1728                                     /* Fake SSH_AGENT_FAILURE. */
1729                                     sentreply = "\0\0\0\1\5";
1730                                     replylen = 5;
1731                                 }
1732                                 send_packet(SSH1_MSG_CHANNEL_DATA,
1733                                             PKT_INT, c->remoteid,
1734                                             PKT_INT, replylen,
1735                                             PKT_DATA, sentreply, replylen,
1736                                             PKT_END);
1737                                 if (reply)
1738                                     free(reply);
1739                                 free(c->u.a.message);
1740                                 c->u.a.lensofar = 0;
1741                             }
1742                         }
1743                         break;
1744                     }
1745                 }                
1746             } else if (pktin.type == SSH1_SMSG_SUCCESS) {
1747                 /* may be from EXEC_SHELL on some servers */
1748             } else if (pktin.type == SSH1_SMSG_FAILURE) {
1749                 /* may be from EXEC_SHELL on some servers
1750                  * if no pty is available or in other odd cases. Ignore */
1751             } else if (pktin.type == SSH1_SMSG_EXIT_STATUS) {
1752                 send_packet(SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
1753             } else {
1754                 bombout(("Strange packet received: type %d", pktin.type));
1755                 crReturnV;
1756             }
1757         } else {
1758             send_packet(SSH1_CMSG_STDIN_DATA,
1759                         PKT_INT, inlen, PKT_DATA, in, inlen, PKT_END);
1760         }
1761     }
1762
1763     crFinishV;
1764 }
1765
1766 /*
1767  * Utility routine for decoding comma-separated strings in KEXINIT.
1768  */
1769 int in_commasep_string(char *needle, char *haystack, int haylen) {
1770     int needlen = strlen(needle);
1771     while (1) {
1772         /*
1773          * Is it at the start of the string?
1774          */
1775         if (haylen >= needlen &&       /* haystack is long enough */
1776             !memcmp(needle, haystack, needlen) &&    /* initial match */
1777             (haylen == needlen || haystack[needlen] == ',')
1778                                        /* either , or EOS follows */
1779             )
1780             return 1;
1781         /*
1782          * If not, search for the next comma and resume after that.
1783          * If no comma found, terminate.
1784          */
1785         while (haylen > 0 && *haystack != ',')
1786             haylen--, haystack++;
1787         if (haylen == 0)
1788             return 0;
1789         haylen--, haystack++;          /* skip over comma itself */
1790     }
1791 }
1792
1793 /*
1794  * SSH2 key creation method.
1795  */
1796 void ssh2_mkkey(Bignum K, char *H, char chr, char *keyspace) {
1797     SHA_State s;
1798     /* First 20 bytes. */
1799     SHA_Init(&s);
1800     sha_mpint(&s, K);
1801     SHA_Bytes(&s, H, 20);
1802     SHA_Bytes(&s, &chr, 1);
1803     SHA_Bytes(&s, H, 20);
1804     SHA_Final(&s, keyspace);
1805     /* Next 20 bytes. */
1806     SHA_Init(&s);
1807     sha_mpint(&s, K);
1808     SHA_Bytes(&s, H, 20);
1809     SHA_Bytes(&s, keyspace, 20);
1810     SHA_Final(&s, keyspace+20);
1811 }
1812
1813 /*
1814  * Handle the SSH2 transport layer.
1815  */
1816 static int do_ssh2_transport(unsigned char *in, int inlen, int ispkt)
1817 {
1818     static int i, len;
1819     static char *str;
1820     static Bignum e, f, K;
1821     static struct ssh_cipher *cscipher_tobe = NULL;
1822     static struct ssh_cipher *sccipher_tobe = NULL;
1823     static struct ssh_mac *csmac_tobe = NULL;
1824     static struct ssh_mac *scmac_tobe = NULL;
1825     static struct ssh_compress *cscomp_tobe = NULL;
1826     static struct ssh_compress *sccomp_tobe = NULL;
1827     static char *hostkeydata, *sigdata, *keystr;
1828     static int hostkeylen, siglen;
1829     static unsigned char exchange_hash[20];
1830     static unsigned char keyspace[40];
1831
1832     crBegin;
1833     random_init();
1834
1835     /*
1836      * Set up the preferred cipher.
1837      */
1838     if (cfg.cipher == CIPHER_BLOWFISH) {
1839         ciphers[0] = &ssh_blowfish_ssh2;
1840     } else if (cfg.cipher == CIPHER_DES) {
1841         logevent("Single DES not supported in SSH2; using 3DES");
1842         ciphers[0] = &ssh_3des_ssh2;
1843     } else if (cfg.cipher == CIPHER_3DES) {
1844         ciphers[0] = &ssh_3des_ssh2;
1845     } else {
1846         /* Shouldn't happen, but we do want to initialise to _something_. */
1847         ciphers[0] = &ssh_3des_ssh2;
1848     }
1849
1850     begin_key_exchange:
1851     /*
1852      * Construct and send our key exchange packet.
1853      */
1854     ssh2_pkt_init(SSH2_MSG_KEXINIT);
1855     for (i = 0; i < 16; i++)
1856         ssh2_pkt_addbyte((unsigned char)random_byte());
1857     /* List key exchange algorithms. */
1858     ssh2_pkt_addstring_start();
1859     for (i = 0; i < lenof(kex_algs); i++) {
1860         ssh2_pkt_addstring_str(kex_algs[i]->name);
1861         if (i < lenof(kex_algs)-1)
1862             ssh2_pkt_addstring_str(",");
1863     }
1864     /* List server host key algorithms. */
1865     ssh2_pkt_addstring_start();
1866     for (i = 0; i < lenof(hostkey_algs); i++) {
1867         ssh2_pkt_addstring_str(hostkey_algs[i]->name);
1868         if (i < lenof(hostkey_algs)-1)
1869             ssh2_pkt_addstring_str(",");
1870     }
1871     /* List client->server encryption algorithms. */
1872     ssh2_pkt_addstring_start();
1873     for (i = 0; i < lenof(ciphers); i++) {
1874         ssh2_pkt_addstring_str(ciphers[i]->name);
1875         if (i < lenof(ciphers)-1)
1876             ssh2_pkt_addstring_str(",");
1877     }
1878     /* List server->client encryption algorithms. */
1879     ssh2_pkt_addstring_start();
1880     for (i = 0; i < lenof(ciphers); i++) {
1881         ssh2_pkt_addstring_str(ciphers[i]->name);
1882         if (i < lenof(ciphers)-1)
1883             ssh2_pkt_addstring_str(",");
1884     }
1885     /* List client->server MAC algorithms. */
1886     ssh2_pkt_addstring_start();
1887     for (i = 0; i < lenof(macs); i++) {
1888         ssh2_pkt_addstring_str(macs[i]->name);
1889         if (i < lenof(macs)-1)
1890             ssh2_pkt_addstring_str(",");
1891     }
1892     /* List server->client MAC algorithms. */
1893     ssh2_pkt_addstring_start();
1894     for (i = 0; i < lenof(macs); i++) {
1895         ssh2_pkt_addstring_str(macs[i]->name);
1896         if (i < lenof(macs)-1)
1897             ssh2_pkt_addstring_str(",");
1898     }
1899     /* List client->server compression algorithms. */
1900     ssh2_pkt_addstring_start();
1901     for (i = 0; i < lenof(compressions); i++) {
1902         ssh2_pkt_addstring_str(compressions[i]->name);
1903         if (i < lenof(compressions)-1)
1904             ssh2_pkt_addstring_str(",");
1905     }
1906     /* List server->client compression algorithms. */
1907     ssh2_pkt_addstring_start();
1908     for (i = 0; i < lenof(compressions); i++) {
1909         ssh2_pkt_addstring_str(compressions[i]->name);
1910         if (i < lenof(compressions)-1)
1911             ssh2_pkt_addstring_str(",");
1912     }
1913     /* List client->server languages. Empty list. */
1914     ssh2_pkt_addstring_start();
1915     /* List server->client languages. Empty list. */
1916     ssh2_pkt_addstring_start();
1917     /* First KEX packet does _not_ follow, because we're not that brave. */
1918     ssh2_pkt_addbool(FALSE);
1919     /* Reserved. */
1920     ssh2_pkt_adduint32(0);
1921     sha_string(&exhash, pktout.data+5, pktout.length-5);
1922     ssh2_pkt_send();
1923
1924     if (!ispkt) crWaitUntil(ispkt);
1925     sha_string(&exhash, pktin.data+5, pktin.length-5);
1926
1927     /*
1928      * Now examine the other side's KEXINIT to see what we're up
1929      * to.
1930      */
1931     if (pktin.type != SSH2_MSG_KEXINIT) {
1932         bombout(("expected key exchange packet from server"));
1933         crReturn(0);
1934     }
1935     kex = NULL; hostkey = NULL; cscipher_tobe = NULL; sccipher_tobe = NULL;
1936     csmac_tobe = NULL; scmac_tobe = NULL; cscomp_tobe = NULL; sccomp_tobe = NULL;
1937     pktin.savedpos += 16;              /* skip garbage cookie */
1938     ssh2_pkt_getstring(&str, &len);    /* key exchange algorithms */
1939     for (i = 0; i < lenof(kex_algs); i++) {
1940         if (in_commasep_string(kex_algs[i]->name, str, len)) {
1941             kex = kex_algs[i];
1942             break;
1943         }
1944     }
1945     ssh2_pkt_getstring(&str, &len);    /* host key algorithms */
1946     for (i = 0; i < lenof(hostkey_algs); i++) {
1947         if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
1948             hostkey = hostkey_algs[i];
1949             break;
1950         }
1951     }
1952     ssh2_pkt_getstring(&str, &len);    /* client->server cipher */
1953     for (i = 0; i < lenof(ciphers); i++) {
1954         if (in_commasep_string(ciphers[i]->name, str, len)) {
1955             cscipher_tobe = ciphers[i];
1956             break;
1957         }
1958     }
1959     ssh2_pkt_getstring(&str, &len);    /* server->client cipher */
1960     for (i = 0; i < lenof(ciphers); i++) {
1961         if (in_commasep_string(ciphers[i]->name, str, len)) {
1962             sccipher_tobe = ciphers[i];
1963             break;
1964         }
1965     }
1966     ssh2_pkt_getstring(&str, &len);    /* client->server mac */
1967     for (i = 0; i < lenof(macs); i++) {
1968         if (in_commasep_string(macs[i]->name, str, len)) {
1969             csmac_tobe = macs[i];
1970             break;
1971         }
1972     }
1973     ssh2_pkt_getstring(&str, &len);    /* server->client mac */
1974     for (i = 0; i < lenof(macs); i++) {
1975         if (in_commasep_string(macs[i]->name, str, len)) {
1976             scmac_tobe = macs[i];
1977             break;
1978         }
1979     }
1980     ssh2_pkt_getstring(&str, &len);    /* client->server compression */
1981     for (i = 0; i < lenof(compressions); i++) {
1982         if (in_commasep_string(compressions[i]->name, str, len)) {
1983             cscomp_tobe = compressions[i];
1984             break;
1985         }
1986     }
1987     ssh2_pkt_getstring(&str, &len);    /* server->client compression */
1988     for (i = 0; i < lenof(compressions); i++) {
1989         if (in_commasep_string(compressions[i]->name, str, len)) {
1990             sccomp_tobe = compressions[i];
1991             break;
1992         }
1993     }
1994
1995     /*
1996      * Currently we only support Diffie-Hellman and DSS, so let's
1997      * bomb out if those aren't selected.
1998      */
1999     if (kex != &ssh_diffiehellman || hostkey != &ssh_dss) {
2000         bombout(("internal fault: chaos in SSH 2 transport layer"));
2001         crReturn(0);
2002     }
2003
2004     /*
2005      * Now we begin the fun. Generate and send e for Diffie-Hellman.
2006      */
2007     e = dh_create_e();
2008     ssh2_pkt_init(SSH2_MSG_KEXDH_INIT);
2009     ssh2_pkt_addmp(e);
2010     ssh2_pkt_send();
2011
2012     crWaitUntil(ispkt);
2013     if (pktin.type != SSH2_MSG_KEXDH_REPLY) {
2014         bombout(("expected key exchange packet from server"));
2015         crReturn(0);
2016     }
2017     ssh2_pkt_getstring(&hostkeydata, &hostkeylen);
2018     f = ssh2_pkt_getmp();
2019     ssh2_pkt_getstring(&sigdata, &siglen);
2020
2021     K = dh_find_K(f);
2022
2023     sha_string(&exhash, hostkeydata, hostkeylen);
2024     sha_mpint(&exhash, e);
2025     sha_mpint(&exhash, f);
2026     sha_mpint(&exhash, K);
2027     SHA_Final(&exhash, exchange_hash);
2028
2029 #if 0
2030     debug(("Exchange hash is:\r\n"));
2031     for (i = 0; i < 20; i++)
2032         debug((" %02x", exchange_hash[i]));
2033     debug(("\r\n"));
2034 #endif
2035
2036     hostkey->setkey(hostkeydata, hostkeylen);
2037     if (!hostkey->verifysig(sigdata, siglen, exchange_hash, 20)) {
2038         bombout(("Server failed host key check"));
2039         crReturn(0);
2040     }
2041
2042     /*
2043      * Expect SSH2_MSG_NEWKEYS from server.
2044      */
2045     crWaitUntil(ispkt);
2046     if (pktin.type != SSH2_MSG_NEWKEYS) {
2047         bombout(("expected new-keys packet from server"));
2048         crReturn(0);
2049     }
2050
2051     /*
2052      * Authenticate remote host: verify host key. (We've already
2053      * checked the signature of the exchange hash.)
2054      */
2055     keystr = hostkey->fmtkey();
2056     verify_ssh_host_key(savedhost, keystr);
2057     free(keystr);
2058
2059     /*
2060      * Send SSH2_MSG_NEWKEYS.
2061      */
2062     ssh2_pkt_init(SSH2_MSG_NEWKEYS);
2063     ssh2_pkt_send();
2064
2065     /*
2066      * Create and initialise session keys.
2067      */
2068     cscipher = cscipher_tobe;
2069     sccipher = sccipher_tobe;
2070     csmac = csmac_tobe;
2071     scmac = scmac_tobe;
2072     cscomp = cscomp_tobe;
2073     sccomp = sccomp_tobe;
2074     /*
2075      * Set IVs after keys.
2076      */
2077     ssh2_mkkey(K, exchange_hash, 'C', keyspace); cscipher->setcskey(keyspace);
2078     ssh2_mkkey(K, exchange_hash, 'D', keyspace); cscipher->setsckey(keyspace);
2079     ssh2_mkkey(K, exchange_hash, 'A', keyspace); cscipher->setcsiv(keyspace);
2080     ssh2_mkkey(K, exchange_hash, 'B', keyspace); sccipher->setsciv(keyspace);
2081     ssh2_mkkey(K, exchange_hash, 'E', keyspace); csmac->setcskey(keyspace);
2082     ssh2_mkkey(K, exchange_hash, 'F', keyspace); scmac->setsckey(keyspace);
2083
2084     /*
2085      * Now we're encrypting. Begin returning 1 to the protocol main
2086      * function so that other things can run on top of the
2087      * transport. If we ever see a KEXINIT, we must go back to the
2088      * start.
2089      */
2090     do {
2091         crReturn(1);
2092     } while (!(ispkt && pktin.type == SSH2_MSG_KEXINIT));
2093     goto begin_key_exchange;
2094
2095     crFinish(1);
2096 }
2097
2098 /*
2099  * Handle the SSH2 userauth and connection layers.
2100  */
2101 static void do_ssh2_authconn(unsigned char *in, int inlen, int ispkt)
2102 {
2103     static unsigned long remote_winsize;
2104     static unsigned long remote_maxpkt;
2105
2106     crBegin;
2107
2108     /*
2109      * Request userauth protocol, and await a response to it.
2110      */
2111     ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
2112     ssh2_pkt_addstring("ssh-userauth");
2113     ssh2_pkt_send();
2114     crWaitUntilV(ispkt);
2115     if (pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
2116         bombout(("Server refused user authentication protocol"));
2117         crReturnV;
2118     }
2119
2120     /*
2121      * FIXME: currently we support only password authentication.
2122      * (This places us technically in violation of the SSH2 spec.
2123      * We must fix this.)
2124      */
2125     while (1) {
2126         /*
2127          * Get a username and a password.
2128          */
2129         static char username[100];
2130         static char password[100];
2131         static int pos = 0;
2132         static char c;
2133
2134         if ((flags & FLAG_INTERACTIVE) && !*cfg.username) {
2135             c_write("login as: ", 10);
2136             ssh_send_ok = 1;
2137             while (pos >= 0) {
2138                 crWaitUntilV(!ispkt);
2139                 while (inlen--) switch (c = *in++) {
2140                   case 10: case 13:
2141                     username[pos] = 0;
2142                     pos = -1;
2143                     break;
2144                   case 8: case 127:
2145                     if (pos > 0) {
2146                         c_write("\b \b", 3);
2147                         pos--;
2148                     }
2149                     break;
2150                   case 21: case 27:
2151                     while (pos > 0) {
2152                         c_write("\b \b", 3);
2153                         pos--;
2154                     }
2155                     break;
2156                   case 3: case 4:
2157                     random_save_seed();
2158                     exit(0);
2159                     break;
2160                   default:
2161                     if (((c >= ' ' && c <= '~') ||
2162                          ((unsigned char)c >= 160)) && pos < 40) {
2163                         username[pos++] = c;
2164                         c_write(&c, 1);
2165                     }
2166                     break;
2167                 }
2168             }
2169             c_write("\r\n", 2);
2170             username[strcspn(username, "\n\r")] = '\0';
2171         } else {
2172             char stuff[200];
2173             strncpy(username, cfg.username, 99);
2174             username[99] = '\0';
2175             if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
2176                 sprintf(stuff, "Using username \"%s\".\r\n", username);
2177                 c_write(stuff, strlen(stuff));
2178             }
2179         }
2180
2181         if (!(flags & FLAG_INTERACTIVE)) {
2182             char prompt[200];
2183             sprintf(prompt, "%.90s@%.90s's password: ", cfg.username, savedhost);
2184             if (!ssh_get_password(prompt, password, sizeof(password))) {
2185                 /*
2186                  * get_password failed to get a password (for
2187                  * example because one was supplied on the command
2188                  * line which has already failed to work).
2189                  * Terminate.
2190                  */
2191                 logevent("No more passwords to try");
2192                 ssh_state = SSH_STATE_CLOSED;
2193                 crReturnV;
2194             }
2195         } else {
2196             c_write("password: ", 10);
2197             ssh_send_ok = 1;
2198
2199             pos = 0;
2200             while (pos >= 0) {
2201                 crWaitUntilV(!ispkt);
2202                 while (inlen--) switch (c = *in++) {
2203                   case 10: case 13:
2204                     password[pos] = 0;
2205                     pos = -1;
2206                     break;
2207                   case 8: case 127:
2208                     if (pos > 0)
2209                         pos--;
2210                     break;
2211                   case 21: case 27:
2212                     pos = 0;
2213                     break;
2214                   case 3: case 4:
2215                     random_save_seed();
2216                     exit(0);
2217                     break;
2218                   default:
2219                     if (((c >= ' ' && c <= '~') ||
2220                          ((unsigned char)c >= 160)) && pos < 40)
2221                         password[pos++] = c;
2222                     break;
2223                 }
2224             }
2225             c_write("\r\n", 2);
2226         }
2227
2228         ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
2229         ssh2_pkt_addstring(username);
2230         ssh2_pkt_addstring("ssh-connection");   /* service requested */
2231         ssh2_pkt_addstring("password");
2232         ssh2_pkt_addbool(FALSE);
2233         ssh2_pkt_addstring(password);
2234         ssh2_pkt_send();
2235
2236         crWaitUntilV(ispkt);
2237         if (pktin.type != SSH2_MSG_USERAUTH_SUCCESS) {
2238             c_write("Access denied\r\n", 15);
2239             logevent("Authentication refused");
2240         } else
2241             break;
2242     }
2243
2244     /*
2245      * Now we're authenticated for the connection protocol. The
2246      * connection protocol will automatically have started at this
2247      * point; there's no need to send SERVICE_REQUEST.
2248      */
2249
2250     /*
2251      * So now create a channel with a session in it.
2252      */
2253     mainchan = malloc(sizeof(struct ssh_channel));
2254     mainchan->localid = 100;           /* as good as any */
2255     ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
2256     ssh2_pkt_addstring("session");
2257     ssh2_pkt_adduint32(mainchan->localid);
2258     ssh2_pkt_adduint32(0x7FFFFFFFUL);  /* our window size */
2259     ssh2_pkt_adduint32(0x4000UL);  /* our max pkt size */
2260     ssh2_pkt_send();
2261     crWaitUntilV(ispkt);
2262     if (pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
2263         bombout(("Server refused to open a session"));
2264         crReturnV;
2265         /* FIXME: error data comes back in FAILURE packet */
2266     }
2267     if (ssh2_pkt_getuint32() != mainchan->localid) {
2268         bombout(("Server's channel confirmation cited wrong channel"));
2269         crReturnV;
2270     }
2271     mainchan->remoteid = ssh2_pkt_getuint32();
2272     mainchan->u.v2.remwindow = ssh2_pkt_getuint32();
2273     mainchan->u.v2.remmaxpkt = ssh2_pkt_getuint32();
2274     mainchan->u.v2.outbuffer = NULL;
2275     mainchan->u.v2.outbuflen = mainchan->u.v2.outbufsize = 0;
2276     logevent("Opened channel for session");
2277
2278     /*
2279      * Now allocate a pty for the session.
2280      */
2281     if (!cfg.nopty) {
2282         ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2283         ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2284         ssh2_pkt_addstring("pty-req");
2285         ssh2_pkt_addbool(1);           /* want reply */
2286         ssh2_pkt_addstring(cfg.termtype);
2287         ssh2_pkt_adduint32(cols);
2288         ssh2_pkt_adduint32(rows);
2289         ssh2_pkt_adduint32(0);         /* pixel width */
2290         ssh2_pkt_adduint32(0);         /* pixel height */
2291         ssh2_pkt_addstring_start();
2292         ssh2_pkt_addstring_data("\0", 1);/* TTY_OP_END, no special options */
2293         ssh2_pkt_send();
2294
2295         do {
2296             crWaitUntilV(ispkt);
2297             if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2298                 /* FIXME: be able to handle other channels here */
2299                 if (ssh2_pkt_getuint32() != mainchan->localid)
2300                     continue;          /* wrong channel */
2301                 mainchan->u.v2.remwindow += ssh2_pkt_getuint32();
2302             }
2303         } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2304
2305         if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2306             if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2307                 bombout(("Server got confused by pty request"));
2308                 crReturnV;
2309             }
2310             c_write("Server refused to allocate pty\r\n", 32);
2311         } else {
2312             logevent("Allocated pty");
2313         }
2314     }
2315
2316     /*
2317      * Start a shell or a remote command.
2318      */
2319     ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
2320     ssh2_pkt_adduint32(mainchan->remoteid); /* recipient channel */
2321     if (*cfg.remote_cmd) {
2322         ssh2_pkt_addstring("exec");
2323         ssh2_pkt_addbool(1);           /* want reply */
2324         ssh2_pkt_addstring(cfg.remote_cmd);
2325     } else {
2326         ssh2_pkt_addstring("shell");
2327         ssh2_pkt_addbool(1);           /* want reply */
2328     }
2329     ssh2_pkt_send();
2330     do {
2331         crWaitUntilV(ispkt);
2332         if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2333             /* FIXME: be able to handle other channels here */
2334             if (ssh2_pkt_getuint32() != mainchan->localid)
2335                 continue;          /* wrong channel */
2336             mainchan->u.v2.remwindow += ssh2_pkt_getuint32();
2337         }
2338     } while (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2339     if (pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
2340         if (pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
2341             bombout(("Server got confused by shell/command request"));
2342             crReturnV;
2343         }
2344         bombout(("Server refused to start a shell/command"));
2345         crReturnV;
2346     } else {
2347         logevent("Started a shell/command");
2348     }
2349
2350     /*
2351      * Transfer data!
2352      */
2353     ssh_send_ok = 1;
2354     begin_session();
2355     while (1) {
2356         static int try_send;
2357         crReturnV;
2358         try_send = FALSE;
2359         if (ispkt) {
2360             if (pktin.type == SSH2_MSG_CHANNEL_DATA ||
2361                 pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
2362                 char *data;
2363                 int length;
2364                 /* FIXME: be able to handle other channels here */
2365                 if (ssh2_pkt_getuint32() != mainchan->localid)
2366                     continue;          /* wrong channel */
2367                 if (pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
2368                     ssh2_pkt_getuint32() != SSH2_EXTENDED_DATA_STDERR)
2369                     continue;          /* extended but not stderr */
2370                 ssh2_pkt_getstring(&data, &length);
2371                 if (data) {
2372                     c_writedata(data, length);
2373                     /*
2374                      * Enlarge the window again at the remote side,
2375                      * just in case it ever runs down and they fail
2376                      * to send us any more data.
2377                      */
2378                     ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
2379                     ssh2_pkt_adduint32(mainchan->remoteid);
2380                     ssh2_pkt_adduint32(length);
2381                     ssh2_pkt_send();
2382                 }
2383             } else if (pktin.type == SSH2_MSG_DISCONNECT) {
2384                 ssh_state = SSH_STATE_CLOSED;
2385                 logevent("Received disconnect message");
2386             } else if (pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
2387                 continue;              /* exit status et al; ignore (FIXME?) */
2388             } else if (pktin.type == SSH2_MSG_CHANNEL_EOF) {
2389                 continue;              /* remote sends EOF; ignore */
2390             } else if (pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
2391                 /* FIXME: be able to handle other channels here */
2392                 if (ssh2_pkt_getuint32() != mainchan->localid)
2393                     continue;          /* wrong channel */
2394                 ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
2395                 ssh2_pkt_adduint32(mainchan->remoteid);
2396                 ssh2_pkt_send();
2397                 /* FIXME: mark the channel as closed */
2398                 if (1 /* FIXME: "all channels are closed" */) {
2399                     logevent("All channels closed. Disconnecting");
2400                     ssh2_pkt_init(SSH2_MSG_DISCONNECT);
2401                     ssh2_pkt_send();
2402                 }
2403                 continue;              /* remote sends close; ignore (FIXME) */
2404             } else if (pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
2405                 /* FIXME: be able to handle other channels here */
2406                 if (ssh2_pkt_getuint32() != mainchan->localid)
2407                     continue;          /* wrong channel */
2408                 mainchan->u.v2.remwindow += ssh2_pkt_getuint32();
2409                 try_send = TRUE;
2410             } else {
2411                 bombout(("Strange packet received: type %d", pktin.type));
2412                 crReturnV;
2413             }
2414         } else {
2415             /*
2416              * We have spare data. Add it to the channel buffer.
2417              */
2418             if (mainchan->u.v2.outbufsize <
2419                 mainchan->u.v2.outbuflen + inlen) {
2420                 mainchan->u.v2.outbufsize =
2421                     mainchan->u.v2.outbuflen + inlen + 1024;
2422                 mainchan->u.v2.outbuffer = srealloc(mainchan->u.v2.outbuffer,
2423                                                     mainchan->u.v2.outbufsize);
2424             }
2425             memcpy(mainchan->u.v2.outbuffer + mainchan->u.v2.outbuflen,
2426                    in, inlen);
2427             mainchan->u.v2.outbuflen += inlen;
2428             try_send = TRUE;
2429         }
2430         if (try_send) {
2431             /*
2432              * Try to send data on the channel if we can. (FIXME:
2433              * on _all_ channels.)
2434              */
2435             while (mainchan->u.v2.remwindow > 0 &&
2436                    mainchan->u.v2.outbuflen > 0) {
2437                 unsigned len = mainchan->u.v2.remwindow;
2438                 if (len > mainchan->u.v2.outbuflen)
2439                     len = mainchan->u.v2.outbuflen;
2440                 if (len > mainchan->u.v2.remmaxpkt)
2441                     len = mainchan->u.v2.remmaxpkt;
2442                 ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
2443                 ssh2_pkt_adduint32(mainchan->remoteid);
2444                 ssh2_pkt_addstring_start();
2445                 ssh2_pkt_addstring_data(mainchan->u.v2.outbuffer, len);
2446                 ssh2_pkt_send();
2447                 mainchan->u.v2.outbuflen -= len;
2448                 memmove(mainchan->u.v2.outbuffer, mainchan->u.v2.outbuffer+len,
2449                         mainchan->u.v2.outbuflen);
2450                 mainchan->u.v2.remwindow -= len;
2451             }
2452         }
2453     }
2454
2455     crFinishV;
2456 }
2457
2458 /*
2459  * Handle the top-level SSH2 protocol.
2460  */
2461 static void ssh2_protocol(unsigned char *in, int inlen, int ispkt)
2462 {
2463     if (do_ssh2_transport(in, inlen, ispkt) == 0)
2464         return;
2465     do_ssh2_authconn(in, inlen, ispkt);
2466 }
2467
2468 /*
2469  * Called to set up the connection. Will arrange for WM_NETEVENT
2470  * messages to be passed to the specified window, whose window
2471  * procedure should then call telnet_msg().
2472  *
2473  * Returns an error message, or NULL on success.
2474  */
2475 static char *ssh_init (HWND hwnd, char *host, int port, char **realhost) {
2476     char *p;
2477         
2478 #ifdef MSCRYPTOAPI
2479     if(crypto_startup() == 0)
2480         return "Microsoft high encryption pack not installed!";
2481 #endif
2482
2483     p = connect_to_host(host, port, realhost);
2484     if (p != NULL)
2485         return p;
2486
2487     if (!do_ssh_init())
2488         return "Protocol initialisation error";
2489
2490     if (hwnd && WSAAsyncSelect (s, hwnd, WM_NETEVENT, FD_READ | FD_CLOSE) == SOCKET_ERROR)
2491         switch (WSAGetLastError()) {
2492           case WSAENETDOWN: return "Network is down";
2493           default: return "WSAAsyncSelect(): unknown error";
2494         }
2495
2496     return NULL;
2497 }
2498
2499 /*
2500  * Process a WM_NETEVENT message. Will return 0 if the connection
2501  * has closed, or <0 for a socket error.
2502  */
2503 static int ssh_msg (WPARAM wParam, LPARAM lParam) {
2504     int ret;
2505     char buf[256];
2506
2507     /*
2508      * Because reading less than the whole of the available pending
2509      * data can generate an FD_READ event, we need to allow for the
2510      * possibility that FD_READ may arrive with FD_CLOSE already in
2511      * the queue; so it's possible that we can get here even with s
2512      * invalid. If so, we return 1 and don't worry about it.
2513      */
2514     if (s == INVALID_SOCKET)
2515         return 1;
2516
2517     if (WSAGETSELECTERROR(lParam) != 0) {
2518         closesocket(s);
2519         s = INVALID_SOCKET;
2520         return -WSAGETSELECTERROR(lParam);
2521     }
2522
2523     switch (WSAGETSELECTEVENT(lParam)) {
2524       case FD_READ:
2525       case FD_CLOSE:
2526         ret = recv(s, buf, sizeof(buf), 0);
2527         if (ret < 0 && WSAGetLastError() == WSAEWOULDBLOCK)
2528             return 1;
2529         if (ret < 0) {                 /* any _other_ error */
2530             closesocket(s);
2531             s = INVALID_SOCKET;
2532             return -10000-WSAGetLastError();
2533         }
2534         if (ret == 0) {
2535             s = INVALID_SOCKET;
2536             return 0;
2537         }
2538         ssh_gotdata (buf, ret);
2539         if (ssh_state == SSH_STATE_CLOSED) {
2540             closesocket(s);
2541             s = INVALID_SOCKET;
2542             return 0;
2543         }
2544         return 1;
2545     }
2546     return 1;                          /* shouldn't happen, but WTF */
2547 }
2548
2549 /*
2550  * Called to send data down the Telnet connection.
2551  */
2552 static void ssh_send (char *buf, int len) {
2553     if (s == INVALID_SOCKET)
2554         return;
2555
2556     ssh_protocol(buf, len, 0);
2557 }
2558
2559 /*
2560  * Called to set the size of the window from Telnet's POV.
2561  */
2562 static void ssh_size(void) {
2563     switch (ssh_state) {
2564       case SSH_STATE_BEFORE_SIZE:
2565       case SSH_STATE_CLOSED:
2566         break;                         /* do nothing */
2567       case SSH_STATE_INTERMED:
2568         size_needed = TRUE;            /* buffer for later */
2569         break;
2570       case SSH_STATE_SESSION:
2571         if (!cfg.nopty) {
2572             send_packet(SSH1_CMSG_WINDOW_SIZE,
2573                         PKT_INT, rows, PKT_INT, cols,
2574                         PKT_INT, 0, PKT_INT, 0, PKT_END);
2575         }
2576     }
2577 }
2578
2579 /*
2580  * Send Telnet special codes. TS_EOF is useful for `plink', so you
2581  * can send an EOF and collect resulting output (e.g. `plink
2582  * hostname sort').
2583  */
2584 static void ssh_special (Telnet_Special code) {
2585     if (code == TS_EOF) {
2586         if (ssh_version == 1) {
2587             send_packet(SSH1_CMSG_EOF, PKT_END);
2588         } else {
2589             ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
2590             ssh2_pkt_adduint32(mainchan->remoteid);
2591             ssh2_pkt_send();
2592         }
2593         logevent("Sent EOF message");
2594     } else {
2595         /* do nothing */
2596     }
2597 }
2598
2599 static SOCKET ssh_socket(void) { return s; }
2600
2601 static int ssh_sendok(void) { return ssh_send_ok; }
2602
2603 Backend ssh_backend = {
2604     ssh_init,
2605     ssh_msg,
2606     ssh_send,
2607     ssh_size,
2608     ssh_special,
2609     ssh_socket,
2610     ssh_sendok
2611 };