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